text stringlengths 54 60.6k |
|---|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtornt.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:52:03 $
*
* 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 _FMTORNT_HXX
#define _FMTORNT_HXX
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _SWTYPES_HXX //autogen
#include <swtypes.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
#ifndef _ORNTENUM_HXX
#include <orntenum.hxx>
#endif
#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif
class IntlWrapper;
#define IVER_VERTORIENT_REL ((USHORT)0x0001)
class SW_DLLPUBLIC SwFmtVertOrient: public SfxPoolItem
{
SwTwips nYPos; //Enthaelt _immer_ die aktuelle RelPos.
SwVertOrient eOrient;
SwRelationOrient eRelation;
public:
TYPEINFO();
SwFmtVertOrient( SwTwips nY = 0, SwVertOrient eVert = VERT_NONE,
SwRelationOrient eRel = PRTAREA );
inline SwFmtVertOrient &operator=( const SwFmtVertOrient &rCpy );
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
SwVertOrient GetVertOrient() const { return eOrient; }
SwRelationOrient GetRelationOrient() const { return eRelation; }
void SetVertOrient( SwVertOrient eNew ) { eOrient = eNew; }
void SetRelationOrient( SwRelationOrient eNew ) { eRelation = eNew; }
SwTwips GetPos() const { return nYPos; }
void SetPos( SwTwips nNew ) { nYPos = nNew; }
SwTwips GetPosConvertedToSw31( const SvxULSpaceItem *pULSpace ) const;
SwTwips GetPosConvertedFromSw31( const SvxULSpaceItem *pULSpace ) const;
};
//SwFmtHoriOrient, wie und woran orientiert --
// sich der FlyFrm in der Hoizontalen ----------
#define IVER_HORIORIENT_TOGGLE ((USHORT)0x0001)
#define IVER_HORIORIENT_REL ((USHORT)0x0002)
class SW_DLLPUBLIC SwFmtHoriOrient: public SfxPoolItem
{
SwTwips nXPos; //Enthaelt _immer_ die aktuelle RelPos.
SwHoriOrient eOrient;
SwRelationOrient eRelation;
BOOL bPosToggle : 1; // auf geraden Seiten Position spiegeln
public:
TYPEINFO();
SwFmtHoriOrient( SwTwips nX = 0, SwHoriOrient eHori = HORI_NONE,
SwRelationOrient eRel = PRTAREA, BOOL bPos = FALSE );
inline SwFmtHoriOrient &operator=( const SwFmtHoriOrient &rCpy );
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
SwHoriOrient GetHoriOrient() const { return eOrient; }
SwRelationOrient GetRelationOrient() const { return eRelation; }
void SetHoriOrient( SwHoriOrient eNew ) { eOrient = eNew; }
void SetRelationOrient( SwRelationOrient eNew ) { eRelation = eNew; }
SwTwips GetPos() const { return nXPos; }
void SetPos( SwTwips nNew ) { nXPos = nNew; }
SwTwips GetPosConvertedToSw31( const SvxLRSpaceItem *pLRSpace ) const;
SwTwips GetPosConvertedFromSw31( const SvxLRSpaceItem *pLRSpace ) const;
BOOL IsPosToggle() const { return bPosToggle; }
void SetPosToggle( BOOL bNew ) { bPosToggle = bNew; }
};
inline SwFmtVertOrient &SwFmtVertOrient::operator=( const SwFmtVertOrient &rCpy )
{
nYPos = rCpy.GetPos();
eOrient = rCpy.GetVertOrient();
eRelation = rCpy.GetRelationOrient();
return *this;
}
inline SwFmtHoriOrient &SwFmtHoriOrient::operator=( const SwFmtHoriOrient &rCpy )
{
nXPos = rCpy.GetPos();
eOrient = rCpy.GetHoriOrient();
eRelation = rCpy.GetRelationOrient();
bPosToggle = rCpy.IsPosToggle();
return *this;
}
inline const SwFmtVertOrient &SwAttrSet::GetVertOrient(BOOL bInP) const
{ return (const SwFmtVertOrient&)Get( RES_VERT_ORIENT,bInP); }
inline const SwFmtHoriOrient &SwAttrSet::GetHoriOrient(BOOL bInP) const
{ return (const SwFmtHoriOrient&)Get( RES_HORI_ORIENT,bInP); }
inline const SwFmtVertOrient &SwFmt::GetVertOrient(BOOL bInP) const
{ return aSet.GetVertOrient(bInP); }
inline const SwFmtHoriOrient &SwFmt::GetHoriOrient(BOOL bInP) const
{ return aSet.GetHoriOrient(bInP); }
#endif
<commit_msg>INTEGRATION: CWS os94 (1.10.732); FILE MERGED 2007/03/12 08:07:30 os 1.10.732.1: #i75235# unused methods removed<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtornt.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2007-04-25 08:54:48 $
*
* 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 _FMTORNT_HXX
#define _FMTORNT_HXX
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _SWTYPES_HXX //autogen
#include <swtypes.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
#ifndef _ORNTENUM_HXX
#include <orntenum.hxx>
#endif
#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif
class IntlWrapper;
#define IVER_VERTORIENT_REL ((USHORT)0x0001)
class SW_DLLPUBLIC SwFmtVertOrient: public SfxPoolItem
{
SwTwips nYPos; //Enthaelt _immer_ die aktuelle RelPos.
SwVertOrient eOrient;
SwRelationOrient eRelation;
public:
TYPEINFO();
SwFmtVertOrient( SwTwips nY = 0, SwVertOrient eVert = VERT_NONE,
SwRelationOrient eRel = PRTAREA );
inline SwFmtVertOrient &operator=( const SwFmtVertOrient &rCpy );
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
SwVertOrient GetVertOrient() const { return eOrient; }
SwRelationOrient GetRelationOrient() const { return eRelation; }
void SetVertOrient( SwVertOrient eNew ) { eOrient = eNew; }
void SetRelationOrient( SwRelationOrient eNew ) { eRelation = eNew; }
SwTwips GetPos() const { return nYPos; }
void SetPos( SwTwips nNew ) { nYPos = nNew; }
};
//SwFmtHoriOrient, wie und woran orientiert --
// sich der FlyFrm in der Hoizontalen ----------
#define IVER_HORIORIENT_TOGGLE ((USHORT)0x0001)
#define IVER_HORIORIENT_REL ((USHORT)0x0002)
class SW_DLLPUBLIC SwFmtHoriOrient: public SfxPoolItem
{
SwTwips nXPos; //Enthaelt _immer_ die aktuelle RelPos.
SwHoriOrient eOrient;
SwRelationOrient eRelation;
BOOL bPosToggle : 1; // auf geraden Seiten Position spiegeln
public:
TYPEINFO();
SwFmtHoriOrient( SwTwips nX = 0, SwHoriOrient eHori = HORI_NONE,
SwRelationOrient eRel = PRTAREA, BOOL bPos = FALSE );
inline SwFmtHoriOrient &operator=( const SwFmtHoriOrient &rCpy );
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
SwHoriOrient GetHoriOrient() const { return eOrient; }
SwRelationOrient GetRelationOrient() const { return eRelation; }
void SetHoriOrient( SwHoriOrient eNew ) { eOrient = eNew; }
void SetRelationOrient( SwRelationOrient eNew ) { eRelation = eNew; }
SwTwips GetPos() const { return nXPos; }
void SetPos( SwTwips nNew ) { nXPos = nNew; }
BOOL IsPosToggle() const { return bPosToggle; }
void SetPosToggle( BOOL bNew ) { bPosToggle = bNew; }
};
inline SwFmtVertOrient &SwFmtVertOrient::operator=( const SwFmtVertOrient &rCpy )
{
nYPos = rCpy.GetPos();
eOrient = rCpy.GetVertOrient();
eRelation = rCpy.GetRelationOrient();
return *this;
}
inline SwFmtHoriOrient &SwFmtHoriOrient::operator=( const SwFmtHoriOrient &rCpy )
{
nXPos = rCpy.GetPos();
eOrient = rCpy.GetHoriOrient();
eRelation = rCpy.GetRelationOrient();
bPosToggle = rCpy.IsPosToggle();
return *this;
}
inline const SwFmtVertOrient &SwAttrSet::GetVertOrient(BOOL bInP) const
{ return (const SwFmtVertOrient&)Get( RES_VERT_ORIENT,bInP); }
inline const SwFmtHoriOrient &SwAttrSet::GetHoriOrient(BOOL bInP) const
{ return (const SwFmtHoriOrient&)Get( RES_HORI_ORIENT,bInP); }
inline const SwFmtVertOrient &SwFmt::GetVertOrient(BOOL bInP) const
{ return aSet.GetVertOrient(bInP); }
inline const SwFmtHoriOrient &SwFmt::GetHoriOrient(BOOL bInP) const
{ return aSet.GetHoriOrient(bInP); }
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2013 Canonical Ltd.
* Copyright 2011 Wolfgang Koller - http://www.gofg.at/
*
* 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 "cordova.h"
#include <QtGui>
#include <QApplication>
#include <QQuickView>
#include <QQuickItem>
#include <QQmlContext>
Cordova::Cordova(const QDir &wwwDir, QQuickItem *item, QObject *parent)
: QObject(parent), _item(item), _www(wwwDir),
_config(_www.absoluteFilePath("../config.xml")) {
qDebug() << "Work directory: " << _www.absolutePath();
if (_config.content().contains(QRegExp("^(http://)"))) {
_mainUrl = QString(_config.content());
} else if (!_www.exists(_config.content())) {
qCritical() << _config.content() << "does not exist";
}
_mainUrl = QUrl::fromUserInput(_www.absoluteFilePath(_config.content()))
.toString();
qDebug() << "Main URL: " << _mainUrl;
}
void Cordova::appLoaded() {
initPlugins();
for (QSharedPointer<CPlugin> &plugin: _plugins) {
plugin->onAppLoaded();
}
}
QString Cordova::get_app_dir() {
return _www.absolutePath();
}
struct Splash {
double rating;
QString path;
};
QString Cordova::getSplashscreenPath() {
double ratio = (double)_item->width() / _item->height();
QDir dir(get_app_dir());
if (!dir.cd("splashscreen"))
return "";
QList<Splash> images;
for (QFileInfo info: dir.entryInfoList()) {
QImage image(info.absoluteFilePath());
if (image.isNull())
continue;
Splash t;
t.path = info.absoluteFilePath();
t.rating = std::abs((image.width() / (double)_item->width()) * ((image.width() / image.height()) / ratio) - 1);
images.push_back(t);
}
std::min_element(images.begin(), images.end(), [](Splash &f, Splash &s) {
return f.rating < s.rating;
});
if (!images.empty())
return images.first().path;
return "";
}
const CordovaInternal::Config& Cordova::config() const {
return _config;}
void Cordova::initPlugins() {
QList<QDir> searchPath = {get_app_dir()};
_plugins.clear();
for (QDir pluginsDir: searchPath) {
for (const QString &fileName: pluginsDir.entryList(QDir::Files)) {
QString path = pluginsDir.absoluteFilePath(fileName);
qDebug() << "Testing" << path;
if (!QLibrary::isLibrary(path))
continue;
CordovaGetPluginInstances loader = (CordovaGetPluginInstances) QLibrary::resolve(path, "cordovaGetPluginInstances");
if (!loader) {
qCritical() << "Missing cordovaGetPluginInstances symbol in" << path;
continue;
}
auto plugins = (*loader)(this);
for (QSharedPointer<CPlugin> plugin: plugins) {
qDebug() << "Enable plugin" << plugin->fullName();
emit pluginWantsToBeAdded(plugin->fullName(), plugin.data(), plugin->shortName());
}
_plugins += plugins;
}
}
}
void Cordova::loadFinished(bool ok) {
Q_UNUSED(ok)
initPlugins();
}
void Cordova::execQML(const QString &src) {
emit qmlExecNeeded(src);
}
void Cordova::execJS(const QString &js) {
emit javaScriptExecNeeded(js);
}
QString Cordova::mainUrl() const {
return _mainUrl;
}
QObject *Cordova::topLevelEventsReceiver() {
return dynamic_cast<QQuickWindow*>(_item->window());
}
QQuickItem *Cordova::rootObject() {
return _item->parentItem();
}
void Cordova::setTitle(const QString &title) {
dynamic_cast<QQuickWindow*>(_item->window())->setTitle(title);
}
void Cordova::pushViewState(const QString &state) {
if (_states.empty()) {
rootObject()->setState(state);
}
_states.push_front(state);
}
void Cordova::popViewState(const QString &state) {
if (!_states.removeOne(state))
qDebug() << "WARNING: incorrect view states order";
if (_states.empty()) {
rootObject()->setState("main");
} else {
rootObject()->setState(_states.front());
}
}
<commit_msg>set mainUrl when the file exists<commit_after>/*
* Copyright 2013 Canonical Ltd.
* Copyright 2011 Wolfgang Koller - http://www.gofg.at/
*
* 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 "cordova.h"
#include <QtGui>
#include <QApplication>
#include <QQuickView>
#include <QQuickItem>
#include <QQmlContext>
Cordova::Cordova(const QDir &wwwDir, QQuickItem *item, QObject *parent)
: QObject(parent), _item(item), _www(wwwDir),
_config(_www.absoluteFilePath("../config.xml")) {
qDebug() << "Work directory: " << _www.absolutePath();
if (_config.content().contains(QRegExp("^(http://)"))) {
_mainUrl = QString(_config.content());
} else if (!_www.exists(_config.content())) {
qCritical() << _config.content() << "does not exist";
} else {
_mainUrl = QUrl::fromUserInput(_www.absoluteFilePath(_config.content()))
.toString();
}
qDebug() << "Main URL: " << _mainUrl;
}
void Cordova::appLoaded() {
initPlugins();
for (QSharedPointer<CPlugin> &plugin: _plugins) {
plugin->onAppLoaded();
}
}
QString Cordova::get_app_dir() {
return _www.absolutePath();
}
struct Splash {
double rating;
QString path;
};
QString Cordova::getSplashscreenPath() {
double ratio = (double)_item->width() / _item->height();
QDir dir(get_app_dir());
if (!dir.cd("splashscreen"))
return "";
QList<Splash> images;
for (QFileInfo info: dir.entryInfoList()) {
QImage image(info.absoluteFilePath());
if (image.isNull())
continue;
Splash t;
t.path = info.absoluteFilePath();
t.rating = std::abs((image.width() / (double)_item->width()) * ((image.width() / image.height()) / ratio) - 1);
images.push_back(t);
}
std::min_element(images.begin(), images.end(), [](Splash &f, Splash &s) {
return f.rating < s.rating;
});
if (!images.empty())
return images.first().path;
return "";
}
const CordovaInternal::Config& Cordova::config() const {
return _config;}
void Cordova::initPlugins() {
QList<QDir> searchPath = {get_app_dir()};
_plugins.clear();
for (QDir pluginsDir: searchPath) {
for (const QString &fileName: pluginsDir.entryList(QDir::Files)) {
QString path = pluginsDir.absoluteFilePath(fileName);
qDebug() << "Testing" << path;
if (!QLibrary::isLibrary(path))
continue;
CordovaGetPluginInstances loader = (CordovaGetPluginInstances) QLibrary::resolve(path, "cordovaGetPluginInstances");
if (!loader) {
qCritical() << "Missing cordovaGetPluginInstances symbol in" << path;
continue;
}
auto plugins = (*loader)(this);
for (QSharedPointer<CPlugin> plugin: plugins) {
qDebug() << "Enable plugin" << plugin->fullName();
emit pluginWantsToBeAdded(plugin->fullName(), plugin.data(), plugin->shortName());
}
_plugins += plugins;
}
}
}
void Cordova::loadFinished(bool ok) {
Q_UNUSED(ok)
initPlugins();
}
void Cordova::execQML(const QString &src) {
emit qmlExecNeeded(src);
}
void Cordova::execJS(const QString &js) {
emit javaScriptExecNeeded(js);
}
QString Cordova::mainUrl() const {
return _mainUrl;
}
QObject *Cordova::topLevelEventsReceiver() {
return dynamic_cast<QQuickWindow*>(_item->window());
}
QQuickItem *Cordova::rootObject() {
return _item->parentItem();
}
void Cordova::setTitle(const QString &title) {
dynamic_cast<QQuickWindow*>(_item->window())->setTitle(title);
}
void Cordova::pushViewState(const QString &state) {
if (_states.empty()) {
rootObject()->setState(state);
}
_states.push_front(state);
}
void Cordova::popViewState(const QString &state) {
if (!_states.removeOne(state))
qDebug() << "WARNING: incorrect view states order";
if (_states.empty()) {
rootObject()->setState("main");
} else {
rootObject()->setState(_states.front());
}
}
<|endoftext|> |
<commit_before><commit_msg>Delete rtest_ac_normalize.cpp<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <csimsbw.h>
#include "csim/model.h"
#include "csim/executable_functions.h"
#include "csim/error_codes.h"
#include "xmlutils.h"
#define CSIM_SUCCESS 0
#define CSIM_FAILED 1
int csim_loadCellml(const char* modelString)
{
return CSIM_SUCCESS;
}
int csim_reset()
{
return CSIM_SUCCESS;
}
int csim_setValue(const char* variableId, double value)
{
return CSIM_SUCCESS;
}
int csim_getVariables(char** *outArray, int *outLength)
{
return CSIM_SUCCESS;
}
int csim_getValues(double* *outArray, int *outLength)
{
return CSIM_SUCCESS;
}
int csim_steadyState()
{
return CSIM_SUCCESS;
}
int csim_simulate(
double initialTime, double startTime, double endTime, int numSteps,
double** *outMatrix, int* outRows, int *outCols)
{
return CSIM_SUCCESS;
}
int csim_oneStep(double step)
{
return CSIM_SUCCESS;
}
int csim_setTolerances(double aTol, double rTol, int maxSteps)
{
return CSIM_SUCCESS;
}
int csim_sayHello(char* *outString, int *outLength)
{
*outLength = 11;
*outString = strdup("Hello World");
return CSIM_SUCCESS;
}
int csim_serialiseCellmlFromUrl(const char* url,
char* *outString, int *outLength)
{
XmlDoc xml;
xml.parseDocument(url);
std::string model = xml.dumpString();
*outLength = model.length();
*outString = strdup(model.c_str());
return CSIM_SUCCESS;
}
//! Frees a vector previously allocated by this library.
void csim_freeVector(void* vector)
{
}
//! Frees a matrix previously allocated by this library.
void csim_freeMatrix(void** matrix, int numRows)
{
}
<commit_msg>fix compile error picked up in linux<commit_after>#include <iostream>
#include <vector>
#include <cstring>
#include <csimsbw.h>
#include "csim/model.h"
#include "csim/executable_functions.h"
#include "csim/error_codes.h"
#include "xmlutils.h"
#define CSIM_SUCCESS 0
#define CSIM_FAILED 1
int csim_loadCellml(const char* modelString)
{
return CSIM_SUCCESS;
}
int csim_reset()
{
return CSIM_SUCCESS;
}
int csim_setValue(const char* variableId, double value)
{
return CSIM_SUCCESS;
}
int csim_getVariables(char** *outArray, int *outLength)
{
return CSIM_SUCCESS;
}
int csim_getValues(double* *outArray, int *outLength)
{
return CSIM_SUCCESS;
}
int csim_steadyState()
{
return CSIM_SUCCESS;
}
int csim_simulate(
double initialTime, double startTime, double endTime, int numSteps,
double** *outMatrix, int* outRows, int *outCols)
{
return CSIM_SUCCESS;
}
int csim_oneStep(double step)
{
return CSIM_SUCCESS;
}
int csim_setTolerances(double aTol, double rTol, int maxSteps)
{
return CSIM_SUCCESS;
}
int csim_sayHello(char* *outString, int *outLength)
{
*outLength = 11;
*outString = strdup("Hello World");
return CSIM_SUCCESS;
}
int csim_serialiseCellmlFromUrl(const char* url,
char* *outString, int *outLength)
{
XmlDoc xml;
xml.parseDocument(url);
std::string model = xml.dumpString();
*outLength = model.length();
*outString = strdup(model.c_str());
return CSIM_SUCCESS;
}
//! Frees a vector previously allocated by this library.
void csim_freeVector(void* vector)
{
}
//! Frees a matrix previously allocated by this library.
void csim_freeMatrix(void** matrix, int numRows)
{
}
<|endoftext|> |
<commit_before>#include <string.h>
#include <v8.h>
#include <node.h>
#include <node_events.h>
#include "macros.h"
#include "database.h"
#include "statement.h"
using namespace node_sqlite3;
Persistent<FunctionTemplate> Database::constructor_template;
void Database::Init(Handle<Object> target) {
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
constructor_template = Persistent<FunctionTemplate>::New(t);
constructor_template->Inherit(EventEmitter::constructor_template);
constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
constructor_template->SetClassName(String::NewSymbol("Database"));
NODE_SET_PROTOTYPE_METHOD(constructor_template, "close", Close);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "exec", Exec);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "serialize", Serialize);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "parallelize", Parallelize);
target->Set(String::NewSymbol("Database"),
constructor_template->GetFunction());
}
void Database::Process() {
if (!open && locked && !queue.empty()) {
EXCEPTION(String::New("Database handle is closed"), SQLITE_MISUSE, exception);
Local<Value> argv[] = { exception };
bool called = false;
// Call all callbacks with the error object.
while (!queue.empty()) {
Call* call = queue.front();
if (!call->baton->callback.IsEmpty() && call->baton->callback->IsFunction()) {
TRY_CATCH_CALL(handle_, call->baton->callback, 1, argv);
called = true;
}
queue.pop();
// We don't call the actual callback, so we have to make sure that
// the baton gets destroyed.
delete call->baton;
delete call;
}
// When we couldn't call a callback function, emit an error on the
// Database object.
if (!called) {
Local<Value> args[] = { String::NewSymbol("error"), exception };
EMIT_EVENT(handle_, 2, args);
}
return;
}
while (open && (!locked || pending == 0) && !queue.empty()) {
Call* call = queue.front();
if (call->exclusive && pending > 0) {
break;
}
queue.pop();
locked = call->exclusive;
call->callback(call->baton);
delete call;
if (locked) break;
}
}
void Database::Schedule(EIO_Callback callback, Baton* baton, bool exclusive) {
if (!open && locked) {
EXCEPTION(String::New("Database is closed"), SQLITE_MISUSE, exception);
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
Local<Value> argv[] = { exception };
TRY_CATCH_CALL(handle_, baton->callback, 1, argv);
}
else {
Local<Value> argv[] = { String::NewSymbol("error"), exception };
EMIT_EVENT(handle_, 2, argv);
}
return;
}
if (!open || ((locked || exclusive || serialize) && pending > 0)) {
queue.push(new Call(callback, baton, exclusive || serialize));
}
else {
locked = exclusive;
callback(baton);
}
}
Handle<Value> Database::New(const Arguments& args) {
HandleScope scope;
if (!Database::HasInstance(args.This())) {
return ThrowException(Exception::TypeError(
String::New("Use the new operator to create new Database objects"))
);
}
REQUIRE_ARGUMENT_STRING(0, filename);
int pos = 1;
int mode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
if (args.Length() >= pos && args[pos]->IsInt32()) {
mode = args[pos++]->Int32Value();
}
Local<Function> callback;
if (args.Length() >= pos && args[pos]->IsFunction()) {
callback = Local<Function>::Cast(args[pos++]);
}
Database* db = new Database();
db->Wrap(args.This());
args.This()->Set(String::NewSymbol("filename"), args[0]->ToString(), ReadOnly);
args.This()->Set(String::NewSymbol("mode"), Integer::New(mode), ReadOnly);
// Start opening the database.
OpenBaton* baton = new OpenBaton(db, callback, *filename, SQLITE_OPEN_FULLMUTEX | mode);
EIO_BeginOpen(baton);
return args.This();
}
void Database::EIO_BeginOpen(Baton* baton) {
eio_custom(EIO_Open, EIO_PRI_DEFAULT, EIO_AfterOpen, baton);
}
int Database::EIO_Open(eio_req *req) {
OpenBaton* baton = static_cast<OpenBaton*>(req->data);
Database* db = baton->db;
baton->status = sqlite3_open_v2(
baton->filename.c_str(),
&db->handle,
baton->mode,
NULL
);
if (baton->status != SQLITE_OK) {
baton->message = std::string(sqlite3_errmsg(db->handle));
db->handle = NULL;
}
return 0;
}
int Database::EIO_AfterOpen(eio_req *req) {
HandleScope scope;
OpenBaton* baton = static_cast<OpenBaton*>(req->data);
Database* db = baton->db;
Local<Value> argv[1];
if (baton->status != SQLITE_OK) {
EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);
argv[0] = exception;
}
else {
db->open = true;
argv[0] = Local<Value>::New(Null());
}
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
else if (!db->open) {
Local<Value> args[] = { String::NewSymbol("error"), argv[0] };
EMIT_EVENT(db->handle_, 2, args);
}
if (db->open) {
Local<Value> args[] = { String::NewSymbol("open") };
EMIT_EVENT(db->handle_, 1, args);
db->Process();
}
delete baton;
return 0;
}
Handle<Value> Database::Close(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
Baton* baton = new Baton(db, callback);
db->Schedule(EIO_BeginClose, baton, true);
return args.This();
}
void Database::EIO_BeginClose(Baton* baton) {
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->handle);
assert(baton->db->pending == 0);
eio_custom(EIO_Close, EIO_PRI_DEFAULT, EIO_AfterClose, baton);
}
int Database::EIO_Close(eio_req *req) {
Baton* baton = static_cast<Baton*>(req->data);
Database* db = baton->db;
baton->status = sqlite3_close(db->handle);
if (baton->status != SQLITE_OK) {
baton->message = std::string(sqlite3_errmsg(db->handle));
}
else {
db->handle = NULL;
}
return 0;
}
int Database::EIO_AfterClose(eio_req *req) {
HandleScope scope;
Baton* baton = static_cast<Baton*>(req->data);
Database* db = baton->db;
Local<Value> argv[1];
if (baton->status != SQLITE_OK) {
EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);
argv[0] = exception;
}
else {
db->open = false;
// Leave db->locked to indicate that this db object has reached
// the end of its life.
argv[0] = Local<Value>::New(Null());
}
// Fire callbacks.
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
else if (db->open) {
Local<Value> args[] = { String::NewSymbol("error"), argv[0] };
EMIT_EVENT(db->handle_, 2, args);
}
assert(baton->db->locked);
assert(!baton->db->open);
assert(!baton->db->handle);
assert(baton->db->pending == 0);
if (!db->open) {
Local<Value> args[] = { String::NewSymbol("close"), argv[0] };
EMIT_EVENT(db->handle_, 1, args);
db->Process();
}
delete baton;
return 0;
}
Handle<Value> Database::Serialize(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
bool before = db->serialize;
db->serialize = true;
if (!callback.IsEmpty() && callback->IsFunction()) {
TRY_CATCH_CALL(args.This(), callback, 0, NULL);
db->serialize = before;
}
db->Process();
return args.This();
}
Handle<Value> Database::Parallelize(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
bool before = db->serialize;
db->serialize = false;
if (!callback.IsEmpty() && callback->IsFunction()) {
TRY_CATCH_CALL(args.This(), callback, 0, NULL);
db->serialize = before;
}
db->Process();
return args.This();
}
Handle<Value> Database::Exec(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
REQUIRE_ARGUMENT_STRING(0, sql);
OPTIONAL_ARGUMENT_FUNCTION(1, callback);
Baton* baton = new ExecBaton(db, callback, *sql);
db->Schedule(EIO_BeginExec, baton, true);
return args.This();
}
void Database::EIO_BeginExec(Baton* baton) {
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->handle);
assert(baton->db->pending == 0);
eio_custom(EIO_Exec, EIO_PRI_DEFAULT, EIO_AfterExec, baton);
}
int Database::EIO_Exec(eio_req *req) {
ExecBaton* baton = static_cast<ExecBaton*>(req->data);
char* message = NULL;
baton->status = sqlite3_exec(
baton->db->handle,
baton->sql.c_str(),
NULL,
NULL,
&message
);
if (baton->status != SQLITE_OK && message != NULL) {
baton->message = std::string(message);
sqlite3_free(message);
}
return 0;
}
int Database::EIO_AfterExec(eio_req *req) {
HandleScope scope;
Baton* baton = static_cast<ExecBaton*>(req->data);
Database* db = baton->db;
if (baton->status != SQLITE_OK) {
EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
Local<Value> argv[] = { exception };
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
else {
Local<Value> args[] = { String::NewSymbol("error"), exception };
EMIT_EVENT(db->handle_, 2, args);
}
}
else if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
Local<Value> argv[] = { Local<Value>::New(Null()) };
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
db->Process();
delete baton;
return 0;
}
/**
* Override this so that we can properly close the database when this object
* gets garbage collected.
*/
void Database::Wrap(Handle<Object> handle) {
assert(handle_.IsEmpty());
assert(handle->InternalFieldCount() > 0);
handle_ = Persistent<Object>::New(handle);
handle_->SetPointerInInternalField(0, this);
handle_.MakeWeak(this, Destruct);
}
inline void Database::MakeWeak (void) {
handle_.MakeWeak(this, Destruct);
}
void Database::Unref() {
assert(!handle_.IsEmpty());
assert(!handle_.IsWeak());
assert(refs_ > 0);
if (--refs_ == 0) { MakeWeak(); }
}
void Database::Destruct(Persistent<Value> value, void *data) {
Database* db = static_cast<Database*>(data);
if (db->handle) {
eio_custom(EIO_Destruct, EIO_PRI_DEFAULT, EIO_AfterDestruct, db);
ev_ref(EV_DEFAULT_UC);
}
else {
delete db;
}
}
int Database::EIO_Destruct(eio_req *req) {
Database* db = static_cast<Database*>(req->data);
sqlite3_close(db->handle);
db->handle = NULL;
return 0;
}
int Database::EIO_AfterDestruct(eio_req *req) {
Database* db = static_cast<Database*>(req->data);
ev_unref(EV_DEFAULT_UC);
delete db;
return 0;
}
<commit_msg>make sure we delete the entire baton<commit_after>#include <string.h>
#include <v8.h>
#include <node.h>
#include <node_events.h>
#include "macros.h"
#include "database.h"
#include "statement.h"
using namespace node_sqlite3;
Persistent<FunctionTemplate> Database::constructor_template;
void Database::Init(Handle<Object> target) {
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
constructor_template = Persistent<FunctionTemplate>::New(t);
constructor_template->Inherit(EventEmitter::constructor_template);
constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
constructor_template->SetClassName(String::NewSymbol("Database"));
NODE_SET_PROTOTYPE_METHOD(constructor_template, "close", Close);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "exec", Exec);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "serialize", Serialize);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "parallelize", Parallelize);
target->Set(String::NewSymbol("Database"),
constructor_template->GetFunction());
}
void Database::Process() {
if (!open && locked && !queue.empty()) {
EXCEPTION(String::New("Database handle is closed"), SQLITE_MISUSE, exception);
Local<Value> argv[] = { exception };
bool called = false;
// Call all callbacks with the error object.
while (!queue.empty()) {
Call* call = queue.front();
if (!call->baton->callback.IsEmpty() && call->baton->callback->IsFunction()) {
TRY_CATCH_CALL(handle_, call->baton->callback, 1, argv);
called = true;
}
queue.pop();
// We don't call the actual callback, so we have to make sure that
// the baton gets destroyed.
delete call->baton;
delete call;
}
// When we couldn't call a callback function, emit an error on the
// Database object.
if (!called) {
Local<Value> args[] = { String::NewSymbol("error"), exception };
EMIT_EVENT(handle_, 2, args);
}
return;
}
while (open && (!locked || pending == 0) && !queue.empty()) {
Call* call = queue.front();
if (call->exclusive && pending > 0) {
break;
}
queue.pop();
locked = call->exclusive;
call->callback(call->baton);
delete call;
if (locked) break;
}
}
void Database::Schedule(EIO_Callback callback, Baton* baton, bool exclusive) {
if (!open && locked) {
EXCEPTION(String::New("Database is closed"), SQLITE_MISUSE, exception);
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
Local<Value> argv[] = { exception };
TRY_CATCH_CALL(handle_, baton->callback, 1, argv);
}
else {
Local<Value> argv[] = { String::NewSymbol("error"), exception };
EMIT_EVENT(handle_, 2, argv);
}
return;
}
if (!open || ((locked || exclusive || serialize) && pending > 0)) {
queue.push(new Call(callback, baton, exclusive || serialize));
}
else {
locked = exclusive;
callback(baton);
}
}
Handle<Value> Database::New(const Arguments& args) {
HandleScope scope;
if (!Database::HasInstance(args.This())) {
return ThrowException(Exception::TypeError(
String::New("Use the new operator to create new Database objects"))
);
}
REQUIRE_ARGUMENT_STRING(0, filename);
int pos = 1;
int mode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
if (args.Length() >= pos && args[pos]->IsInt32()) {
mode = args[pos++]->Int32Value();
}
Local<Function> callback;
if (args.Length() >= pos && args[pos]->IsFunction()) {
callback = Local<Function>::Cast(args[pos++]);
}
Database* db = new Database();
db->Wrap(args.This());
args.This()->Set(String::NewSymbol("filename"), args[0]->ToString(), ReadOnly);
args.This()->Set(String::NewSymbol("mode"), Integer::New(mode), ReadOnly);
// Start opening the database.
OpenBaton* baton = new OpenBaton(db, callback, *filename, SQLITE_OPEN_FULLMUTEX | mode);
EIO_BeginOpen(baton);
return args.This();
}
void Database::EIO_BeginOpen(Baton* baton) {
eio_custom(EIO_Open, EIO_PRI_DEFAULT, EIO_AfterOpen, baton);
}
int Database::EIO_Open(eio_req *req) {
OpenBaton* baton = static_cast<OpenBaton*>(req->data);
Database* db = baton->db;
baton->status = sqlite3_open_v2(
baton->filename.c_str(),
&db->handle,
baton->mode,
NULL
);
if (baton->status != SQLITE_OK) {
baton->message = std::string(sqlite3_errmsg(db->handle));
db->handle = NULL;
}
return 0;
}
int Database::EIO_AfterOpen(eio_req *req) {
HandleScope scope;
OpenBaton* baton = static_cast<OpenBaton*>(req->data);
Database* db = baton->db;
Local<Value> argv[1];
if (baton->status != SQLITE_OK) {
EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);
argv[0] = exception;
}
else {
db->open = true;
argv[0] = Local<Value>::New(Null());
}
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
else if (!db->open) {
Local<Value> args[] = { String::NewSymbol("error"), argv[0] };
EMIT_EVENT(db->handle_, 2, args);
}
if (db->open) {
Local<Value> args[] = { String::NewSymbol("open") };
EMIT_EVENT(db->handle_, 1, args);
db->Process();
}
delete baton;
return 0;
}
Handle<Value> Database::Close(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
Baton* baton = new Baton(db, callback);
db->Schedule(EIO_BeginClose, baton, true);
return args.This();
}
void Database::EIO_BeginClose(Baton* baton) {
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->handle);
assert(baton->db->pending == 0);
eio_custom(EIO_Close, EIO_PRI_DEFAULT, EIO_AfterClose, baton);
}
int Database::EIO_Close(eio_req *req) {
Baton* baton = static_cast<Baton*>(req->data);
Database* db = baton->db;
baton->status = sqlite3_close(db->handle);
if (baton->status != SQLITE_OK) {
baton->message = std::string(sqlite3_errmsg(db->handle));
}
else {
db->handle = NULL;
}
return 0;
}
int Database::EIO_AfterClose(eio_req *req) {
HandleScope scope;
Baton* baton = static_cast<Baton*>(req->data);
Database* db = baton->db;
Local<Value> argv[1];
if (baton->status != SQLITE_OK) {
EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);
argv[0] = exception;
}
else {
db->open = false;
// Leave db->locked to indicate that this db object has reached
// the end of its life.
argv[0] = Local<Value>::New(Null());
}
// Fire callbacks.
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
else if (db->open) {
Local<Value> args[] = { String::NewSymbol("error"), argv[0] };
EMIT_EVENT(db->handle_, 2, args);
}
assert(baton->db->locked);
assert(!baton->db->open);
assert(!baton->db->handle);
assert(baton->db->pending == 0);
if (!db->open) {
Local<Value> args[] = { String::NewSymbol("close"), argv[0] };
EMIT_EVENT(db->handle_, 1, args);
db->Process();
}
delete baton;
return 0;
}
Handle<Value> Database::Serialize(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
bool before = db->serialize;
db->serialize = true;
if (!callback.IsEmpty() && callback->IsFunction()) {
TRY_CATCH_CALL(args.This(), callback, 0, NULL);
db->serialize = before;
}
db->Process();
return args.This();
}
Handle<Value> Database::Parallelize(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
bool before = db->serialize;
db->serialize = false;
if (!callback.IsEmpty() && callback->IsFunction()) {
TRY_CATCH_CALL(args.This(), callback, 0, NULL);
db->serialize = before;
}
db->Process();
return args.This();
}
Handle<Value> Database::Exec(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
REQUIRE_ARGUMENT_STRING(0, sql);
OPTIONAL_ARGUMENT_FUNCTION(1, callback);
Baton* baton = new ExecBaton(db, callback, *sql);
db->Schedule(EIO_BeginExec, baton, true);
return args.This();
}
void Database::EIO_BeginExec(Baton* baton) {
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->handle);
assert(baton->db->pending == 0);
eio_custom(EIO_Exec, EIO_PRI_DEFAULT, EIO_AfterExec, baton);
}
int Database::EIO_Exec(eio_req *req) {
ExecBaton* baton = static_cast<ExecBaton*>(req->data);
char* message = NULL;
baton->status = sqlite3_exec(
baton->db->handle,
baton->sql.c_str(),
NULL,
NULL,
&message
);
if (baton->status != SQLITE_OK && message != NULL) {
baton->message = std::string(message);
sqlite3_free(message);
}
return 0;
}
int Database::EIO_AfterExec(eio_req *req) {
HandleScope scope;
ExecBaton* baton = static_cast<ExecBaton*>(req->data);
Database* db = baton->db;
if (baton->status != SQLITE_OK) {
EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
Local<Value> argv[] = { exception };
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
else {
Local<Value> args[] = { String::NewSymbol("error"), exception };
EMIT_EVENT(db->handle_, 2, args);
}
}
else if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
Local<Value> argv[] = { Local<Value>::New(Null()) };
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
db->Process();
delete baton;
return 0;
}
/**
* Override this so that we can properly close the database when this object
* gets garbage collected.
*/
void Database::Wrap(Handle<Object> handle) {
assert(handle_.IsEmpty());
assert(handle->InternalFieldCount() > 0);
handle_ = Persistent<Object>::New(handle);
handle_->SetPointerInInternalField(0, this);
handle_.MakeWeak(this, Destruct);
}
inline void Database::MakeWeak (void) {
handle_.MakeWeak(this, Destruct);
}
void Database::Unref() {
assert(!handle_.IsEmpty());
assert(!handle_.IsWeak());
assert(refs_ > 0);
if (--refs_ == 0) { MakeWeak(); }
}
void Database::Destruct(Persistent<Value> value, void *data) {
Database* db = static_cast<Database*>(data);
if (db->handle) {
eio_custom(EIO_Destruct, EIO_PRI_DEFAULT, EIO_AfterDestruct, db);
ev_ref(EV_DEFAULT_UC);
}
else {
delete db;
}
}
int Database::EIO_Destruct(eio_req *req) {
Database* db = static_cast<Database*>(req->data);
sqlite3_close(db->handle);
db->handle = NULL;
return 0;
}
int Database::EIO_AfterDestruct(eio_req *req) {
Database* db = static_cast<Database*>(req->data);
ev_unref(EV_DEFAULT_UC);
delete db;
return 0;
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <sqlite3.h>
#include <nan.h>
#include "macros.h"
#include "database.h"
namespace NODE_SQLITE3_PLUS_DATABASE {
int WRITE_MODE = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
int READ_MODE = SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX;
v8::PropertyAttribute FROZEN = static_cast<v8::PropertyAttribute>(v8::DontDelete | v8::ReadOnly);
enum STATE {CONNECTING, READY, DONE};
bool CONSTRUCTING_PRIVILEGES = false;
class Database : public Nan::ObjectWrap {
public:
Database(char*);
~Database();
static NAN_MODULE_INIT(Init);
friend class OpenWorker;
friend class CloseWorker;
private:
static CONSTRUCTOR(constructor);
static NAN_METHOD(New);
static NAN_GETTER(OpenGetter);
static NAN_METHOD(Close);
static NAN_METHOD(PrepareTransaction);
char* filename;
sqlite3* readHandle;
sqlite3* writeHandle;
STATE state;
};
class Transaction : public Nan::ObjectWrap {
public:
Transaction();
~Transaction();
static void Init();
friend class Database;
private:
static CONSTRUCTOR(constructor);
static NAN_METHOD(New);
bool dead;
};
class OpenWorker : public Nan::AsyncWorker {
public:
OpenWorker(Database*);
~OpenWorker();
void Execute();
void HandleOKCallback();
void HandleErrorCallback();
private:
Database* db;
};
class CloseWorker : public Nan::AsyncWorker {
public:
CloseWorker(Database*, bool);
~CloseWorker();
void Execute();
void HandleOKCallback();
void HandleErrorCallback();
private:
Database* db;
bool doNothing;
};
Database::Database(char* filename) : Nan::ObjectWrap(),
filename(filename),
readHandle(NULL),
writeHandle(NULL),
state(CONNECTING) {}
Database::~Database() {
state = DONE;
sqlite3_close(readHandle);
sqlite3_close(writeHandle);
readHandle = NULL;
writeHandle = NULL;
free(filename);
filename = NULL;
}
NAN_MODULE_INIT(Database::Init) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New("Database").ToLocalChecked());
Nan::SetPrototypeMethod(t, "disconnect", Close);
Nan::SetPrototypeMethod(t, "begin", PrepareTransaction);
Nan::SetAccessor(t->InstanceTemplate(), Nan::New("connected").ToLocalChecked(), OpenGetter);
constructor.Reset(Nan::GetFunction(t).ToLocalChecked());
Nan::Set(target, Nan::New("Database").ToLocalChecked(),
Nan::GetFunction(t).ToLocalChecked());
}
CONSTRUCTOR(Database::constructor);
NAN_METHOD(Database::New) {
REQUIRE_ARGUMENTS(1);
if (!info.IsConstructCall()) {
v8::Local<v8::Value> args[1] = {info[0]};
v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);
info.GetReturnValue().Set(cons->NewInstance(1, args));
} else {
REQUIRE_ARGUMENT_STRING(0, filename);
Database* db = new Database(RAW_STRING(filename));
db->Wrap(info.This());
db->Ref();
AsyncQueueWorker(new OpenWorker(db));
info.GetReturnValue().Set(info.This());
}
}
NAN_GETTER(Database::OpenGetter) {
Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This());
info.GetReturnValue().Set(db->state == READY);
}
NAN_METHOD(Database::Close) {
Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This());
if (db->state != DONE) {
db->Ref();
// --
// This should wait in queue for all pending transactions to finish. (writes AND reads).
// This should be invoked right away if there are no pending transactions (which will
// always be the case if it's still connecting). db->state == DONE simply means that it
// was READY when Close was invoked, and therefore should be treated equally, as shown
// below.
AsyncQueueWorker(new CloseWorker(db, db->state == CONNECTING));
// --
db->state = DONE;
}
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(Database::PrepareTransaction) {
OPTIONAL_ARGUMENT_STRING(0, source);
v8::Local<v8::Function> cons = Nan::New<v8::Function>(Transaction::constructor);
CONSTRUCTING_PRIVILEGES = true;
v8::Local<v8::Object> transaction = cons->NewInstance(0, NULL);
CONSTRUCTING_PRIVILEGES = false;
Nan::ForceSet(transaction, Nan::New("database").ToLocalChecked(), info.This(), FROZEN);
if (source->Length()) {
// Invoke .and() to append a statement.
}
info.GetReturnValue().Set(transaction);
}
Transaction::Transaction() : Nan::ObjectWrap(),
dead(false) {}
Transaction::~Transaction() {
dead = true;
}
void Transaction::Init() {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New("Transaction").ToLocalChecked());
constructor.Reset(Nan::GetFunction(t).ToLocalChecked());
}
CONSTRUCTOR(Transaction::constructor);
NAN_METHOD(Transaction::New) {
if (!CONSTRUCTING_PRIVILEGES) {
return Nan::ThrowSyntaxError("Transactions can only be constructed by the db.begin() method.");
}
Transaction* trans = new Transaction();
trans->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
OpenWorker::OpenWorker(Database* db)
: Nan::AsyncWorker(NULL), db(db) {}
OpenWorker::~OpenWorker() {}
void OpenWorker::Execute() {
int status;
status = sqlite3_open_v2(db->filename, &db->writeHandle, WRITE_MODE, NULL);
if (status != SQLITE_OK) {
SetErrorMessage(sqlite3_errmsg(db->writeHandle));
sqlite3_close(db->writeHandle);
db->writeHandle = NULL;
return;
}
status = sqlite3_open_v2(db->filename, &db->readHandle, READ_MODE, NULL);
if (status != SQLITE_OK) {
SetErrorMessage(sqlite3_errmsg(db->readHandle));
sqlite3_close(db->writeHandle);
sqlite3_close(db->readHandle);
db->writeHandle = NULL;
db->readHandle = NULL;
return;
}
sqlite3_busy_timeout(db->writeHandle, 30000);
sqlite3_busy_timeout(db->readHandle, 30000);
}
void OpenWorker::HandleOKCallback() {
Nan::HandleScope scope;
if (db->state == DONE) {
sqlite3_close(db->writeHandle);
sqlite3_close(db->readHandle);
db->writeHandle = NULL;
db->readHandle = NULL;
} else {
db->state = READY;
v8::Local<v8::Value> args[1] = {Nan::New("connect").ToLocalChecked()};
EMIT_EVENT(db->handle(), 1, args);
}
db->Unref();
}
void OpenWorker::HandleErrorCallback() {
Nan::HandleScope scope;
if (db->state != DONE) {
db->state = DONE;
v8::Local<v8::Value> args[2] = {
Nan::New("disconnect").ToLocalChecked(),
v8::Exception::Error(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked())
};
EMIT_EVENT(db->handle(), 2, args);
}
db->Unref();
}
CloseWorker::CloseWorker(Database* db, bool doNothing)
: Nan::AsyncWorker(NULL), db(db), doNothing(doNothing) {}
CloseWorker::~CloseWorker() {}
void CloseWorker::Execute() {
if (!doNothing) {
int status1 = sqlite3_close(db->writeHandle);
int status2 = sqlite3_close(db->readHandle);
db->writeHandle = NULL;
db->readHandle = NULL;
if (status1 != SQLITE_OK) {
SetErrorMessage(sqlite3_errmsg(db->writeHandle));
} else if (status2 != SQLITE_OK) {
SetErrorMessage(sqlite3_errmsg(db->readHandle));
}
}
}
void CloseWorker::HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> args[2] = {Nan::New("disconnect").ToLocalChecked(), Nan::Null()};
EMIT_EVENT(db->handle(), 2, args);
db->Unref();
}
void CloseWorker::HandleErrorCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> args[2] = {
Nan::New("disconnect").ToLocalChecked(),
v8::Exception::Error(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked())
};
EMIT_EVENT(db->handle(), 2, args);
db->Unref();
}
NAN_MODULE_INIT(InitDatabase) {
Database::Init(target);
Transaction::Init();
}
}
<commit_msg>added readquery<commit_after>#include <cstdlib>
#include <sqlite3.h>
#include <nan.h>
#include "macros.h"
#include "database.h"
namespace NODE_SQLITE3_PLUS_DATABASE {
int WRITE_MODE = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
int READ_MODE = SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX;
v8::PropertyAttribute FROZEN = static_cast<v8::PropertyAttribute>(v8::DontDelete | v8::ReadOnly);
enum STATE {CONNECTING, READY, DONE};
bool CONSTRUCTING_PRIVILEGES = false;
class Database : public Nan::ObjectWrap {
public:
Database(char*);
~Database();
static NAN_MODULE_INIT(Init);
friend class OpenWorker;
friend class CloseWorker;
private:
static CONSTRUCTOR(constructor);
static NAN_METHOD(New);
static NAN_GETTER(OpenGetter);
static NAN_METHOD(Close);
static NAN_METHOD(PrepareTransaction);
static NAN_METHOD(PrepareReadQuery);
char* filename;
sqlite3* readHandle;
sqlite3* writeHandle;
STATE state;
};
class Transaction : public Nan::ObjectWrap {
public:
Transaction();
~Transaction();
static void Init();
friend class Database;
private:
static CONSTRUCTOR(constructor);
static NAN_METHOD(New);
bool dead;
};
class ReadQuery : public Nan::ObjectWrap {
public:
ReadQuery();
~ReadQuery();
static void Init();
friend class Database;
private:
static CONSTRUCTOR(constructor);
static NAN_METHOD(New);
bool dead;
};
class OpenWorker : public Nan::AsyncWorker {
public:
OpenWorker(Database*);
~OpenWorker();
void Execute();
void HandleOKCallback();
void HandleErrorCallback();
private:
Database* db;
};
class CloseWorker : public Nan::AsyncWorker {
public:
CloseWorker(Database*, bool);
~CloseWorker();
void Execute();
void HandleOKCallback();
void HandleErrorCallback();
private:
Database* db;
bool doNothing;
};
Database::Database(char* filename) : Nan::ObjectWrap(),
filename(filename),
readHandle(NULL),
writeHandle(NULL),
state(CONNECTING) {}
Database::~Database() {
state = DONE;
sqlite3_close(readHandle);
sqlite3_close(writeHandle);
readHandle = NULL;
writeHandle = NULL;
free(filename);
filename = NULL;
}
NAN_MODULE_INIT(Database::Init) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New("Database").ToLocalChecked());
Nan::SetPrototypeMethod(t, "disconnect", Close);
Nan::SetPrototypeMethod(t, "begin", PrepareTransaction);
Nan::SetPrototypeMethod(t, "read", PrepareReadQuery);
Nan::SetAccessor(t->InstanceTemplate(), Nan::New("connected").ToLocalChecked(), OpenGetter);
constructor.Reset(Nan::GetFunction(t).ToLocalChecked());
Nan::Set(target, Nan::New("Database").ToLocalChecked(),
Nan::GetFunction(t).ToLocalChecked());
}
CONSTRUCTOR(Database::constructor);
NAN_METHOD(Database::New) {
REQUIRE_ARGUMENTS(1);
if (!info.IsConstructCall()) {
v8::Local<v8::Value> args[1] = {info[0]};
v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);
info.GetReturnValue().Set(cons->NewInstance(1, args));
} else {
REQUIRE_ARGUMENT_STRING(0, filename);
Database* db = new Database(RAW_STRING(filename));
db->Wrap(info.This());
db->Ref();
AsyncQueueWorker(new OpenWorker(db));
info.GetReturnValue().Set(info.This());
}
}
NAN_GETTER(Database::OpenGetter) {
Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This());
info.GetReturnValue().Set(db->state == READY);
}
NAN_METHOD(Database::Close) {
Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This());
if (db->state != DONE) {
db->Ref();
// --
// This should wait in queue for all pending transactions to finish. (writes AND reads).
// This should be invoked right away if there are no pending transactions (which will
// always be the case if it's still connecting). db->state == DONE simply means that it
// was READY when Close was invoked, and therefore should be treated equally, as shown
// below.
AsyncQueueWorker(new CloseWorker(db, db->state == CONNECTING));
// --
db->state = DONE;
}
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(Database::PrepareTransaction) {
OPTIONAL_ARGUMENT_STRING(0, source);
v8::Local<v8::Function> cons = Nan::New<v8::Function>(Transaction::constructor);
CONSTRUCTING_PRIVILEGES = true;
v8::Local<v8::Object> transaction = cons->NewInstance(0, NULL);
CONSTRUCTING_PRIVILEGES = false;
Nan::ForceSet(transaction, Nan::New("database").ToLocalChecked(), info.This(), FROZEN);
if (source->Length()) {
// Invoke .and() to append a statement.
}
info.GetReturnValue().Set(transaction);
}
NAN_METHOD(Database::PrepareReadQuery) {
REQUIRE_ARGUMENT_STRING(0, source);
v8::Local<v8::Function> cons = Nan::New<v8::Function>(ReadQuery::constructor);
CONSTRUCTING_PRIVILEGES = true;
v8::Local<v8::Object> readQuery = cons->NewInstance(0, NULL);
CONSTRUCTING_PRIVILEGES = false;
Nan::ForceSet(readQuery, Nan::New("database").ToLocalChecked(), info.This(), FROZEN);
Nan::ForceSet(readQuery, Nan::New("source").ToLocalChecked(), source, FROZEN);
info.GetReturnValue().Set(readQuery);
}
Transaction::Transaction() : Nan::ObjectWrap(),
dead(false) {}
Transaction::~Transaction() {
dead = true;
}
void Transaction::Init() {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New("Transaction").ToLocalChecked());
constructor.Reset(Nan::GetFunction(t).ToLocalChecked());
}
CONSTRUCTOR(Transaction::constructor);
NAN_METHOD(Transaction::New) {
if (!CONSTRUCTING_PRIVILEGES) {
return Nan::ThrowSyntaxError("Transactions can only be constructed by the db.begin() method.");
}
Transaction* trans = new Transaction();
trans->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
ReadQuery::ReadQuery() : Nan::ObjectWrap(),
dead(false) {}
ReadQuery::~ReadQuery() {
dead = true;
}
void ReadQuery::Init() {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New("ReadQuery").ToLocalChecked());
constructor.Reset(Nan::GetFunction(t).ToLocalChecked());
}
CONSTRUCTOR(ReadQuery::constructor);
NAN_METHOD(ReadQuery::New) {
if (!CONSTRUCTING_PRIVILEGES) {
return Nan::ThrowSyntaxError("ReadQuerys can only be constructed by the db.read() method.");
}
ReadQuery* readQuery = new ReadQuery();
readQuery->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
OpenWorker::OpenWorker(Database* db)
: Nan::AsyncWorker(NULL), db(db) {}
OpenWorker::~OpenWorker() {}
void OpenWorker::Execute() {
int status;
status = sqlite3_open_v2(db->filename, &db->writeHandle, WRITE_MODE, NULL);
if (status != SQLITE_OK) {
SetErrorMessage(sqlite3_errmsg(db->writeHandle));
sqlite3_close(db->writeHandle);
db->writeHandle = NULL;
return;
}
status = sqlite3_open_v2(db->filename, &db->readHandle, READ_MODE, NULL);
if (status != SQLITE_OK) {
SetErrorMessage(sqlite3_errmsg(db->readHandle));
sqlite3_close(db->writeHandle);
sqlite3_close(db->readHandle);
db->writeHandle = NULL;
db->readHandle = NULL;
return;
}
sqlite3_busy_timeout(db->writeHandle, 30000);
sqlite3_busy_timeout(db->readHandle, 30000);
}
void OpenWorker::HandleOKCallback() {
Nan::HandleScope scope;
if (db->state == DONE) {
sqlite3_close(db->writeHandle);
sqlite3_close(db->readHandle);
db->writeHandle = NULL;
db->readHandle = NULL;
} else {
db->state = READY;
v8::Local<v8::Value> args[1] = {Nan::New("connect").ToLocalChecked()};
EMIT_EVENT(db->handle(), 1, args);
}
db->Unref();
}
void OpenWorker::HandleErrorCallback() {
Nan::HandleScope scope;
if (db->state != DONE) {
db->state = DONE;
v8::Local<v8::Value> args[2] = {
Nan::New("disconnect").ToLocalChecked(),
v8::Exception::Error(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked())
};
EMIT_EVENT(db->handle(), 2, args);
}
db->Unref();
}
CloseWorker::CloseWorker(Database* db, bool doNothing)
: Nan::AsyncWorker(NULL), db(db), doNothing(doNothing) {}
CloseWorker::~CloseWorker() {}
void CloseWorker::Execute() {
if (!doNothing) {
int status1 = sqlite3_close(db->writeHandle);
int status2 = sqlite3_close(db->readHandle);
db->writeHandle = NULL;
db->readHandle = NULL;
if (status1 != SQLITE_OK) {
SetErrorMessage(sqlite3_errmsg(db->writeHandle));
} else if (status2 != SQLITE_OK) {
SetErrorMessage(sqlite3_errmsg(db->readHandle));
}
}
}
void CloseWorker::HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> args[2] = {Nan::New("disconnect").ToLocalChecked(), Nan::Null()};
EMIT_EVENT(db->handle(), 2, args);
db->Unref();
}
void CloseWorker::HandleErrorCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> args[2] = {
Nan::New("disconnect").ToLocalChecked(),
v8::Exception::Error(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked())
};
EMIT_EVENT(db->handle(), 2, args);
db->Unref();
}
NAN_MODULE_INIT(InitDatabase) {
Database::Init(target);
Transaction::Init();
ReadQuery::Init();
}
}
<|endoftext|> |
<commit_before>// Copyright 2012 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.
#include "deps_log.h"
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#ifndef _WIN32
#include <unistd.h>
#endif
#include "graph.h"
#include "metrics.h"
#include "state.h"
#include "util.h"
// The version is stored as 4 bytes after the signature and also serves as a
// byte order mark. Signature and version combined are 16 bytes long.
const char kFileSignature[] = "# ninjadeps\n";
const int kCurrentVersion = 3;
// Record size is currently limited to less than the full 32 bit, due to
// internal buffers having to have this size.
const unsigned kMaxRecordSize = (1 << 19) - 1;
DepsLog::~DepsLog() {
Close();
}
bool DepsLog::OpenForWrite(const string& path, string* err) {
if (needs_recompaction_) {
if (!Recompact(path, err))
return false;
}
file_ = fopen(path.c_str(), "ab");
if (!file_) {
*err = strerror(errno);
return false;
}
// Set the buffer size to this and flush the file buffer after every record
// to make sure records aren't written partially.
setvbuf(file_, NULL, _IOFBF, kMaxRecordSize + 1);
SetCloseOnExec(fileno(file_));
// Opening a file in append mode doesn't set the file pointer to the file's
// end on Windows. Do that explicitly.
fseek(file_, 0, SEEK_END);
if (ftell(file_) == 0) {
if (fwrite(kFileSignature, sizeof(kFileSignature) - 1, 1, file_) < 1) {
*err = strerror(errno);
return false;
}
if (fwrite(&kCurrentVersion, 4, 1, file_) < 1) {
*err = strerror(errno);
return false;
}
}
if (fflush(file_) != 0) {
*err = strerror(errno);
return false;
}
return true;
}
bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
const vector<Node*>& nodes) {
return RecordDeps(node, mtime, nodes.size(),
nodes.empty() ? NULL : (Node**)&nodes.front());
}
bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
int node_count, Node** nodes) {
// Track whether there's any new data to be recorded.
bool made_change = false;
// Assign ids to all nodes that are missing one.
if (node->id() < 0) {
if (!RecordId(node))
return false;
made_change = true;
}
for (int i = 0; i < node_count; ++i) {
if (nodes[i]->id() < 0) {
if (!RecordId(nodes[i]))
return false;
made_change = true;
}
}
// See if the new data is different than the existing data, if any.
if (!made_change) {
Deps* deps = GetDeps(node);
if (!deps ||
deps->mtime != mtime ||
deps->node_count != node_count) {
made_change = true;
} else {
for (int i = 0; i < node_count; ++i) {
if (deps->nodes[i] != nodes[i]) {
made_change = true;
break;
}
}
}
}
// Don't write anything if there's no new info.
if (!made_change)
return true;
// Update on-disk representation.
unsigned size = 4 * (1 + 1 + (uint16_t)node_count);
if (size > kMaxRecordSize) {
errno = ERANGE;
return false;
}
size |= 0x80000000; // Deps record: set high bit.
if (fwrite(&size, 4, 1, file_) < 1)
return false;
int id = node->id();
if (fwrite(&id, 4, 1, file_) < 1)
return false;
int timestamp = mtime;
if (fwrite(×tamp, 4, 1, file_) < 1)
return false;
for (int i = 0; i < node_count; ++i) {
id = nodes[i]->id();
if (fwrite(&id, 4, 1, file_) < 1)
return false;
}
if (fflush(file_) != 0)
return false;
// Update in-memory representation.
Deps* deps = new Deps(mtime, node_count);
for (int i = 0; i < node_count; ++i)
deps->nodes[i] = nodes[i];
UpdateDeps(node->id(), deps);
return true;
}
void DepsLog::Close() {
if (file_)
fclose(file_);
file_ = NULL;
}
bool DepsLog::Load(const string& path, State* state, string* err) {
METRIC_RECORD(".ninja_deps load");
char buf[kMaxRecordSize + 1];
FILE* f = fopen(path.c_str(), "rb");
if (!f) {
if (errno == ENOENT)
return true;
*err = strerror(errno);
return false;
}
bool valid_header = true;
int version = 0;
if (!fgets(buf, sizeof(buf), f) || fread(&version, 4, 1, f) < 1)
valid_header = false;
// Note: For version differences, this should migrate to the new format.
// But the v1 format could sometimes (rarely) end up with invalid data, so
// don't migrate v1 to v3 to force a rebuild. (v2 only existed for a few days,
// and there was no release with it, so pretend that it never happened.)
if (!valid_header || strcmp(buf, kFileSignature) != 0 ||
version != kCurrentVersion) {
if (version == 1)
*err = "deps log potentially corrupt; rebuilding";
else
*err = "bad deps log signature or version; starting over";
fclose(f);
unlink(path.c_str());
// Don't report this as a failure. An empty deps log will cause
// us to rebuild the outputs anyway.
return true;
}
long offset;
bool read_failed = false;
int unique_dep_record_count = 0;
int total_dep_record_count = 0;
for (;;) {
offset = ftell(f);
unsigned size;
if (fread(&size, 4, 1, f) < 1) {
if (!feof(f))
read_failed = true;
break;
}
bool is_deps = (size >> 31) != 0;
size = size & 0x7FFFFFFF;
if (fread(buf, size, 1, f) < 1 || size > kMaxRecordSize) {
read_failed = true;
break;
}
if (is_deps) {
assert(size % 4 == 0);
int* deps_data = reinterpret_cast<int*>(buf);
int out_id = deps_data[0];
int mtime = deps_data[1];
deps_data += 2;
int deps_count = (size / 4) - 2;
Deps* deps = new Deps(mtime, deps_count);
for (int i = 0; i < deps_count; ++i) {
assert(deps_data[i] < (int)nodes_.size());
assert(nodes_[deps_data[i]]);
deps->nodes[i] = nodes_[deps_data[i]];
}
total_dep_record_count++;
if (!UpdateDeps(out_id, deps))
++unique_dep_record_count;
} else {
int path_size = size - 4;
// There can be up to 3 bytes of padding.
if (buf[path_size - 1] == '\0') --path_size;
if (buf[path_size - 1] == '\0') --path_size;
if (buf[path_size - 1] == '\0') --path_size;
StringPiece path(buf, path_size);
Node* node = state->GetNode(path);
// Check that the expected index matches the actual index. This can only
// happen if two ninja processes write to the same deps log concurrently.
// (This uses unary complement to make the checksum look less like a
// dependency record entry.)
unsigned checksum = *reinterpret_cast<unsigned*>(buf + size - 4);
int expected_id = ~checksum;
int id = nodes_.size();
if (id != expected_id) {
read_failed = true;
break;
}
assert(node->id() < 0);
node->set_id(id);
nodes_.push_back(node);
}
}
if (read_failed) {
// An error occurred while loading; try to recover by truncating the
// file to the last fully-read record.
if (ferror(f)) {
*err = strerror(ferror(f));
} else {
*err = "premature end of file";
}
fclose(f);
if (!Truncate(path.c_str(), offset, err))
return false;
// The truncate succeeded; we'll just report the load error as a
// warning because the build can proceed.
*err += "; recovering";
return true;
}
fclose(f);
// Rebuild the log if there are too many dead records.
int kMinCompactionEntryCount = 1000;
int kCompactionRatio = 3;
if (total_dep_record_count > kMinCompactionEntryCount &&
total_dep_record_count > unique_dep_record_count * kCompactionRatio) {
needs_recompaction_ = true;
}
return true;
}
DepsLog::Deps* DepsLog::GetDeps(Node* node) {
// Abort if the node has no id (never referenced in the deps) or if
// there's no deps recorded for the node.
if (node->id() < 0 || node->id() >= (int)deps_.size())
return NULL;
return deps_[node->id()];
}
bool DepsLog::Recompact(const string& path, string* err) {
METRIC_RECORD(".ninja_deps recompact");
printf("Recompacting deps...\n");
Close();
string temp_path = path + ".recompact";
// OpenForWrite() opens for append. Make sure it's not appending to a
// left-over file from a previous recompaction attempt that crashed somehow.
unlink(temp_path.c_str());
DepsLog new_log;
if (!new_log.OpenForWrite(temp_path, err))
return false;
// Clear all known ids so that new ones can be reassigned. The new indices
// will refer to the ordering in new_log, not in the current log.
for (vector<Node*>::iterator i = nodes_.begin(); i != nodes_.end(); ++i)
(*i)->set_id(-1);
// Write out all deps again.
for (int old_id = 0; old_id < (int)deps_.size(); ++old_id) {
Deps* deps = deps_[old_id];
if (!deps) continue; // If nodes_[old_id] is a leaf, it has no deps.
if (!new_log.RecordDeps(nodes_[old_id], deps->mtime,
deps->node_count, deps->nodes)) {
new_log.Close();
return false;
}
}
new_log.Close();
// All nodes now have ids that refer to new_log, so steal its data.
deps_.swap(new_log.deps_);
nodes_.swap(new_log.nodes_);
if (unlink(path.c_str()) < 0) {
*err = strerror(errno);
return false;
}
if (rename(temp_path.c_str(), path.c_str()) < 0) {
*err = strerror(errno);
return false;
}
return true;
}
bool DepsLog::UpdateDeps(int out_id, Deps* deps) {
if (out_id >= (int)deps_.size())
deps_.resize(out_id + 1);
bool delete_old = deps_[out_id] != NULL;
if (delete_old)
delete deps_[out_id];
deps_[out_id] = deps;
return delete_old;
}
bool DepsLog::RecordId(Node* node) {
int path_size = node->path().size();
int padding = (4 - path_size % 4) % 4; // Pad path to 4 byte boundary.
unsigned size = path_size + padding + 4;
if (size > kMaxRecordSize) {
errno = ERANGE;
return false;
}
if (fwrite(&size, 4, 1, file_) < 1)
return false;
if (fwrite(node->path().data(), path_size, 1, file_) < 1) {
assert(node->path().size() > 0);
return false;
}
if (padding && fwrite("\0\0", padding, 1, file_) < 1)
return false;
int id = nodes_.size();
unsigned checksum = ~(unsigned)id;
if (fwrite(&checksum, 4, 1, file_) < 1)
return false;
if (fflush(file_) != 0)
return false;
node->set_id(id);
nodes_.push_back(node);
return true;
}
<commit_msg>document an assumption<commit_after>// Copyright 2012 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.
#include "deps_log.h"
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#ifndef _WIN32
#include <unistd.h>
#endif
#include "graph.h"
#include "metrics.h"
#include "state.h"
#include "util.h"
// The version is stored as 4 bytes after the signature and also serves as a
// byte order mark. Signature and version combined are 16 bytes long.
const char kFileSignature[] = "# ninjadeps\n";
const int kCurrentVersion = 3;
// Record size is currently limited to less than the full 32 bit, due to
// internal buffers having to have this size.
const unsigned kMaxRecordSize = (1 << 19) - 1;
DepsLog::~DepsLog() {
Close();
}
bool DepsLog::OpenForWrite(const string& path, string* err) {
if (needs_recompaction_) {
if (!Recompact(path, err))
return false;
}
file_ = fopen(path.c_str(), "ab");
if (!file_) {
*err = strerror(errno);
return false;
}
// Set the buffer size to this and flush the file buffer after every record
// to make sure records aren't written partially.
setvbuf(file_, NULL, _IOFBF, kMaxRecordSize + 1);
SetCloseOnExec(fileno(file_));
// Opening a file in append mode doesn't set the file pointer to the file's
// end on Windows. Do that explicitly.
fseek(file_, 0, SEEK_END);
if (ftell(file_) == 0) {
if (fwrite(kFileSignature, sizeof(kFileSignature) - 1, 1, file_) < 1) {
*err = strerror(errno);
return false;
}
if (fwrite(&kCurrentVersion, 4, 1, file_) < 1) {
*err = strerror(errno);
return false;
}
}
if (fflush(file_) != 0) {
*err = strerror(errno);
return false;
}
return true;
}
bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
const vector<Node*>& nodes) {
return RecordDeps(node, mtime, nodes.size(),
nodes.empty() ? NULL : (Node**)&nodes.front());
}
bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
int node_count, Node** nodes) {
// Track whether there's any new data to be recorded.
bool made_change = false;
// Assign ids to all nodes that are missing one.
if (node->id() < 0) {
if (!RecordId(node))
return false;
made_change = true;
}
for (int i = 0; i < node_count; ++i) {
if (nodes[i]->id() < 0) {
if (!RecordId(nodes[i]))
return false;
made_change = true;
}
}
// See if the new data is different than the existing data, if any.
if (!made_change) {
Deps* deps = GetDeps(node);
if (!deps ||
deps->mtime != mtime ||
deps->node_count != node_count) {
made_change = true;
} else {
for (int i = 0; i < node_count; ++i) {
if (deps->nodes[i] != nodes[i]) {
made_change = true;
break;
}
}
}
}
// Don't write anything if there's no new info.
if (!made_change)
return true;
// Update on-disk representation.
unsigned size = 4 * (1 + 1 + (uint16_t)node_count);
if (size > kMaxRecordSize) {
errno = ERANGE;
return false;
}
size |= 0x80000000; // Deps record: set high bit.
if (fwrite(&size, 4, 1, file_) < 1)
return false;
int id = node->id();
if (fwrite(&id, 4, 1, file_) < 1)
return false;
int timestamp = mtime;
if (fwrite(×tamp, 4, 1, file_) < 1)
return false;
for (int i = 0; i < node_count; ++i) {
id = nodes[i]->id();
if (fwrite(&id, 4, 1, file_) < 1)
return false;
}
if (fflush(file_) != 0)
return false;
// Update in-memory representation.
Deps* deps = new Deps(mtime, node_count);
for (int i = 0; i < node_count; ++i)
deps->nodes[i] = nodes[i];
UpdateDeps(node->id(), deps);
return true;
}
void DepsLog::Close() {
if (file_)
fclose(file_);
file_ = NULL;
}
bool DepsLog::Load(const string& path, State* state, string* err) {
METRIC_RECORD(".ninja_deps load");
char buf[kMaxRecordSize + 1];
FILE* f = fopen(path.c_str(), "rb");
if (!f) {
if (errno == ENOENT)
return true;
*err = strerror(errno);
return false;
}
bool valid_header = true;
int version = 0;
if (!fgets(buf, sizeof(buf), f) || fread(&version, 4, 1, f) < 1)
valid_header = false;
// Note: For version differences, this should migrate to the new format.
// But the v1 format could sometimes (rarely) end up with invalid data, so
// don't migrate v1 to v3 to force a rebuild. (v2 only existed for a few days,
// and there was no release with it, so pretend that it never happened.)
if (!valid_header || strcmp(buf, kFileSignature) != 0 ||
version != kCurrentVersion) {
if (version == 1)
*err = "deps log potentially corrupt; rebuilding";
else
*err = "bad deps log signature or version; starting over";
fclose(f);
unlink(path.c_str());
// Don't report this as a failure. An empty deps log will cause
// us to rebuild the outputs anyway.
return true;
}
long offset;
bool read_failed = false;
int unique_dep_record_count = 0;
int total_dep_record_count = 0;
for (;;) {
offset = ftell(f);
unsigned size;
if (fread(&size, 4, 1, f) < 1) {
if (!feof(f))
read_failed = true;
break;
}
bool is_deps = (size >> 31) != 0;
size = size & 0x7FFFFFFF;
if (fread(buf, size, 1, f) < 1 || size > kMaxRecordSize) {
read_failed = true;
break;
}
if (is_deps) {
assert(size % 4 == 0);
int* deps_data = reinterpret_cast<int*>(buf);
int out_id = deps_data[0];
int mtime = deps_data[1];
deps_data += 2;
int deps_count = (size / 4) - 2;
Deps* deps = new Deps(mtime, deps_count);
for (int i = 0; i < deps_count; ++i) {
assert(deps_data[i] < (int)nodes_.size());
assert(nodes_[deps_data[i]]);
deps->nodes[i] = nodes_[deps_data[i]];
}
total_dep_record_count++;
if (!UpdateDeps(out_id, deps))
++unique_dep_record_count;
} else {
int path_size = size - 4;
assert(path_size > 0); // CanonicalizePath() rejects empty paths.
// There can be up to 3 bytes of padding.
if (buf[path_size - 1] == '\0') --path_size;
if (buf[path_size - 1] == '\0') --path_size;
if (buf[path_size - 1] == '\0') --path_size;
StringPiece path(buf, path_size);
Node* node = state->GetNode(path);
// Check that the expected index matches the actual index. This can only
// happen if two ninja processes write to the same deps log concurrently.
// (This uses unary complement to make the checksum look less like a
// dependency record entry.)
unsigned checksum = *reinterpret_cast<unsigned*>(buf + size - 4);
int expected_id = ~checksum;
int id = nodes_.size();
if (id != expected_id) {
read_failed = true;
break;
}
assert(node->id() < 0);
node->set_id(id);
nodes_.push_back(node);
}
}
if (read_failed) {
// An error occurred while loading; try to recover by truncating the
// file to the last fully-read record.
if (ferror(f)) {
*err = strerror(ferror(f));
} else {
*err = "premature end of file";
}
fclose(f);
if (!Truncate(path.c_str(), offset, err))
return false;
// The truncate succeeded; we'll just report the load error as a
// warning because the build can proceed.
*err += "; recovering";
return true;
}
fclose(f);
// Rebuild the log if there are too many dead records.
int kMinCompactionEntryCount = 1000;
int kCompactionRatio = 3;
if (total_dep_record_count > kMinCompactionEntryCount &&
total_dep_record_count > unique_dep_record_count * kCompactionRatio) {
needs_recompaction_ = true;
}
return true;
}
DepsLog::Deps* DepsLog::GetDeps(Node* node) {
// Abort if the node has no id (never referenced in the deps) or if
// there's no deps recorded for the node.
if (node->id() < 0 || node->id() >= (int)deps_.size())
return NULL;
return deps_[node->id()];
}
bool DepsLog::Recompact(const string& path, string* err) {
METRIC_RECORD(".ninja_deps recompact");
printf("Recompacting deps...\n");
Close();
string temp_path = path + ".recompact";
// OpenForWrite() opens for append. Make sure it's not appending to a
// left-over file from a previous recompaction attempt that crashed somehow.
unlink(temp_path.c_str());
DepsLog new_log;
if (!new_log.OpenForWrite(temp_path, err))
return false;
// Clear all known ids so that new ones can be reassigned. The new indices
// will refer to the ordering in new_log, not in the current log.
for (vector<Node*>::iterator i = nodes_.begin(); i != nodes_.end(); ++i)
(*i)->set_id(-1);
// Write out all deps again.
for (int old_id = 0; old_id < (int)deps_.size(); ++old_id) {
Deps* deps = deps_[old_id];
if (!deps) continue; // If nodes_[old_id] is a leaf, it has no deps.
if (!new_log.RecordDeps(nodes_[old_id], deps->mtime,
deps->node_count, deps->nodes)) {
new_log.Close();
return false;
}
}
new_log.Close();
// All nodes now have ids that refer to new_log, so steal its data.
deps_.swap(new_log.deps_);
nodes_.swap(new_log.nodes_);
if (unlink(path.c_str()) < 0) {
*err = strerror(errno);
return false;
}
if (rename(temp_path.c_str(), path.c_str()) < 0) {
*err = strerror(errno);
return false;
}
return true;
}
bool DepsLog::UpdateDeps(int out_id, Deps* deps) {
if (out_id >= (int)deps_.size())
deps_.resize(out_id + 1);
bool delete_old = deps_[out_id] != NULL;
if (delete_old)
delete deps_[out_id];
deps_[out_id] = deps;
return delete_old;
}
bool DepsLog::RecordId(Node* node) {
int path_size = node->path().size();
int padding = (4 - path_size % 4) % 4; // Pad path to 4 byte boundary.
unsigned size = path_size + padding + 4;
if (size > kMaxRecordSize) {
errno = ERANGE;
return false;
}
if (fwrite(&size, 4, 1, file_) < 1)
return false;
if (fwrite(node->path().data(), path_size, 1, file_) < 1) {
assert(node->path().size() > 0);
return false;
}
if (padding && fwrite("\0\0", padding, 1, file_) < 1)
return false;
int id = nodes_.size();
unsigned checksum = ~(unsigned)id;
if (fwrite(&checksum, 4, 1, file_) < 1)
return false;
if (fflush(file_) != 0)
return false;
node->set_id(id);
nodes_.push_back(node);
return true;
}
<|endoftext|> |
<commit_before>/**
* @author: Jeff Thompson
* See COPYING for copyright and distribution information.
*/
#ifndef NDN_COMMON_HPP
#define NDN_COMMON_HPP
#include <vector>
#include "../config.h"
// Depending on where ./configure found shared_ptr, define the ptr_lib namespace.
// We always use ndn::ptr_lib.
#if HAVE_STD_SHARED_PTR
#include <memory>
namespace ndn { namespace ptr_lib = std; }
#elif HAVE_BOOST_SHARED_PTR
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
namespace ndn { namespace ptr_lib = boost; }
#else
// Use the boost header files in this distribution that were extracted with:
// cd <INCLUDE DIRECTORY WITH boost SUBDIRECTORY>
// dist/bin/bcp --namespace=ndnboost shared_ptr make_shared weak_ptr function bind <NDN-CPP ROOT>
// cd <NDN-CPP ROOT>
// mv boost ndnboost
// cd ndnboost
// (unset LANG; find . -type f -exec sed -i '' 's/\<boost\//\<ndnboost\//g' {} +)
// (unset LANG; find . -type f -exec sed -i '' 's/\"boost\//\"ndnboost\//g' {} +)
#include <ndnboost/shared_ptr.hpp>
#include <ndnboost/make_shared.hpp>
namespace ndn { namespace ptr_lib = ndnboost; }
#endif
// Depending on where ./configure found function, define the func_lib namespace.
// We always use ndn::func_lib.
#if HAVE_STD_FUNCTION
#include <functional>
namespace ndn { namespace func_lib = std; }
#elif HAVE_BOOST_FUNCTION
#include <boost/function.hpp>
#include <boost/bind.hpp>
namespace ndn { namespace func_lib = boost; }
#else
// Use the boost header files in this distribution that were extracted as above:
#include <ndnboost/function.hpp>
#include <ndnboost/bind.hpp>
namespace ndn { namespace func_lib = ndnboost; }
#endif
namespace ndn {
/**
* Clear the vector and copy valueLength bytes from value.
* @param v the vector to copy to
* @param value the array of bytes, or 0 to not copy
* @param valueLength the length of value
*/
static inline void setVector(std::vector<unsigned char>& vec, const unsigned char *value, unsigned int valueLength)
{
vec.clear();
if (value)
vec.insert(vec.begin(), value, value + valueLength);
}
/**
* Return the hex representation of the bytes in array.
* @param array The array of bytes.
* @return Hex string.
*/
std::string toHex(const std::vector<unsigned char>& array);
}
#endif
<commit_msg>Remove unused setVector.<commit_after>/**
* @author: Jeff Thompson
* See COPYING for copyright and distribution information.
*/
#ifndef NDN_COMMON_HPP
#define NDN_COMMON_HPP
#include <vector>
#include "../config.h"
// Depending on where ./configure found shared_ptr, define the ptr_lib namespace.
// We always use ndn::ptr_lib.
#if HAVE_STD_SHARED_PTR
#include <memory>
namespace ndn { namespace ptr_lib = std; }
#elif HAVE_BOOST_SHARED_PTR
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
namespace ndn { namespace ptr_lib = boost; }
#else
// Use the boost header files in this distribution that were extracted with:
// cd <INCLUDE DIRECTORY WITH boost SUBDIRECTORY>
// dist/bin/bcp --namespace=ndnboost shared_ptr make_shared weak_ptr function bind <NDN-CPP ROOT>
// cd <NDN-CPP ROOT>
// mv boost ndnboost
// cd ndnboost
// (unset LANG; find . -type f -exec sed -i '' 's/\<boost\//\<ndnboost\//g' {} +)
// (unset LANG; find . -type f -exec sed -i '' 's/\"boost\//\"ndnboost\//g' {} +)
#include <ndnboost/shared_ptr.hpp>
#include <ndnboost/make_shared.hpp>
namespace ndn { namespace ptr_lib = ndnboost; }
#endif
// Depending on where ./configure found function, define the func_lib namespace.
// We always use ndn::func_lib.
#if HAVE_STD_FUNCTION
#include <functional>
namespace ndn { namespace func_lib = std; }
#elif HAVE_BOOST_FUNCTION
#include <boost/function.hpp>
#include <boost/bind.hpp>
namespace ndn { namespace func_lib = boost; }
#else
// Use the boost header files in this distribution that were extracted as above:
#include <ndnboost/function.hpp>
#include <ndnboost/bind.hpp>
namespace ndn { namespace func_lib = ndnboost; }
#endif
namespace ndn {
/**
* Return the hex representation of the bytes in array.
* @param array The array of bytes.
* @return Hex string.
*/
std::string toHex(const std::vector<unsigned char>& array);
}
#endif
<|endoftext|> |
<commit_before>#include "document.h"
#include <iostream>
using namespace v8;
using namespace libxmljs;
Handle<Value>
Document::SetRoot(
const Arguments& args)
{
return args.This();
}
Handle<Value>
Document::GetProperty(
Local<String> property,
const AccessorInfo& info)
{
HandleScope scope;
Document *document = ObjectWrap::Unwrap<Document>(info.This());
assert(document);
const char * value = NULL;
if (property == VERSION_SYMBOL) {
value = document->get_version();
} else if (property == ENCODING_SYMBOL) {
value = document->get_encoding();
} else {
assert("Should not get here!");
return ThrowException(Exception::Error(String::New("Should not get here!")));
}
return String::New(value, xmlStrlen((const xmlChar*)value));
}
void
Document::SetEncoding(
Local<String> property,
Local<Value> value,
const AccessorInfo& info)
{
HandleScope scope;
Document *document = ObjectWrap::Unwrap<Document>(info.This());
assert(document);
assert(property == ENCODING_SYMBOL);
String::Utf8Value encoding(value->ToString());
document->set_encoding(*encoding);
}
Handle<Value>
Document::New(
const Arguments& args)
{
HandleScope scope;
Handle<Function> callback;
String::Utf8Value *version = NULL, *encoding = NULL;
switch (args.Length()) {
case 0: // newDocument()
break;
case 1: // newDocument(version), newDocument(callback)
if (args[0]->IsString()) {
version = new String::Utf8Value(args[0]->ToString());
} else if (args[0]->IsFunction()) {
callback = Handle<Function>::Cast(args[0]);
} else {
LIBXMLJS_THROW_EXCEPTION("Bad argument: newDocument([version]) or newDocument([callback])");
}
break;
case 2: // newDocument(version, encoding), newDocument(version, callback)
if (args[0]->IsString() && args[1]->IsString()) {
version = new String::Utf8Value(args[0]->ToString());
encoding = new String::Utf8Value(args[1]->ToString());
} else if (args[0]->IsString() && args[1]->IsFunction()) {
version = new String::Utf8Value(args[0]->ToString());
callback = Handle<Function>::Cast(args[1]);
} else {
LIBXMLJS_THROW_EXCEPTION("Bad argument: newDocument([version], [encoding]) or newDocument([version], [callback])");
}
break;
default: // newDocument(version, encoding, callback)
if (args[0]->IsString() && args[1]->IsString() && args[2]->IsFunction()) {
version = new String::Utf8Value(args[0]->ToString());
encoding = new String::Utf8Value(args[1]->ToString());
callback = Handle<Function>::Cast(args[2]);
} else {
LIBXMLJS_THROW_EXCEPTION("Bad argument: newDocument([version], [encoding], [callback])");
}
break;
}
Document *document = version ? new Document(**version) : new Document();
document->Wrap(args.This());
if (encoding)
document->set_encoding(**encoding);
if (*callback && !callback->IsNull()) {
Handle<Value> argv[1] = { args.This() };
*callback->Call(args.This(), 1, argv);
}
return args.This();
}
Document::Document()
{
init_document("1.0");
}
Document::Document(
const char * version)
{
init_document(version);
}
Document::~Document()
{
xmlFreeDoc(doc_);
}
void
Document::init_document(
const char * version)
{
doc_ = xmlNewDoc((const xmlChar*)version);
doc_->_private = this;
}
void
Document::set_encoding(
const char * encoding)
{
doc_->encoding = (const xmlChar*)encoding;
}
const char *
Document::get_encoding()
{
assert(doc_);
const char * encoding = NULL;
if(doc_->encoding)
encoding = (const char*)doc_->encoding;
return encoding;
}
const char *
Document::get_version()
{
assert(doc_);
const char * version = NULL;
if(doc_->version)
version = (const char*)doc_->version;
return version;
}
void
Document::Initialize (Handle<Object> target)
{
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
Persistent<FunctionTemplate> doc_template = Persistent<FunctionTemplate>::New(t);
doc_template->InstanceTemplate()->SetInternalFieldCount(1);
LIBXMLJS_SET_PROTOTYPE_METHOD(doc_template, "root", Document::SetRoot);
doc_template->PrototypeTemplate()->SetAccessor(ENCODING_SYMBOL, GetProperty, SetEncoding);
doc_template->PrototypeTemplate()->SetAccessor(VERSION_SYMBOL, GetProperty);
target->Set(String::NewSymbol("newDocument"), doc_template->GetFunction());
}
<commit_msg>remove errant include<commit_after>#include "document.h"
using namespace v8;
using namespace libxmljs;
Handle<Value>
Document::SetRoot(
const Arguments& args)
{
return args.This();
}
Handle<Value>
Document::GetProperty(
Local<String> property,
const AccessorInfo& info)
{
HandleScope scope;
Document *document = ObjectWrap::Unwrap<Document>(info.This());
assert(document);
const char * value = NULL;
if (property == VERSION_SYMBOL) {
value = document->get_version();
} else if (property == ENCODING_SYMBOL) {
value = document->get_encoding();
} else {
assert("Should not get here!");
return ThrowException(Exception::Error(String::New("Should not get here!")));
}
return String::New(value, xmlStrlen((const xmlChar*)value));
}
void
Document::SetEncoding(
Local<String> property,
Local<Value> value,
const AccessorInfo& info)
{
HandleScope scope;
Document *document = ObjectWrap::Unwrap<Document>(info.This());
assert(document);
assert(property == ENCODING_SYMBOL);
String::Utf8Value encoding(value->ToString());
document->set_encoding(*encoding);
}
Handle<Value>
Document::New(
const Arguments& args)
{
HandleScope scope;
Handle<Function> callback;
String::Utf8Value *version = NULL, *encoding = NULL;
switch (args.Length()) {
case 0: // newDocument()
break;
case 1: // newDocument(version), newDocument(callback)
if (args[0]->IsString()) {
version = new String::Utf8Value(args[0]->ToString());
} else if (args[0]->IsFunction()) {
callback = Handle<Function>::Cast(args[0]);
} else {
LIBXMLJS_THROW_EXCEPTION("Bad argument: newDocument([version]) or newDocument([callback])");
}
break;
case 2: // newDocument(version, encoding), newDocument(version, callback)
if (args[0]->IsString() && args[1]->IsString()) {
version = new String::Utf8Value(args[0]->ToString());
encoding = new String::Utf8Value(args[1]->ToString());
} else if (args[0]->IsString() && args[1]->IsFunction()) {
version = new String::Utf8Value(args[0]->ToString());
callback = Handle<Function>::Cast(args[1]);
} else {
LIBXMLJS_THROW_EXCEPTION("Bad argument: newDocument([version], [encoding]) or newDocument([version], [callback])");
}
break;
default: // newDocument(version, encoding, callback)
if (args[0]->IsString() && args[1]->IsString() && args[2]->IsFunction()) {
version = new String::Utf8Value(args[0]->ToString());
encoding = new String::Utf8Value(args[1]->ToString());
callback = Handle<Function>::Cast(args[2]);
} else {
LIBXMLJS_THROW_EXCEPTION("Bad argument: newDocument([version], [encoding], [callback])");
}
break;
}
Document *document = version ? new Document(**version) : new Document();
document->Wrap(args.This());
if (encoding)
document->set_encoding(**encoding);
if (*callback && !callback->IsNull()) {
Handle<Value> argv[1] = { args.This() };
*callback->Call(args.This(), 1, argv);
}
return args.This();
}
Document::Document()
{
init_document("1.0");
}
Document::Document(
const char * version)
{
init_document(version);
}
Document::~Document()
{
xmlFreeDoc(doc_);
}
void
Document::init_document(
const char * version)
{
doc_ = xmlNewDoc((const xmlChar*)version);
doc_->_private = this;
}
void
Document::set_encoding(
const char * encoding)
{
doc_->encoding = (const xmlChar*)encoding;
}
const char *
Document::get_encoding()
{
assert(doc_);
const char * encoding = NULL;
if(doc_->encoding)
encoding = (const char*)doc_->encoding;
return encoding;
}
const char *
Document::get_version()
{
assert(doc_);
const char * version = NULL;
if(doc_->version)
version = (const char*)doc_->version;
return version;
}
void
Document::Initialize (Handle<Object> target)
{
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
Persistent<FunctionTemplate> doc_template = Persistent<FunctionTemplate>::New(t);
doc_template->InstanceTemplate()->SetInternalFieldCount(1);
LIBXMLJS_SET_PROTOTYPE_METHOD(doc_template, "root", Document::SetRoot);
doc_template->PrototypeTemplate()->SetAccessor(ENCODING_SYMBOL, GetProperty, SetEncoding);
doc_template->PrototypeTemplate()->SetAccessor(VERSION_SYMBOL, GetProperty);
target->Set(String::NewSymbol("newDocument"), doc_template->GetFunction());
}
<|endoftext|> |
<commit_before>//Copyright (c) 2011 Krishna Rajendran <krishna@emptybox.org>.
//Licensed under an MIT/X11 license. See LICENSE file for details.
extern "C" {
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
}
#include "eldb.hpp"
#include "eldb_gtk_globalkeybind.hpp"
namespace elgtk {
struct KeyList;
struct ValueList;
struct Window {
eldb::Eldb eldb;
GtkWidget *window;
GtkWidget *searchEntry;
KeyList *keyList;
ValueList *valueList;
Window();
static void destroy();
static void searchEntryChanged( GtkWidget *widget, Window *window );
static int keySnooper( GtkWidget *widget, GdkEventKey *event, gpointer data );
void layout();
};
struct KeyList {
GtkWidget *treeView;
GtkListStore *listStore;
GtkTreeViewColumn *column;
GtkCellRenderer *nameRenderer;
GtkTreeSelection *select;
enum Columns {
KEY_COLUMN = 0,
VALUE_COLUMN
};
KeyList( ValueList *valueList );
static void changed( GtkTreeSelection *widget, ValueList *valueList );
};
struct ValueList {
GtkWidget* vBox;
ValueList();
};
Window::Window() {
if ( !eldb.init( "" ) ) {
exit(1);
}
window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
searchEntry = gtk_entry_new();
valueList = new ValueList();
keyList = new KeyList( valueList );
layout();
g_signal_connect( searchEntry, "changed", G_CALLBACK( searchEntryChanged ), this );
g_signal_connect( window, "destroy", G_CALLBACK( destroy ), NULL );
gtk_window_set_title( GTK_WINDOW( window ), "The Exo Lobe" );
gtk_window_set_default_size( GTK_WINDOW( window ), 800, 300 );
gtk_widget_show_all( window );
gtk_window_stick( GTK_WINDOW( window ) );
gtk_window_set_keep_above( GTK_WINDOW( window ), 1 );
searchEntryChanged( searchEntry, this );
gtk_key_snooper_install( keySnooper, window );
gtk_window_set_focus( GTK_WINDOW( window ), 0 );
globalBinding( GTK_WINDOW( window ) );
}
KeyList::KeyList( ValueList *valueList ) {
listStore = gtk_list_store_new( 2, G_TYPE_STRING, G_TYPE_STRING );
treeView = gtk_tree_view_new_with_model( GTK_TREE_MODEL( listStore ) );
nameRenderer = gtk_cell_renderer_text_new();
column = gtk_tree_view_column_new_with_attributes( "Keys", nameRenderer, "text", KEY_COLUMN, (void *)NULL );
gtk_tree_view_append_column( GTK_TREE_VIEW( treeView ), column );
g_object_unref( G_OBJECT( listStore ) );
select = gtk_tree_view_get_selection( GTK_TREE_VIEW ( treeView ) );
gtk_tree_selection_set_mode( select, GTK_SELECTION_SINGLE );
g_signal_connect( select, "changed", G_CALLBACK( KeyList::changed ), valueList );
}
void KeyList::changed( GtkTreeSelection *selection, ValueList *valueList ) {
GtkTreeIter iter;
GtkTreeModel *model;
//const char *key;
if ( gtk_tree_selection_get_selected( selection, &model, &iter ) ) {
/* gtk_tree_model_get( model, &iter, VALUE_COLUMN, &key, -1 );
GtkTextBuffer *buffer = gtk_text_view_get_buffer( textView );
gtk_text_buffer_set_text( buffer, key, -1 );*/
}
}
ValueList::ValueList() {
vBox = gtk_vbox_new( FALSE, 3 );
//TODO gtk_text_view_set_wrap_mode( GTK_TEXT_VIEW( textView ), GTK_WRAP_WORD_CHAR );
}
void Window::destroy( ) {
gtk_main_quit ();
}
void Window::searchEntryChanged( GtkWidget *widget, Window *window ) {
const char *text;
GtkTreeIter iter;
GtkListStore *keyStore = window->keyList->listStore;
gtk_list_store_clear( keyStore );
text = gtk_entry_get_text( GTK_ENTRY( widget ) );
auto result = window->eldb.find( text );
if ( result->count ) {
for ( auto key: result->keys ) {
fprintf( stdout, "%s :\n", key->key.c_str() );
for ( auto value: key->values ) {
fprintf( stdout, "\t%s\n", value->value.c_str() );
gtk_list_store_append( keyStore, &iter );
gtk_list_store_set( keyStore, &iter,
KeyList::KEY_COLUMN , key->key.c_str(),
KeyList::VALUE_COLUMN, value->value.c_str(),
-1 );
}
}
} else {
fprintf( stderr, "No Results\n" );
}
}
void Window::layout() {
GtkWidget *table = gtk_table_new( 3, 3, FALSE );
GtkWidget *textViewScroller = gtk_scrolled_window_new( NULL, NULL );
GtkWidget *keyListScroller = gtk_scrolled_window_new( NULL, NULL );
gtk_container_set_border_width( GTK_CONTAINER( window ), 5 );
gtk_table_attach( GTK_TABLE( table ), searchEntry, 0, 3, 0, 1, GtkAttachOptions( GTK_EXPAND | GTK_FILL ), GTK_SHRINK, 0, 0 );
gtk_table_attach_defaults( GTK_TABLE( table ), keyListScroller, 0, 1, 1, 3 );
gtk_table_attach_defaults( GTK_TABLE( table ), textViewScroller, 1, 3, 1, 3 );
gtk_container_add( GTK_CONTAINER( keyListScroller ), keyList->treeView );
gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( textViewScroller ), valueList->vBox );
gtk_table_set_row_spacings( GTK_TABLE( table ), 2 );
gtk_table_set_col_spacings( GTK_TABLE( table ), 2 );
gtk_container_add( GTK_CONTAINER( window ), table );
}
int Window::keySnooper( GtkWidget *widget, GdkEventKey *event, gpointer data ) {
if ( event->keyval == GDK_KEY_q && event->state & GDK_CONTROL_MASK ) {
destroy( );
}
if ( event->keyval == GDK_KEY_Escape ) {
gtk_window_set_focus( GTK_WINDOW( data ), 0 );
}
return 0;
}
} //namespace elgtk
int main( int argc, char **argv ) {
gtk_init( &argc, &argv );
elgtk::Window window;
gtk_main();
return 0;
}
<commit_msg>Display an icon for the gtk app<commit_after>//Copyright (c) 2011 Krishna Rajendran <krishna@emptybox.org>.
//Licensed under an MIT/X11 license. See LICENSE file for details.
extern "C" {
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
}
#include "eldb.hpp"
#include "eldb_gtk_globalkeybind.hpp"
namespace elgtk {
struct KeyList;
struct ValueList;
struct Window {
eldb::Eldb eldb;
GtkWidget *window;
GtkWidget *searchEntry;
KeyList *keyList;
ValueList *valueList;
Window();
static void destroy();
static void searchEntryChanged( GtkWidget *widget, Window *window );
static int keySnooper( GtkWidget *widget, GdkEventKey *event, gpointer data );
void layout();
};
struct KeyList {
GtkWidget *treeView;
GtkListStore *listStore;
GtkTreeViewColumn *column;
GtkCellRenderer *nameRenderer;
GtkTreeSelection *select;
enum Columns {
KEY_COLUMN = 0,
VALUE_COLUMN
};
KeyList( ValueList *valueList );
static void changed( GtkTreeSelection *widget, ValueList *valueList );
};
struct ValueList {
GtkWidget* vBox;
ValueList();
};
Window::Window() {
if ( !eldb.init( "" ) ) {
exit(1);
}
window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
searchEntry = gtk_entry_new();
valueList = new ValueList();
keyList = new KeyList( valueList );
layout();
GError *error;
if ( ! gtk_window_set_icon_from_file( GTK_WINDOW( window ), "exolobe_tray.png", &error ) ) {
fprintf( stderr, "%s\n", error->message );
g_error_free( error );
}
g_signal_connect( searchEntry, "changed", G_CALLBACK( searchEntryChanged ), this );
g_signal_connect( window, "destroy", G_CALLBACK( destroy ), NULL );
gtk_window_set_title( GTK_WINDOW( window ), "The Exo Lobe" );
gtk_window_set_default_size( GTK_WINDOW( window ), 800, 300 );
gtk_widget_show_all( window );
gtk_window_stick( GTK_WINDOW( window ) );
gtk_window_set_keep_above( GTK_WINDOW( window ), 1 );
searchEntryChanged( searchEntry, this );
gtk_key_snooper_install( keySnooper, window );
gtk_window_set_focus( GTK_WINDOW( window ), 0 );
globalBinding( GTK_WINDOW( window ) );
}
KeyList::KeyList( ValueList *valueList ) {
listStore = gtk_list_store_new( 2, G_TYPE_STRING, G_TYPE_STRING );
treeView = gtk_tree_view_new_with_model( GTK_TREE_MODEL( listStore ) );
nameRenderer = gtk_cell_renderer_text_new();
column = gtk_tree_view_column_new_with_attributes( "Keys", nameRenderer, "text", KEY_COLUMN, (void *)NULL );
gtk_tree_view_append_column( GTK_TREE_VIEW( treeView ), column );
g_object_unref( G_OBJECT( listStore ) );
select = gtk_tree_view_get_selection( GTK_TREE_VIEW ( treeView ) );
gtk_tree_selection_set_mode( select, GTK_SELECTION_SINGLE );
g_signal_connect( select, "changed", G_CALLBACK( KeyList::changed ), valueList );
}
void KeyList::changed( GtkTreeSelection *selection, ValueList *valueList ) {
GtkTreeIter iter;
GtkTreeModel *model;
//const char *key;
if ( gtk_tree_selection_get_selected( selection, &model, &iter ) ) {
/* gtk_tree_model_get( model, &iter, VALUE_COLUMN, &key, -1 );
GtkTextBuffer *buffer = gtk_text_view_get_buffer( textView );
gtk_text_buffer_set_text( buffer, key, -1 );*/
}
}
ValueList::ValueList() {
vBox = gtk_vbox_new( FALSE, 3 );
//TODO gtk_text_view_set_wrap_mode( GTK_TEXT_VIEW( textView ), GTK_WRAP_WORD_CHAR );
}
void Window::destroy( ) {
gtk_main_quit ();
}
void Window::searchEntryChanged( GtkWidget *widget, Window *window ) {
const char *text;
GtkTreeIter iter;
GtkListStore *keyStore = window->keyList->listStore;
gtk_list_store_clear( keyStore );
text = gtk_entry_get_text( GTK_ENTRY( widget ) );
auto result = window->eldb.find( text );
if ( result->count ) {
for ( auto key: result->keys ) {
fprintf( stdout, "%s :\n", key->key.c_str() );
for ( auto value: key->values ) {
fprintf( stdout, "\t%s\n", value->value.c_str() );
gtk_list_store_append( keyStore, &iter );
gtk_list_store_set( keyStore, &iter,
KeyList::KEY_COLUMN , key->key.c_str(),
KeyList::VALUE_COLUMN, value->value.c_str(),
-1 );
}
}
} else {
fprintf( stderr, "No Results\n" );
}
}
void Window::layout() {
GtkWidget *table = gtk_table_new( 3, 3, FALSE );
GtkWidget *textViewScroller = gtk_scrolled_window_new( NULL, NULL );
GtkWidget *keyListScroller = gtk_scrolled_window_new( NULL, NULL );
gtk_container_set_border_width( GTK_CONTAINER( window ), 5 );
gtk_table_attach( GTK_TABLE( table ), searchEntry, 0, 3, 0, 1, GtkAttachOptions( GTK_EXPAND | GTK_FILL ), GTK_SHRINK, 0, 0 );
gtk_table_attach_defaults( GTK_TABLE( table ), keyListScroller, 0, 1, 1, 3 );
gtk_table_attach_defaults( GTK_TABLE( table ), textViewScroller, 1, 3, 1, 3 );
gtk_container_add( GTK_CONTAINER( keyListScroller ), keyList->treeView );
gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( textViewScroller ), valueList->vBox );
gtk_table_set_row_spacings( GTK_TABLE( table ), 2 );
gtk_table_set_col_spacings( GTK_TABLE( table ), 2 );
gtk_container_add( GTK_CONTAINER( window ), table );
}
int Window::keySnooper( GtkWidget *widget, GdkEventKey *event, gpointer data ) {
if ( event->keyval == GDK_KEY_q && event->state & GDK_CONTROL_MASK ) {
destroy( );
}
if ( event->keyval == GDK_KEY_Escape ) {
gtk_window_set_focus( GTK_WINDOW( data ), 0 );
}
return 0;
}
} //namespace elgtk
int main( int argc, char **argv ) {
gtk_init( &argc, &argv );
elgtk::Window window;
gtk_main();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2014 Tom Regan
//
// 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 "encodings.h"
namespace encodings {
namespace binary {
void print_byte(uint8_t byte) {
for (auto i = 0x80; i; i = i >> 1) {
std::cout << (((byte & i) == i) ? "1" : "0");
}
std::cout << '\n';
}
void print_double(uint32_t bits) {
for (uint32_t i = 0x80000000; i; i = i >> 1) {
if (i == 0x80 || i == 0x8000 || i == 0x800000) {
std::cout << ' ';
}
std::cout << (((bits & i) == i) ? "1" : "0");
}
std::cout << '\n';
}
} // binary
namespace base64 {
uint8_t to_byte(uint8_t byte) {
if (byte == '+') {
return 62;
} else if (byte == '/') {
return 63;
} else if (byte < 58) {
return byte + 4;
} else if (byte < 91) {
return byte - 65;
}
return byte - 71;
}
uint8_t from_byte(uint8_t byte) {
if (byte < 26) {
return byte + 65; // ascii A
} else if (byte < 52) {
return byte + 71; // ascii a
} else if (byte < 62) {
return byte - 4; // ascii 0
} else if (byte == 62) {
return '+';
}
return '/';
}
std::string from_hex(std::string hex_string) {
auto buffer = std::stringstream();
while (!hex_string.empty()) {
uint32_t bitset = std::stoul(hex_string.substr(0, 6), 0, 16);
hex_string.erase(0, 6);
while (!(bitset & 0x00ff0000)) {
bitset <<= 8;
}
uint8_t bytemask = 0x3f;
buffer << from_byte((bitset >> 18) & bytemask);
buffer << from_byte((bitset >> 12) & bytemask);
if (bitset & 0x00000fc0) {
buffer << from_byte((bitset >> 6) & bytemask);
if (bitset & 0x0000003f) {
buffer << from_byte(bitset & bytemask);
}
}
while (buffer.str().size() % 4) {
buffer << '=';
}
}
return buffer.str();
}
} // base64
namespace hex {
std::string from_base64(std::string base64_string) {
auto buffer = std::stringstream();
while (base64_string.size()) {
std::string dword = base64_string.substr(0, 4);
base64_string.erase(0, 4);
uint32_t bitset = base64::to_byte(dword[0]);
bitset <<=6;
bitset |= base64::to_byte(dword[1]);
bitset <<= 6;
bitset |= base64::to_byte(dword[2]);
bitset <<=6;
bitset |= base64::to_byte(dword[3]);
if (dword[2] == '=' && dword[3] == '=') {
bitset >>= 16;
}
else if (dword[3] == '=') {
bitset >>= 8;
}
buffer << std::hex << bitset;
}
return buffer.str();
}
} // hex
} // encodings
<commit_msg>such c++. many constructors. wow<commit_after>// Copyright 2014 Tom Regan
//
// 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 "encodings.h"
namespace encodings {
namespace binary {
void print_byte(uint8_t byte) {
for (auto i = 0x80; i; i = i >> 1) {
std::cout << (((byte & i) == i) ? "1" : "0");
}
std::cout << '\n';
}
void print_double(uint32_t bits) {
for (uint32_t i = 0x80000000; i; i = i >> 1) {
if (i == 0x80 || i == 0x8000 || i == 0x800000) {
std::cout << ' ';
}
std::cout << (((bits & i) == i) ? "1" : "0");
}
std::cout << '\n';
}
} // binary
namespace base64 {
uint8_t to_byte(uint8_t byte) {
if (byte == '+') {
return 62;
} else if (byte == '/') {
return 63;
} else if (byte < 58) {
return byte + 4;
} else if (byte < 91) {
return byte - 65;
}
return byte - 71;
}
uint8_t from_byte(uint8_t byte) {
if (byte < 26) {
return byte + 65; // ascii A
} else if (byte < 52) {
return byte + 71; // ascii a
} else if (byte < 62) {
return byte - 4; // ascii 0
} else if (byte == 62) {
return '+';
}
return '/';
}
std::string from_hex(std::string hex_string) {
std::stringstream buffer;
while (!hex_string.empty()) {
uint32_t bitset = std::stoul(hex_string.substr(0, 6), 0, 16);
hex_string.erase(0, 6);
while (!(bitset & 0x00ff0000)) {
bitset <<= 8;
}
uint8_t bytemask = 0x3f;
buffer << from_byte((bitset >> 18) & bytemask);
buffer << from_byte((bitset >> 12) & bytemask);
if (bitset & 0x00000fc0) {
buffer << from_byte((bitset >> 6) & bytemask);
if (bitset & 0x0000003f) {
buffer << from_byte(bitset & bytemask);
}
}
while (buffer.str().size() % 4) {
buffer << '=';
}
}
return buffer.str();
}
} // base64
namespace hex {
std::string from_base64(std::string base64_string) {
std::stringstream buffer;
while (base64_string.size()) {
std::string dword = base64_string.substr(0, 4);
base64_string.erase(0, 4);
uint32_t bitset = base64::to_byte(dword[0]);
bitset <<=6;
bitset |= base64::to_byte(dword[1]);
bitset <<= 6;
bitset |= base64::to_byte(dword[2]);
bitset <<=6;
bitset |= base64::to_byte(dword[3]);
if (dword[2] == '=' && dword[3] == '=') {
bitset >>= 16;
}
else if (dword[3] == '=') {
bitset >>= 8;
}
buffer << std::hex << bitset;
}
return buffer.str();
}
} // hex
} // encodings
<|endoftext|> |
<commit_before>// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2011 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include "CQBrowserPane.h"
#include "listviews.h"
CQBrowserPane::CQBrowserPane(QWidget* parent) :
QTreeView(parent)
{
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(this->sizePolicy().hasHeightForWidth());
setSizePolicy(sizePolicy);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
setAutoScroll(true);
setEditTriggers(QAbstractItemView::NoEditTriggers);
setTextElideMode(Qt::ElideNone);
setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
setUniformRowHeights(true);
setSortingEnabled(true);
setHeaderHidden(true);
setObjectName("CQBrowserPane");
connect(this, SIGNAL(expanded(const QModelIndex &)), this, SLOT(slotUpdateScrollBar(const QModelIndex &)));
connect(this, SIGNAL(collapsed(const QModelIndex &)), this, SLOT(slotUpdateScrollBar(const QModelIndex &)));
}
// virtual
CQBrowserPane::~CQBrowserPane()
{}
// virtual
void CQBrowserPane::currentChanged(const QModelIndex & current, const QModelIndex & /* previous */)
{
static_cast< ListViews * >(parent())->slotFolderChanged(current);
}
void CQBrowserPane::slotUpdateScrollBar(const QModelIndex & index)
{
resizeColumnToContents(index.column());
}
<commit_msg>- avoid rtti error<commit_after>// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2011 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include "CQBrowserPane.h"
#include "listviews.h"
CQBrowserPane::CQBrowserPane(QWidget* parent) :
QTreeView(parent)
{
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(this->sizePolicy().hasHeightForWidth());
setSizePolicy(sizePolicy);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
setAutoScroll(true);
setEditTriggers(QAbstractItemView::NoEditTriggers);
setTextElideMode(Qt::ElideNone);
setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
setUniformRowHeights(true);
setSortingEnabled(true);
setHeaderHidden(true);
setObjectName("CQBrowserPane");
connect(this, SIGNAL(expanded(const QModelIndex &)), this, SLOT(slotUpdateScrollBar(const QModelIndex &)));
connect(this, SIGNAL(collapsed(const QModelIndex &)), this, SLOT(slotUpdateScrollBar(const QModelIndex &)));
}
// virtual
CQBrowserPane::~CQBrowserPane()
{}
// virtual
void CQBrowserPane::currentChanged(const QModelIndex & current, const QModelIndex & /* previous */)
{
qobject_cast< ListViews * >(parent())->slotFolderChanged(current);
}
void CQBrowserPane::slotUpdateScrollBar(const QModelIndex & index)
{
resizeColumnToContents(index.column());
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <wallet/wallet.h>
#include <qt/receivecoinsdialog.h>
#include <qt/forms/ui_receivecoinsdialog.h>
#include <qt/addressbookpage.h>
#include <qt/addresstablemodel.h>
#include <qt/bitcoinunits.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <qt/receiverequestdialog.h>
#include <qt/recentrequeststablemodel.h>
#include <qt/walletmodel.h>
#include <QAction>
#include <QCursor>
#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>
ReceiveCoinsDialog::ReceiveCoinsDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::ReceiveCoinsDialog),
columnResizingFixer(0),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
if (!_platformStyle->getImagesOnButtons()) {
ui->clearButton->setIcon(QIcon());
ui->receiveButton->setIcon(QIcon());
ui->showRequestButton->setIcon(QIcon());
ui->removeRequestButton->setIcon(QIcon());
} else {
ui->clearButton->setIcon(_platformStyle->SingleColorIcon(":/icons/remove"));
ui->receiveButton->setIcon(_platformStyle->SingleColorIcon(":/icons/receiving_addresses"));
ui->showRequestButton->setIcon(_platformStyle->SingleColorIcon(":/icons/edit"));
ui->removeRequestButton->setIcon(_platformStyle->SingleColorIcon(":/icons/remove"));
}
// context menu actions
QAction *copyURIAction = new QAction(tr("Copy URI"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyMessageAction = new QAction(tr("Copy message"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
// context menu
contextMenu = new QMenu(this);
contextMenu->addAction(copyURIAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyMessageAction);
contextMenu->addAction(copyAmountAction);
// context menu signals
connect(ui->recentRequestsView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
connect(copyURIAction, SIGNAL(triggered()), this, SLOT(copyURI()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(copyMessage()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
}
void ReceiveCoinsDialog::setModel(WalletModel *_model)
{
this->model = _model;
if(_model && _model->getOptionsModel())
{
_model->getRecentRequestsTableModel()->sort(RecentRequestsTableModel::Date, Qt::DescendingOrder);
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
updateDisplayUnit();
QTableView* tableView = ui->recentRequestsView;
tableView->verticalHeader()->hide();
tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
tableView->setModel(_model->getRecentRequestsTableModel());
tableView->setAlternatingRowColors(true);
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setSelectionMode(QAbstractItemView::ContiguousSelection);
tableView->setColumnWidth(RecentRequestsTableModel::Date, DATE_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Label, LABEL_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Amount, AMOUNT_MINIMUM_COLUMN_WIDTH);
connect(tableView->selectionModel(),
SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this,
SLOT(recentRequestsView_selectionChanged(QItemSelection, QItemSelection)));
// Last 2 columns are set by the columnResizingFixer, when the table geometry is ready.
columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH, this);
// configure bech32 checkbox, disable if launched with legacy as default:
if (model->wallet().getDefaultAddressType() == OutputType::BECH32) {
ui->useBech32->setCheckState(Qt::Checked);
} else {
ui->useBech32->setCheckState(Qt::Unchecked);
}
ui->useBech32->setVisible(model->wallet().getDefaultAddressType() != OutputType::LEGACY);
}
}
ReceiveCoinsDialog::~ReceiveCoinsDialog()
{
delete ui;
}
void ReceiveCoinsDialog::clear()
{
ui->reqAmount->clear();
ui->reqLabel->setText("");
ui->reqMessage->setText("");
updateDisplayUnit();
}
void ReceiveCoinsDialog::reject()
{
clear();
}
void ReceiveCoinsDialog::accept()
{
clear();
}
void ReceiveCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
ui->reqAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
void ReceiveCoinsDialog::on_receiveButton_clicked()
{
if(!model || !model->getOptionsModel() || !model->getAddressTableModel() || !model->getRecentRequestsTableModel())
return;
QString address;
QString label = ui->reqLabel->text();
/* Generate new receiving address */
OutputType address_type = model->wallet().getDefaultAddressType();
if (address_type != OutputType::LEGACY) {
address_type = ui->useBech32->isChecked() ? OutputType::BECH32 : OutputType::P2SH_SEGWIT;
}
address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "", address_type);
SendCoinsRecipient info(address, label,
ui->reqAmount->value(), ui->reqMessage->text());
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setModel(model);
dialog->setInfo(info);
dialog->show();
clear();
/* Store request for later reference */
model->getRecentRequestsTableModel()->addNewRequest(info);
}
void ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex &index)
{
const RecentRequestsTableModel *submodel = model->getRecentRequestsTableModel();
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setModel(model);
dialog->setInfo(submodel->entry(index.row()).recipient);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
void ReceiveCoinsDialog::recentRequestsView_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
// Enable Show/Remove buttons only if anything is selected.
bool enable = !ui->recentRequestsView->selectionModel()->selectedRows().isEmpty();
ui->showRequestButton->setEnabled(enable);
ui->removeRequestButton->setEnabled(enable);
}
void ReceiveCoinsDialog::on_showRequestButton_clicked()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
for (const QModelIndex& index : selection) {
on_recentRequestsView_doubleClicked(index);
}
}
void ReceiveCoinsDialog::on_removeRequestButton_clicked()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if(selection.empty())
return;
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
model->getRecentRequestsTableModel()->removeRows(firstIndex.row(), selection.length(), firstIndex.parent());
}
// We override the virtual resizeEvent of the QWidget to adjust tables column
// sizes as the tables width is proportional to the dialogs width.
void ReceiveCoinsDialog::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
columnResizingFixer->stretchColumnWidth(RecentRequestsTableModel::Message);
}
void ReceiveCoinsDialog::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Return)
{
// press return -> submit form
if (ui->reqLabel->hasFocus() || ui->reqAmount->hasFocus() || ui->reqMessage->hasFocus())
{
event->ignore();
on_receiveButton_clicked();
return;
}
}
this->QDialog::keyPressEvent(event);
}
QModelIndex ReceiveCoinsDialog::selectedRow()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return QModelIndex();
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if(selection.empty())
return QModelIndex();
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
return firstIndex;
}
// copy column of selected row to clipboard
void ReceiveCoinsDialog::copyColumnToClipboard(int column)
{
QModelIndex firstIndex = selectedRow();
if (!firstIndex.isValid()) {
return;
}
GUIUtil::setClipboard(model->getRecentRequestsTableModel()->data(firstIndex.child(firstIndex.row(), column), Qt::EditRole).toString());
}
// context menu
void ReceiveCoinsDialog::showMenu(const QPoint &point)
{
if (!selectedRow().isValid()) {
return;
}
contextMenu->exec(QCursor::pos());
}
// context menu action: copy URI
void ReceiveCoinsDialog::copyURI()
{
QModelIndex sel = selectedRow();
if (!sel.isValid()) {
return;
}
const RecentRequestsTableModel * const submodel = model->getRecentRequestsTableModel();
const QString uri = GUIUtil::formatBitcoinURI(submodel->entry(sel.row()).recipient);
GUIUtil::setClipboard(uri);
}
// context menu action: copy label
void ReceiveCoinsDialog::copyLabel()
{
copyColumnToClipboard(RecentRequestsTableModel::Label);
}
// context menu action: copy message
void ReceiveCoinsDialog::copyMessage()
{
copyColumnToClipboard(RecentRequestsTableModel::Message);
}
// context menu action: copy amount
void ReceiveCoinsDialog::copyAmount()
{
copyColumnToClipboard(RecentRequestsTableModel::Amount);
}
<commit_msg>GUI: Allow generating Bech32 addresses with a legacy-address default<commit_after>// Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <wallet/wallet.h>
#include <qt/receivecoinsdialog.h>
#include <qt/forms/ui_receivecoinsdialog.h>
#include <qt/addressbookpage.h>
#include <qt/addresstablemodel.h>
#include <qt/bitcoinunits.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <qt/receiverequestdialog.h>
#include <qt/recentrequeststablemodel.h>
#include <qt/walletmodel.h>
#include <QAction>
#include <QCursor>
#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>
ReceiveCoinsDialog::ReceiveCoinsDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::ReceiveCoinsDialog),
columnResizingFixer(0),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
if (!_platformStyle->getImagesOnButtons()) {
ui->clearButton->setIcon(QIcon());
ui->receiveButton->setIcon(QIcon());
ui->showRequestButton->setIcon(QIcon());
ui->removeRequestButton->setIcon(QIcon());
} else {
ui->clearButton->setIcon(_platformStyle->SingleColorIcon(":/icons/remove"));
ui->receiveButton->setIcon(_platformStyle->SingleColorIcon(":/icons/receiving_addresses"));
ui->showRequestButton->setIcon(_platformStyle->SingleColorIcon(":/icons/edit"));
ui->removeRequestButton->setIcon(_platformStyle->SingleColorIcon(":/icons/remove"));
}
// context menu actions
QAction *copyURIAction = new QAction(tr("Copy URI"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyMessageAction = new QAction(tr("Copy message"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
// context menu
contextMenu = new QMenu(this);
contextMenu->addAction(copyURIAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyMessageAction);
contextMenu->addAction(copyAmountAction);
// context menu signals
connect(ui->recentRequestsView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
connect(copyURIAction, SIGNAL(triggered()), this, SLOT(copyURI()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(copyMessage()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
}
void ReceiveCoinsDialog::setModel(WalletModel *_model)
{
this->model = _model;
if(_model && _model->getOptionsModel())
{
_model->getRecentRequestsTableModel()->sort(RecentRequestsTableModel::Date, Qt::DescendingOrder);
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
updateDisplayUnit();
QTableView* tableView = ui->recentRequestsView;
tableView->verticalHeader()->hide();
tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
tableView->setModel(_model->getRecentRequestsTableModel());
tableView->setAlternatingRowColors(true);
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setSelectionMode(QAbstractItemView::ContiguousSelection);
tableView->setColumnWidth(RecentRequestsTableModel::Date, DATE_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Label, LABEL_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Amount, AMOUNT_MINIMUM_COLUMN_WIDTH);
connect(tableView->selectionModel(),
SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this,
SLOT(recentRequestsView_selectionChanged(QItemSelection, QItemSelection)));
// Last 2 columns are set by the columnResizingFixer, when the table geometry is ready.
columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH, this);
if (model->wallet().getDefaultAddressType() == OutputType::BECH32) {
ui->useBech32->setCheckState(Qt::Checked);
} else {
ui->useBech32->setCheckState(Qt::Unchecked);
}
}
}
ReceiveCoinsDialog::~ReceiveCoinsDialog()
{
delete ui;
}
void ReceiveCoinsDialog::clear()
{
ui->reqAmount->clear();
ui->reqLabel->setText("");
ui->reqMessage->setText("");
updateDisplayUnit();
}
void ReceiveCoinsDialog::reject()
{
clear();
}
void ReceiveCoinsDialog::accept()
{
clear();
}
void ReceiveCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
ui->reqAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
void ReceiveCoinsDialog::on_receiveButton_clicked()
{
if(!model || !model->getOptionsModel() || !model->getAddressTableModel() || !model->getRecentRequestsTableModel())
return;
QString address;
QString label = ui->reqLabel->text();
/* Generate new receiving address */
OutputType address_type;
if (ui->useBech32->isChecked()) {
address_type = OutputType::BECH32;
} else {
address_type = model->wallet().getDefaultAddressType();
if (address_type == OutputType::BECH32) {
address_type = OutputType::P2SH_SEGWIT;
}
}
address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "", address_type);
SendCoinsRecipient info(address, label,
ui->reqAmount->value(), ui->reqMessage->text());
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setModel(model);
dialog->setInfo(info);
dialog->show();
clear();
/* Store request for later reference */
model->getRecentRequestsTableModel()->addNewRequest(info);
}
void ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex &index)
{
const RecentRequestsTableModel *submodel = model->getRecentRequestsTableModel();
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setModel(model);
dialog->setInfo(submodel->entry(index.row()).recipient);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
void ReceiveCoinsDialog::recentRequestsView_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
// Enable Show/Remove buttons only if anything is selected.
bool enable = !ui->recentRequestsView->selectionModel()->selectedRows().isEmpty();
ui->showRequestButton->setEnabled(enable);
ui->removeRequestButton->setEnabled(enable);
}
void ReceiveCoinsDialog::on_showRequestButton_clicked()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
for (const QModelIndex& index : selection) {
on_recentRequestsView_doubleClicked(index);
}
}
void ReceiveCoinsDialog::on_removeRequestButton_clicked()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if(selection.empty())
return;
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
model->getRecentRequestsTableModel()->removeRows(firstIndex.row(), selection.length(), firstIndex.parent());
}
// We override the virtual resizeEvent of the QWidget to adjust tables column
// sizes as the tables width is proportional to the dialogs width.
void ReceiveCoinsDialog::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
columnResizingFixer->stretchColumnWidth(RecentRequestsTableModel::Message);
}
void ReceiveCoinsDialog::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Return)
{
// press return -> submit form
if (ui->reqLabel->hasFocus() || ui->reqAmount->hasFocus() || ui->reqMessage->hasFocus())
{
event->ignore();
on_receiveButton_clicked();
return;
}
}
this->QDialog::keyPressEvent(event);
}
QModelIndex ReceiveCoinsDialog::selectedRow()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return QModelIndex();
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if(selection.empty())
return QModelIndex();
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
return firstIndex;
}
// copy column of selected row to clipboard
void ReceiveCoinsDialog::copyColumnToClipboard(int column)
{
QModelIndex firstIndex = selectedRow();
if (!firstIndex.isValid()) {
return;
}
GUIUtil::setClipboard(model->getRecentRequestsTableModel()->data(firstIndex.child(firstIndex.row(), column), Qt::EditRole).toString());
}
// context menu
void ReceiveCoinsDialog::showMenu(const QPoint &point)
{
if (!selectedRow().isValid()) {
return;
}
contextMenu->exec(QCursor::pos());
}
// context menu action: copy URI
void ReceiveCoinsDialog::copyURI()
{
QModelIndex sel = selectedRow();
if (!sel.isValid()) {
return;
}
const RecentRequestsTableModel * const submodel = model->getRecentRequestsTableModel();
const QString uri = GUIUtil::formatBitcoinURI(submodel->entry(sel.row()).recipient);
GUIUtil::setClipboard(uri);
}
// context menu action: copy label
void ReceiveCoinsDialog::copyLabel()
{
copyColumnToClipboard(RecentRequestsTableModel::Label);
}
// context menu action: copy message
void ReceiveCoinsDialog::copyMessage()
{
copyColumnToClipboard(RecentRequestsTableModel::Message);
}
// context menu action: copy amount
void ReceiveCoinsDialog::copyAmount()
{
copyColumnToClipboard(RecentRequestsTableModel::Amount);
}
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2009 Dan Leinir Turthra Jensen <admin@leinir.dk>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "gluonobjectfactory.h"
#include "directoryprovider.h"
#include "gluonobject.h"
#include "debughelper.h"
#include <QtGui/QApplication>
#include <QtCore/QDir>
#include <QtCore/QPluginLoader>
#include <QtCore/QVariant>
using namespace GluonCore;
GLUON_DEFINE_SINGLETON( GluonObjectFactory )
QStringList
GluonObjectFactory::objectTypeNames() const
{
QStringList theNames;
QHash<QString, const QMetaObject*>::const_iterator i;
for( i = m_objectTypes.constBegin(); i != m_objectTypes.constEnd(); ++i )
theNames << i.key();
return theNames;
}
QHash<QString, const QMetaObject*>
GluonObjectFactory::objectTypes() const
{
return m_objectTypes;
}
const QHash<QString, int>
GluonObjectFactory::objectTypeIDs() const
{
return m_objectTypeIDs;
}
QStringList
GluonObjectFactory::objectMimeTypes() const
{
return m_mimeTypes.keys();
}
GluonObject*
GluonObjectFactory::instantiateObjectByName( const QString& objectTypeName )
{
DEBUG_BLOCK
QString fullObjectTypeName( objectTypeName );
if( !objectTypeName.contains( "::" ) )
fullObjectTypeName = QString( "Gluon::" ) + fullObjectTypeName;
const QMetaObject* meta;
if( ( meta = m_objectTypes.value( objectTypeName, 0 ) ) )
{
GluonObject* obj = qobject_cast<GluonObject*>( meta->newInstance() );
if( obj )
{
return obj;
}
else
{
DEBUG_TEXT2( "If you are seeing this message, you have most likely failed to mark the constructor of %1 as Q_INVOKABLE", objectTypeName )
return 0;
}
}
DEBUG_TEXT( QString( "Object type named %1 not found in factory!" ).arg( objectTypeName ) )
return 0;
}
GluonObject*
GluonObjectFactory::instantiateObjectByMimetype( const QString& objectMimeType )
{
return instantiateObjectByName( m_mimeTypes[objectMimeType] );
}
QVariant
GluonObjectFactory::wrapObject( const QVariant& original, GluonObject* newValue )
{
DEBUG_BLOCK
QString type = original.typeName();
if( type.endsWith( '*' ) ) //Remove the * from the type
{
type = type.left( type.length() - 1 );
}
if( m_objectTypes.contains( type ) )
{
QScopedPointer<GluonObject> obj( instantiateObjectByName( type ) );
return obj->toVariant( newValue );
}
DEBUG_TEXT2( "Warning: Type %1 not found.", type )
return QVariant();
}
QVariant
GluonObjectFactory::wrapObject( const QString& type, GluonObject* newValue )
{
DEBUG_BLOCK
QString typeName = type;
if( type.endsWith( '*' ) )
typeName = type.left( type.length() - 1 );
if( m_objectTypes.contains( typeName ) )
{
QScopedPointer<GluonObject> obj( instantiateObjectByName( typeName ) );
return obj->toVariant( newValue );
}
DEBUG_TEXT2( "Warning: Type %1 not found.", typeName )
return QVariant();
}
GluonObject*
GluonObjectFactory::wrappedObject( const QVariant& wrappedObject )
{
QString type( wrappedObject.typeName() );
QString typeName = type;
if( type.endsWith( '*' ) )
typeName = type.left( type.length() - 1 );
if( m_objectTypes.contains( typeName ) )
{
QScopedPointer<GluonObject> obj( instantiateObjectByName( typeName ) );
return obj->fromVariant( wrappedObject );
}
DEBUG_BLOCK
DEBUG_TEXT2( "Warning: Type %1 not found.", typeName)
return 0;
}
void
GluonObjectFactory::loadPlugins()
{
DEBUG_FUNC_NAME
QList<QDir> pluginDirs;
QDir pluginDir( QApplication::applicationDirPath() );
#if defined(Q_OS_WIN)
if( pluginDir.dirName().toLower() == "debug" || pluginDir.dirName().toLower() == "release" )
pluginDir.cdUp();
#elif defined(Q_OS_MAC)
if( pluginDir.dirName() == "MacOS" )
{
pluginDir.cdUp();
}
#endif
if( pluginDir.cd( "PlugIns" ) )
pluginDirs.append( pluginDir );
if( pluginDir.cd( GluonCore::DirectoryProvider::instance()->libDirectory() ) )
pluginDirs.append( pluginDir );
// this is the plugin dir on windows
if( pluginDir.cd( GluonCore::DirectoryProvider::instance()->libDirectory() + "/kde4" ) )
pluginDirs.append( pluginDir );
if( pluginDir.cd( GluonCore::DirectoryProvider::instance()->libDirectory() + "/gluon" ) )
pluginDirs.append( pluginDir );
if( pluginDir.cd( QDir::homePath() + "/gluonplugins" ) )
pluginDirs.append( pluginDir );
DEBUG_TEXT2( "Number of plugin locations: %1", pluginDirs.count() )
for( QList<QDir>::iterator theDir = pluginDirs.begin(); theDir != pluginDirs.end(); ++theDir )
{
DEBUG_TEXT( QString( "Looking for pluggable components in %1" ).arg( (*theDir).absolutePath() ) )
#ifdef Q_WS_X11
//Only attempt to load our current version. This makes it possible to have different versions
//of the plugins in the plugin dir.
(*theDir).setNameFilters( QStringList() << QString( "*.so.%1.%2.%3" ).arg( GLUON_VERSION_MAJOR ).arg( GLUON_VERSION_MINOR ).arg( GLUON_VERSION_PATCH ) );
#endif
(*theDir).setFilter( QDir::AllEntries| QDir::NoDotAndDotDot );
DEBUG_TEXT2( "Found %1 potential plugins. Attempting to load...", (*theDir).count() )
foreach( const QString & fileName, (*theDir).entryList( QDir::Files ) )
{
// Don't attempt to load non-gluon_plugin prefixed libraries
if( !fileName.contains( "gluon" ) )
continue;
// Don't attempt to load non-libraries
if( !QLibrary::isLibrary( (*theDir).absoluteFilePath( fileName ) ) )
continue;
QPluginLoader loader( (*theDir).absoluteFilePath( fileName ) );
loader.load();
if( !loader.isLoaded() )
{
DEBUG_TEXT( loader.errorString() )
}
}
}
DEBUG_TEXT2( "Total number of objects in factory after loading: %1", m_objectTypes.count() )
}
GluonObjectFactory::GluonObjectFactory ( QObject* parent )
: GluonCore::Singleton< GluonCore::GluonObjectFactory >( parent )
{
}
#include "gluonobjectfactory.moc"
<commit_msg>Use the DirectoryProvider for getting the plugin directory paths<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2009 Dan Leinir Turthra Jensen <admin@leinir.dk>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "gluonobjectfactory.h"
#include "directoryprovider.h"
#include "gluonobject.h"
#include "debughelper.h"
#include <QtGui/QApplication>
#include <QtCore/QDir>
#include <QtCore/QPluginLoader>
#include <QtCore/QVariant>
using namespace GluonCore;
GLUON_DEFINE_SINGLETON( GluonObjectFactory )
QStringList
GluonObjectFactory::objectTypeNames() const
{
QStringList theNames;
QHash<QString, const QMetaObject*>::const_iterator i;
for( i = m_objectTypes.constBegin(); i != m_objectTypes.constEnd(); ++i )
theNames << i.key();
return theNames;
}
QHash<QString, const QMetaObject*>
GluonObjectFactory::objectTypes() const
{
return m_objectTypes;
}
const QHash<QString, int>
GluonObjectFactory::objectTypeIDs() const
{
return m_objectTypeIDs;
}
QStringList
GluonObjectFactory::objectMimeTypes() const
{
return m_mimeTypes.keys();
}
GluonObject*
GluonObjectFactory::instantiateObjectByName( const QString& objectTypeName )
{
DEBUG_BLOCK
QString fullObjectTypeName( objectTypeName );
if( !objectTypeName.contains( "::" ) )
fullObjectTypeName = QString( "Gluon::" ) + fullObjectTypeName;
const QMetaObject* meta;
if( ( meta = m_objectTypes.value( objectTypeName, 0 ) ) )
{
GluonObject* obj = qobject_cast<GluonObject*>( meta->newInstance() );
if( obj )
{
return obj;
}
else
{
DEBUG_TEXT2( "If you are seeing this message, you have most likely failed to mark the constructor of %1 as Q_INVOKABLE", objectTypeName )
return 0;
}
}
DEBUG_TEXT( QString( "Object type named %1 not found in factory!" ).arg( objectTypeName ) )
return 0;
}
GluonObject*
GluonObjectFactory::instantiateObjectByMimetype( const QString& objectMimeType )
{
return instantiateObjectByName( m_mimeTypes[objectMimeType] );
}
QVariant
GluonObjectFactory::wrapObject( const QVariant& original, GluonObject* newValue )
{
DEBUG_BLOCK
QString type = original.typeName();
if( type.endsWith( '*' ) ) //Remove the * from the type
{
type = type.left( type.length() - 1 );
}
if( m_objectTypes.contains( type ) )
{
QScopedPointer<GluonObject> obj( instantiateObjectByName( type ) );
return obj->toVariant( newValue );
}
DEBUG_TEXT2( "Warning: Type %1 not found.", type )
return QVariant();
}
QVariant
GluonObjectFactory::wrapObject( const QString& type, GluonObject* newValue )
{
DEBUG_BLOCK
QString typeName = type;
if( type.endsWith( '*' ) )
typeName = type.left( type.length() - 1 );
if( m_objectTypes.contains( typeName ) )
{
QScopedPointer<GluonObject> obj( instantiateObjectByName( typeName ) );
return obj->toVariant( newValue );
}
DEBUG_TEXT2( "Warning: Type %1 not found.", typeName )
return QVariant();
}
GluonObject*
GluonObjectFactory::wrappedObject( const QVariant& wrappedObject )
{
QString type( wrappedObject.typeName() );
QString typeName = type;
if( type.endsWith( '*' ) )
typeName = type.left( type.length() - 1 );
if( m_objectTypes.contains( typeName ) )
{
QScopedPointer<GluonObject> obj( instantiateObjectByName( typeName ) );
return obj->fromVariant( wrappedObject );
}
DEBUG_BLOCK
DEBUG_TEXT2( "Warning: Type %1 not found.", typeName)
return 0;
}
void
GluonObjectFactory::loadPlugins()
{
DEBUG_FUNC_NAME
QStringList pluginDirectoryPaths = GluonCore::DirectoryProvider::instance()->pluginDirectoryPaths();
DEBUG_TEXT2( "Number of plugin locations: %1", pluginDirectoryPaths.count() )
foreach( const QString& pluginDirectoryPath, pluginDirectoryPaths )
{
QDir pluginDirectory( pluginDirectoryPath );
DEBUG_TEXT( QString( "Looking for pluggable components in %1" ).arg( pluginDirectory.absolutePath() ) )
#ifdef Q_WS_X11
//Only attempt to load our current version. This makes it possible to have different versions
//of the plugins in the plugin dir.
pluginDirectory.setNameFilters( QStringList() << QString( "*.so.%1.%2.%3" ).arg( GLUON_VERSION_MAJOR ).arg( GLUON_VERSION_MINOR ).arg( GLUON_VERSION_PATCH ) );
#endif
pluginDirectory.setFilter( QDir::AllEntries| QDir::NoDotAndDotDot );
DEBUG_TEXT2( "Found %1 potential plugins. Attempting to load...", pluginDirectory.count() )
foreach( const QString & fileName, pluginDirectory.entryList( QDir::Files ) )
{
// Don't attempt to load non-gluon_plugin prefixed libraries
if( !fileName.contains( "gluon" ) )
continue;
// Don't attempt to load non-libraries
if( !QLibrary::isLibrary( pluginDirectory.absoluteFilePath( fileName ) ) )
continue;
QPluginLoader loader( pluginDirectory.absoluteFilePath( fileName ) );
loader.load();
if( !loader.isLoaded() )
{
DEBUG_TEXT( loader.errorString() )
}
}
}
DEBUG_TEXT2( "Total number of objects in factory after loading: %1", m_objectTypes.count() )
}
GluonObjectFactory::GluonObjectFactory ( QObject* parent )
: GluonCore::Singleton< GluonCore::GluonObjectFactory >( parent )
{
}
#include "gluonobjectfactory.moc"
<|endoftext|> |
<commit_before>//*******************************************************************
//glfont2.cpp -- glFont Version 2.0 implementation
//Copyright (c) 1998-2002 Brad Fish
//See glfont.html for terms of use
//May 14, 2002
//*******************************************************************
//STL headers
#include <string>
#include <utility>
#include <iostream>
#include <fstream>
using namespace std;
//OpenGL headers
#ifdef _WINDOWS
#include <windows.h>
#endif
#include <GL/gl.h>
//glFont header
#include "glfont2.h"
using namespace glfont;
//*******************************************************************
//GLFont Class Implementation
//*******************************************************************
GLFont::GLFont ()
{
//Initialize header to safe state
header.tex = -1;
header.tex_width = 0;
header.tex_height = 0;
header.start_char = 0;
header.end_char = 0;
header.chars = NULL;
}
//*******************************************************************
GLFont::~GLFont ()
{
//Destroy the font
Destroy();
}
//*******************************************************************
bool GLFont::Create (const char *file_name, int tex)
{
ifstream input;
int num_chars, num_tex_bytes;
char *tex_bytes;
//Destroy the old font if there was one, just to be safe
Destroy();
//Open input file
input.open(file_name, ios::in | ios::binary);
if (!input)
return false;
//Read the header from file
input.read((char *)&header, sizeof(header));
header.tex = tex;
//Allocate space for character array
num_chars = header.end_char - header.start_char + 1;
if ((header.chars = new GLFontChar[num_chars]) == NULL)
return false;
//Read character array
for(int i=0; i < num_chars; i++)
input.read((char *)&header.chars[i], sizeof(GLFontChar));
//Read texture pixel data
num_tex_bytes = header.tex_width * header.tex_height * 2;
tex_bytes = new char[num_tex_bytes];
input.read(tex_bytes, num_tex_bytes);
//Create OpenGL texture
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexImage2D(GL_TEXTURE_2D, 0, 2, header.tex_width,
header.tex_height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE,
(void *)tex_bytes);
//Free texture pixels memory
delete[] tex_bytes;
//Close input file
input.close();
//Return successfully
return true;
}
//*******************************************************************
bool GLFont::Create (const std::string &file_name, int tex)
{
return Create(file_name.c_str(), tex);
}
//*******************************************************************
void GLFont::Destroy (void)
{
//Delete the character array if necessary
if (header.chars)
{
delete[] header.chars;
header.chars = NULL;
}
}
//*******************************************************************
void GLFont::GetTexSize (std::pair<int, int> *size)
{
//Retrieve texture size
size->first = header.tex_width;
size->second = header.tex_height;
}
//*******************************************************************
int GLFont::GetTexWidth (void)
{
//Return texture width
return header.tex_width;
}
//*******************************************************************
int GLFont::GetTexHeight (void)
{
//Return texture height
return header.tex_height;
}
//*******************************************************************
void GLFont::GetCharInterval (std::pair<int, int> *interval)
{
//Retrieve character interval
interval->first = header.start_char;
interval->second = header.end_char;
}
//*******************************************************************
int GLFont::GetStartChar (void)
{
//Return start character
return header.start_char;
}
//*******************************************************************
int GLFont::GetEndChar (void)
{
//Return end character
return header.end_char;
}
//*******************************************************************
void GLFont::GetCharSize (int c, std::pair<int, int> *size)
{
//Make sure character is in range
if (c < header.start_char || c > header.end_char)
{
//Not a valid character, so it obviously has no size
size->first = 0;
size->second = 0;
}
else
{
GLFontChar *glfont_char;
//Retrieve character size
glfont_char = &header.chars[c - header.start_char];
size->first = (int)(glfont_char->dx * header.tex_width);
size->second = (int)(glfont_char->dy *
header.tex_height);
}
}
//*******************************************************************
int GLFont::GetCharWidth (int c)
{
//Make sure in range
if (c < header.start_char || c > header.end_char)
return 0;
else
{
GLFontChar *glfont_char;
//Retrieve character width
glfont_char = &header.chars[c - header.start_char];
return (int)(glfont_char->dx * header.tex_width);
}
}
//*******************************************************************
int GLFont::GetCharHeight (int c)
{
//Make sure in range
if (c < header.start_char || c > header.end_char)
return 0;
else
{
GLFontChar *glfont_char;
//Retrieve character height
glfont_char = &header.chars[c - header.start_char];
return (int)(glfont_char->dy * header.tex_height);
}
}
//*******************************************************************
void GLFont::Begin (void)
{
//Bind to font texture
glBindTexture(GL_TEXTURE_2D, header.tex);
}
//*******************************************************************
//End of file
<commit_msg>64-bit debugging code<commit_after>//*******************************************************************
//glfont2.cpp -- glFont Version 2.0 implementation
//Copyright (c) 1998-2002 Brad Fish
//See glfont.html for terms of use
//May 14, 2002
//*******************************************************************
//STL headers
#include <string>
#include <utility>
#include <iostream>
#include <fstream>
using namespace std;
//OpenGL headers
#ifdef _WINDOWS
#include <windows.h>
#endif
#include <GL/gl.h>
//glFont header
#include "glfont2.h"
using namespace glfont;
//*******************************************************************
//GLFont Class Implementation
//*******************************************************************
GLFont::GLFont ()
{
//Initialize header to safe state
header.tex = -1;
header.tex_width = 0;
header.tex_height = 0;
header.start_char = 0;
header.end_char = 0;
header.chars = NULL;
}
//*******************************************************************
GLFont::~GLFont ()
{
//Destroy the font
Destroy();
}
//*******************************************************************
bool GLFont::Create (const char *file_name, int tex)
{
ifstream input;
int num_chars, num_tex_bytes;
char *tex_bytes;
//Destroy the old font if there was one, just to be safe
Destroy();
//Open input file
input.open(file_name, ios::in | ios::binary);
if (!input)
return false;
//Read the header from file
input.read((char *)&header, sizeof(header));
header.tex = tex;
//Allocate space for character array
num_chars = header.end_char - header.start_char + 1;
if ((header.chars = new GLFontChar[num_chars]) == NULL)
return false;
//Read character array
for(int i=0; i < num_chars; i++)
input.read((char *)&header.chars[i], sizeof(GLFontChar));
//Read texture pixel data
num_tex_bytes = header.tex_width * header.tex_height * 2;
tex_bytes = new char[num_tex_bytes];
input.read(tex_bytes, num_tex_bytes);
//Create OpenGL texture
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexImage2D(GL_TEXTURE_2D, 0, 2, header.tex_width,
header.tex_height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE,
(void *)tex_bytes);
//Free texture pixels memory
delete[] tex_bytes;
//Close input file
input.close();
//Return successfully
cout << "Start: " << header.start_char << ", End: " << header.end_char << ", Chars: " << header.chars << endl;
cout << "Height: " << header.tex_height << ", Width: " << header.tex_width << endl;
//Read character array
for(int i=header.start_char; i < header.end_char; i++)
{
GLFontChar c = header.chars[i - header.start_char];
cout << "Char: " << i << ", dx: " << c.dx << ", dy: " << c.dy << endl;
cout << "ty1: " << c.ty1 << ", ty2: " << c.ty2 << ", tx1: " << c.tx1 << ", tx2: " << c.tx2 << endl;
}
return true;
}
//*******************************************************************
bool GLFont::Create (const std::string &file_name, int tex)
{
return Create(file_name.c_str(), tex);
}
//*******************************************************************
void GLFont::Destroy (void)
{
//Delete the character array if necessary
if (header.chars)
{
delete[] header.chars;
header.chars = NULL;
}
}
//*******************************************************************
void GLFont::GetTexSize (std::pair<int, int> *size)
{
//Retrieve texture size
size->first = header.tex_width;
size->second = header.tex_height;
}
//*******************************************************************
int GLFont::GetTexWidth (void)
{
//Return texture width
return header.tex_width;
}
//*******************************************************************
int GLFont::GetTexHeight (void)
{
//Return texture height
return header.tex_height;
}
//*******************************************************************
void GLFont::GetCharInterval (std::pair<int, int> *interval)
{
//Retrieve character interval
interval->first = header.start_char;
interval->second = header.end_char;
}
//*******************************************************************
int GLFont::GetStartChar (void)
{
//Return start character
return header.start_char;
}
//*******************************************************************
int GLFont::GetEndChar (void)
{
//Return end character
return header.end_char;
}
//*******************************************************************
void GLFont::GetCharSize (int c, std::pair<int, int> *size)
{
//Make sure character is in range
if (c < header.start_char || c > header.end_char)
{
//Not a valid character, so it obviously has no size
size->first = 0;
size->second = 0;
}
else
{
GLFontChar *glfont_char;
//Retrieve character size
glfont_char = &header.chars[c - header.start_char];
size->first = (int)(glfont_char->dx * header.tex_width);
size->second = (int)(glfont_char->dy *
header.tex_height);
}
}
//*******************************************************************
int GLFont::GetCharWidth (int c)
{
//Make sure in range
if (c < header.start_char || c > header.end_char)
return 0;
else
{
GLFontChar *glfont_char;
//Retrieve character width
glfont_char = &header.chars[c - header.start_char];
return (int)(glfont_char->dx * header.tex_width);
}
}
//*******************************************************************
int GLFont::GetCharHeight (int c)
{
//Make sure in range
if (c < header.start_char || c > header.end_char)
return 0;
else
{
GLFontChar *glfont_char;
//Retrieve character height
glfont_char = &header.chars[c - header.start_char];
return (int)(glfont_char->dy * header.tex_height);
}
}
//*******************************************************************
void GLFont::Begin (void)
{
//Bind to font texture
glBindTexture(GL_TEXTURE_2D, header.tex);
}
//*******************************************************************
//End of file
<|endoftext|> |
<commit_before>/*
The code is licensed under the MIT License <http://opensource.org/licenses/MIT>:
Copyright (c) 2015-2017 Niels Lohmann.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef NLOHMANN_FIFO_MAP_HPP
#define NLOHMANN_FIFO_MAP_HPP
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <limits>
#include <map>
#include <memory>
#include <unordered_map>
#include <utility>
#include <vector>
/*!
@brief namespace for Niels Lohmann
@see https://github.com/nlohmann
*/
namespace nlohmann
{
template<class Key>
class fifo_map_compare
{
public:
/// constructor given a pointer to a key storage
fifo_map_compare(
std::unordered_map<Key, std::size_t>* k,
std::size_t timestamp = 1)
:
timestamp(timestamp),
keys(k)
{}
/*!
This function compares two keys with respect to the order in which they
were added to the container. For this, the mapping keys is used.
*/
bool operator()(const Key& lhs, const Key& rhs) const
{
// look up timestamps for both keys
const auto timestamp_lhs = keys->find(lhs);
const auto timestamp_rhs = keys->find(rhs);
if (timestamp_lhs == keys->end())
{
// timestamp for lhs not found - cannot be smaller than for rhs
return false;
}
if (timestamp_rhs == keys->end())
{
// timestamp for rhs not found - timestamp for lhs is smaller
return true;
}
// compare timestamps
return timestamp_lhs->second < timestamp_rhs->second;
}
void add_key(const Key& key)
{
keys->insert({key, timestamp++});
}
void remove_key(const Key& key)
{
keys->erase(key);
}
/// the next valid insertion timestamp
size_t timestamp = 1;
private:
/// pointer to a mapping from keys to insertion timestamps
std::unordered_map<Key, std::size_t>* keys = nullptr;
};
template <
class Key,
class T,
class Compare = fifo_map_compare<Key>,
class Allocator = std::allocator<std::pair<const Key, T>>
> class fifo_map
{
public:
using key_type = Key;
using mapped_type = T;
using value_type = std::pair<const Key, T>;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using key_compare = Compare;
using allocator_type = Allocator;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = typename std::allocator_traits<Allocator>::pointer;
using const_pointer = typename std::allocator_traits<Allocator>::const_pointer;
using internal_map_type = std::map<Key, T, Compare, Allocator>;
using iterator = typename internal_map_type::iterator;
using const_iterator = typename internal_map_type::const_iterator;
using reverse_iterator = typename internal_map_type::reverse_iterator;
using const_reverse_iterator = typename internal_map_type::const_reverse_iterator;
public:
/// default constructor
fifo_map() : m_keys(), m_compare(&m_keys), m_map(m_compare) {}
/// copy constructor
fifo_map(const fifo_map &f) : m_keys(f.m_keys), m_compare(&m_keys, f.m_compare.timestamp), m_map(f.m_map.begin(), f.m_map.end(), m_compare) {}
/// constructor for a range of elements
template<class InputIterator>
fifo_map(InputIterator first, InputIterator last)
: m_keys(), m_compare(&m_keys), m_map(m_compare)
{
for (auto it = first; it != last; ++it)
{
insert(*it);
}
}
/// constructor for a list of elements
fifo_map(std::initializer_list<value_type> init) : fifo_map()
{
for (auto x : init)
{
insert(x);
}
}
/*
* Element access
*/
/// access specified element with bounds checking
T& at(const Key& key)
{
return m_map.at(key);
}
/// access specified element with bounds checking
const T& at(const Key& key) const
{
return m_map.at(key);
}
/// access specified element
T& operator[](const Key& key)
{
m_compare.add_key(key);
return m_map[key];
}
/// access specified element
T& operator[](Key&& key)
{
m_compare.add_key(key);
return m_map[key];
}
/*
* Iterators
*/
/// returns an iterator to the beginning
iterator begin() noexcept
{
return m_map.begin();
}
/// returns an iterator to the end
iterator end() noexcept
{
return m_map.end();
}
/// returns an iterator to the beginning
const_iterator begin() const noexcept
{
return m_map.begin();
}
/// returns an iterator to the end
const_iterator end() const noexcept
{
return m_map.end();
}
/// returns an iterator to the beginning
const_iterator cbegin() const noexcept
{
return m_map.cbegin();
}
/// returns an iterator to the end
const_iterator cend() const noexcept
{
return m_map.cend();
}
/// returns a reverse iterator to the beginning
reverse_iterator rbegin() noexcept
{
return m_map.rbegin();
}
/// returns a reverse iterator to the end
reverse_iterator rend() noexcept
{
return m_map.rend();
}
/// returns a reverse iterator to the beginning
const_reverse_iterator rbegin() const noexcept
{
return m_map.rbegin();
}
/// returns a reverse iterator to the end
const_reverse_iterator rend() const noexcept
{
return m_map.rend();
}
/// returns a reverse iterator to the beginning
const_reverse_iterator crbegin() const noexcept
{
return m_map.crbegin();
}
/// returns a reverse iterator to the end
const_reverse_iterator crend() const noexcept
{
return m_map.crend();
}
/*
* Capacity
*/
/// checks whether the container is empty
bool empty() const noexcept
{
return m_map.empty();
}
/// returns the number of elements
size_type size() const noexcept
{
return m_map.size();
}
/// returns the maximum possible number of elements
size_type max_size() const noexcept
{
return m_map.max_size();
}
/*
* Modifiers
*/
/// clears the contents
void clear() noexcept
{
m_map.clear();
m_keys.clear();
}
/// insert value
std::pair<iterator, bool> insert(const value_type& value)
{
m_compare.add_key(value.first);
return m_map.insert(value);
}
/// insert value
template<class P>
std::pair<iterator, bool> insert( P&& value )
{
m_compare.add_key(value.first);
return m_map.insert(value);
}
/// insert value with hint
iterator insert(const_iterator hint, const value_type& value)
{
m_compare.add_key(value.first);
return m_map.insert(hint, value);
}
/// insert value with hint
iterator insert(const_iterator hint, value_type&& value)
{
m_compare.add_key(value.first);
return m_map.insert(hint, value);
}
/// insert value range
template<class InputIt>
void insert(InputIt first, InputIt last)
{
for (const_iterator it = first; it != last; ++it)
{
m_compare.add_key(it->first);
}
m_map.insert(first, last);
}
/// insert value list
void insert(std::initializer_list<value_type> ilist)
{
for (auto value : ilist)
{
m_compare.add_key(value.first);
}
m_map.insert(ilist);
}
/// constructs element in-place
template<class... Args>
std::pair<iterator, bool> emplace(Args&& ... args)
{
typename fifo_map::value_type value(std::forward<Args>(args)...);
m_compare.add_key(value.first);
return m_map.emplace(std::move(value));
}
/// constructs element in-place with hint
template<class... Args>
iterator emplace_hint(const_iterator hint, Args&& ... args)
{
typename fifo_map::value_type value(std::forward<Args>(args)...);
m_compare.add_key(value.first);
return m_map.emplace_hint(hint, std::move(value));
}
/// remove element at position
iterator erase(const_iterator pos)
{
m_compare.remove_key(pos->first);
return m_map.erase(pos);
}
/// remove elements in range
iterator erase(const_iterator first, const_iterator last)
{
for (const_iterator it = first; it != last; ++it)
{
m_compare.remove_key(it->first);
}
return m_map.erase(first, last);
}
/// remove elements with key
size_type erase(const key_type& key)
{
size_type res = m_map.erase(key);
if (res > 0)
{
m_compare.remove_key(key);
}
return res;
}
/// swaps the contents
void swap(fifo_map& other)
{
std::swap(m_map, other.m_map);
std::swap(m_compare, other.m_compare);
std::swap(m_keys, other.m_keys);
}
/*
* Lookup
*/
/// returns the number of elements matching specific key
size_type count(const Key& key) const
{
return m_map.count(key);
}
/// finds element with specific key
iterator find(const Key& key)
{
return m_map.find(key);
}
/// finds element with specific key
const_iterator find(const Key& key) const
{
return m_map.find(key);
}
/// returns range of elements matching a specific key
std::pair<iterator, iterator> equal_range(const Key& key)
{
return m_map.equal_range(key);
}
/// returns range of elements matching a specific key
std::pair<const_iterator, const_iterator> equal_range(const Key& key) const
{
return m_map.equal_range(key);
}
/// returns an iterator to the first element not less than the given key
iterator lower_bound(const Key& key)
{
return m_map.lower_bound(key);
}
/// returns an iterator to the first element not less than the given key
const_iterator lower_bound(const Key& key) const
{
return m_map.lower_bound(key);
}
/// returns an iterator to the first element greater than the given key
iterator upper_bound(const Key& key)
{
return m_map.upper_bound(key);
}
/// returns an iterator to the first element greater than the given key
const_iterator upper_bound(const Key& key) const
{
return m_map.upper_bound(key);
}
/*
* Observers
*/
/// returns the function that compares keys
key_compare key_comp() const
{
return m_compare;
}
/*
* Non-member functions
*/
friend bool operator==(const fifo_map& lhs, const fifo_map& rhs)
{
return lhs.m_map == rhs.m_map;
}
friend bool operator!=(const fifo_map& lhs, const fifo_map& rhs)
{
return lhs.m_map != rhs.m_map;
}
friend bool operator<(const fifo_map& lhs, const fifo_map& rhs)
{
return lhs.m_map < rhs.m_map;
}
friend bool operator<=(const fifo_map& lhs, const fifo_map& rhs)
{
return lhs.m_map <= rhs.m_map;
}
friend bool operator>(const fifo_map& lhs, const fifo_map& rhs)
{
return lhs.m_map > rhs.m_map;
}
friend bool operator>=(const fifo_map& lhs, const fifo_map& rhs)
{
return lhs.m_map >= rhs.m_map;
}
private:
/// the keys
std::unordered_map<Key, std::size_t> m_keys;
/// the comparison object
Compare m_compare;
/// the internal data structure
internal_map_type m_map;
};
}
// specialization of std::swap
namespace std
{
template <class Key, class T, class Compare, class Allocator>
inline void swap(nlohmann::fifo_map<Key, T, Compare, Allocator>& m1,
nlohmann::fifo_map<Key, T, Compare, Allocator>& m2)
{
m1.swap(m2);
}
}
#endif
<commit_msg>Add timestamp getter<commit_after>/*
The code is licensed under the MIT License <http://opensource.org/licenses/MIT>:
Copyright (c) 2015-2017 Niels Lohmann.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef NLOHMANN_FIFO_MAP_HPP
#define NLOHMANN_FIFO_MAP_HPP
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <limits>
#include <map>
#include <memory>
#include <unordered_map>
#include <utility>
#include <vector>
/*!
@brief namespace for Niels Lohmann
@see https://github.com/nlohmann
*/
namespace nlohmann
{
template<class Key>
class fifo_map_compare
{
public:
/// constructor given a pointer to a key storage
fifo_map_compare(
std::unordered_map<Key, std::size_t>* keys,
std::size_t timestamp = 1)
:
m_timestamp(timestamp),
m_keys(keys)
{}
/*!
This function compares two keys with respect to the order in which they
were added to the container. For this, the mapping keys is used.
*/
bool operator()(const Key& lhs, const Key& rhs) const
{
// look up timestamps for both keys
const auto timestamp_lhs = m_keys->find(lhs);
const auto timestamp_rhs = m_keys->find(rhs);
if (timestamp_lhs == m_keys->end())
{
// timestamp for lhs not found - cannot be smaller than for rhs
return false;
}
if (timestamp_rhs == m_keys->end())
{
// timestamp for rhs not found - timestamp for lhs is smaller
return true;
}
// compare timestamps
return timestamp_lhs->second < timestamp_rhs->second;
}
void add_key(const Key& key)
{
m_keys->insert({key, m_timestamp++});
}
void remove_key(const Key& key)
{
m_keys->erase(key);
}
std::size_t timestamp() const
{
return m_timestamp;
}
private:
/// the next valid insertion timestamp
std::size_t m_timestamp = 1;
/// pointer to a mapping from keys to insertion timestamps
std::unordered_map<Key, std::size_t>* m_keys = nullptr;
};
template <
class Key,
class T,
class Compare = fifo_map_compare<Key>,
class Allocator = std::allocator<std::pair<const Key, T>>
> class fifo_map
{
public:
using key_type = Key;
using mapped_type = T;
using value_type = std::pair<const Key, T>;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using key_compare = Compare;
using allocator_type = Allocator;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = typename std::allocator_traits<Allocator>::pointer;
using const_pointer = typename std::allocator_traits<Allocator>::const_pointer;
using internal_map_type = std::map<Key, T, Compare, Allocator>;
using iterator = typename internal_map_type::iterator;
using const_iterator = typename internal_map_type::const_iterator;
using reverse_iterator = typename internal_map_type::reverse_iterator;
using const_reverse_iterator = typename internal_map_type::const_reverse_iterator;
public:
/// default constructor
fifo_map() : m_keys(), m_compare(&m_keys), m_map(m_compare) {}
/// copy constructor
fifo_map(const fifo_map &f) : m_keys(f.m_keys), m_compare(&m_keys, f.m_compare.timestamp()), m_map(f.m_map.begin(), f.m_map.end(), m_compare) {}
/// constructor for a range of elements
template<class InputIterator>
fifo_map(InputIterator first, InputIterator last)
: m_keys(), m_compare(&m_keys), m_map(m_compare)
{
for (auto it = first; it != last; ++it)
{
insert(*it);
}
}
/// constructor for a list of elements
fifo_map(std::initializer_list<value_type> init) : fifo_map()
{
for (auto x : init)
{
insert(x);
}
}
/*
* Element access
*/
/// access specified element with bounds checking
T& at(const Key& key)
{
return m_map.at(key);
}
/// access specified element with bounds checking
const T& at(const Key& key) const
{
return m_map.at(key);
}
/// access specified element
T& operator[](const Key& key)
{
m_compare.add_key(key);
return m_map[key];
}
/// access specified element
T& operator[](Key&& key)
{
m_compare.add_key(key);
return m_map[key];
}
/*
* Iterators
*/
/// returns an iterator to the beginning
iterator begin() noexcept
{
return m_map.begin();
}
/// returns an iterator to the end
iterator end() noexcept
{
return m_map.end();
}
/// returns an iterator to the beginning
const_iterator begin() const noexcept
{
return m_map.begin();
}
/// returns an iterator to the end
const_iterator end() const noexcept
{
return m_map.end();
}
/// returns an iterator to the beginning
const_iterator cbegin() const noexcept
{
return m_map.cbegin();
}
/// returns an iterator to the end
const_iterator cend() const noexcept
{
return m_map.cend();
}
/// returns a reverse iterator to the beginning
reverse_iterator rbegin() noexcept
{
return m_map.rbegin();
}
/// returns a reverse iterator to the end
reverse_iterator rend() noexcept
{
return m_map.rend();
}
/// returns a reverse iterator to the beginning
const_reverse_iterator rbegin() const noexcept
{
return m_map.rbegin();
}
/// returns a reverse iterator to the end
const_reverse_iterator rend() const noexcept
{
return m_map.rend();
}
/// returns a reverse iterator to the beginning
const_reverse_iterator crbegin() const noexcept
{
return m_map.crbegin();
}
/// returns a reverse iterator to the end
const_reverse_iterator crend() const noexcept
{
return m_map.crend();
}
/*
* Capacity
*/
/// checks whether the container is empty
bool empty() const noexcept
{
return m_map.empty();
}
/// returns the number of elements
size_type size() const noexcept
{
return m_map.size();
}
/// returns the maximum possible number of elements
size_type max_size() const noexcept
{
return m_map.max_size();
}
/*
* Modifiers
*/
/// clears the contents
void clear() noexcept
{
m_map.clear();
m_keys.clear();
}
/// insert value
std::pair<iterator, bool> insert(const value_type& value)
{
m_compare.add_key(value.first);
return m_map.insert(value);
}
/// insert value
template<class P>
std::pair<iterator, bool> insert( P&& value )
{
m_compare.add_key(value.first);
return m_map.insert(value);
}
/// insert value with hint
iterator insert(const_iterator hint, const value_type& value)
{
m_compare.add_key(value.first);
return m_map.insert(hint, value);
}
/// insert value with hint
iterator insert(const_iterator hint, value_type&& value)
{
m_compare.add_key(value.first);
return m_map.insert(hint, value);
}
/// insert value range
template<class InputIt>
void insert(InputIt first, InputIt last)
{
for (const_iterator it = first; it != last; ++it)
{
m_compare.add_key(it->first);
}
m_map.insert(first, last);
}
/// insert value list
void insert(std::initializer_list<value_type> ilist)
{
for (auto value : ilist)
{
m_compare.add_key(value.first);
}
m_map.insert(ilist);
}
/// constructs element in-place
template<class... Args>
std::pair<iterator, bool> emplace(Args&& ... args)
{
typename fifo_map::value_type value(std::forward<Args>(args)...);
m_compare.add_key(value.first);
return m_map.emplace(std::move(value));
}
/// constructs element in-place with hint
template<class... Args>
iterator emplace_hint(const_iterator hint, Args&& ... args)
{
typename fifo_map::value_type value(std::forward<Args>(args)...);
m_compare.add_key(value.first);
return m_map.emplace_hint(hint, std::move(value));
}
/// remove element at position
iterator erase(const_iterator pos)
{
m_compare.remove_key(pos->first);
return m_map.erase(pos);
}
/// remove elements in range
iterator erase(const_iterator first, const_iterator last)
{
for (const_iterator it = first; it != last; ++it)
{
m_compare.remove_key(it->first);
}
return m_map.erase(first, last);
}
/// remove elements with key
size_type erase(const key_type& key)
{
size_type res = m_map.erase(key);
if (res > 0)
{
m_compare.remove_key(key);
}
return res;
}
/// swaps the contents
void swap(fifo_map& other)
{
std::swap(m_map, other.m_map);
std::swap(m_compare, other.m_compare);
std::swap(m_keys, other.m_keys);
}
/*
* Lookup
*/
/// returns the number of elements matching specific key
size_type count(const Key& key) const
{
return m_map.count(key);
}
/// finds element with specific key
iterator find(const Key& key)
{
return m_map.find(key);
}
/// finds element with specific key
const_iterator find(const Key& key) const
{
return m_map.find(key);
}
/// returns range of elements matching a specific key
std::pair<iterator, iterator> equal_range(const Key& key)
{
return m_map.equal_range(key);
}
/// returns range of elements matching a specific key
std::pair<const_iterator, const_iterator> equal_range(const Key& key) const
{
return m_map.equal_range(key);
}
/// returns an iterator to the first element not less than the given key
iterator lower_bound(const Key& key)
{
return m_map.lower_bound(key);
}
/// returns an iterator to the first element not less than the given key
const_iterator lower_bound(const Key& key) const
{
return m_map.lower_bound(key);
}
/// returns an iterator to the first element greater than the given key
iterator upper_bound(const Key& key)
{
return m_map.upper_bound(key);
}
/// returns an iterator to the first element greater than the given key
const_iterator upper_bound(const Key& key) const
{
return m_map.upper_bound(key);
}
/*
* Observers
*/
/// returns the function that compares keys
key_compare key_comp() const
{
return m_compare;
}
/*
* Non-member functions
*/
friend bool operator==(const fifo_map& lhs, const fifo_map& rhs)
{
return lhs.m_map == rhs.m_map;
}
friend bool operator!=(const fifo_map& lhs, const fifo_map& rhs)
{
return lhs.m_map != rhs.m_map;
}
friend bool operator<(const fifo_map& lhs, const fifo_map& rhs)
{
return lhs.m_map < rhs.m_map;
}
friend bool operator<=(const fifo_map& lhs, const fifo_map& rhs)
{
return lhs.m_map <= rhs.m_map;
}
friend bool operator>(const fifo_map& lhs, const fifo_map& rhs)
{
return lhs.m_map > rhs.m_map;
}
friend bool operator>=(const fifo_map& lhs, const fifo_map& rhs)
{
return lhs.m_map >= rhs.m_map;
}
private:
/// the keys
std::unordered_map<Key, std::size_t> m_keys;
/// the comparison object
Compare m_compare;
/// the internal data structure
internal_map_type m_map;
};
}
// specialization of std::swap
namespace std
{
template <class Key, class T, class Compare, class Allocator>
inline void swap(nlohmann::fifo_map<Key, T, Compare, Allocator>& m1,
nlohmann::fifo_map<Key, T, Compare, Allocator>& m2)
{
m1.swap(m2);
}
}
#endif
<|endoftext|> |
<commit_before>/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2013-2020 Couchbase, 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 "hostlist.h"
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include <algorithm>
#include <string>
using namespace lcb;
Hostlist::~Hostlist()
{
reset_strlist();
}
void
Hostlist::reset_strlist()
{
for (size_t ii = 0; ii < hoststrs.size(); ++ii) {
if (hoststrs[ii] != NULL) {
delete[] hoststrs[ii];
}
}
hoststrs.clear();
}
lcb_STATUS
lcb_host_parse(lcb_host_t *host, const char *spec, int speclen, int deflport)
{
std::vector<char> zspec;
char *host_s;
char *port_s;
char *delim;
bool ipv6 = false;
/** Parse the host properly */
if (speclen < 0) {
speclen = strlen(spec);
} else if (speclen == 0) {
return LCB_ERR_INVALID_HOST_FORMAT;
}
if (deflport < 1) {
return LCB_ERR_INVALID_HOST_FORMAT;
}
zspec.assign(spec, spec + speclen);
zspec.push_back('\0');
host_s = &zspec[0];
if ( (delim = strstr(host_s, "://"))) {
host_s = delim + 3;
}
if ((delim = strstr(host_s, "/"))) {
*delim = '\0';
}
port_s = strstr(host_s, ":");
if (port_s != NULL && strstr(port_s + 1, ":") != NULL) {
ipv6 = true;
// treat as IPv6 address
if (host_s[0] == '[') {
host_s++;
char *hostend = strstr(host_s, "]");
if (hostend == NULL) {
return LCB_ERR_INVALID_HOST_FORMAT;
}
port_s = hostend + 1;
if (*port_s != ':' || (size_t)(port_s - host_s) >= strlen(host_s)) {
port_s = NULL;
}
*hostend = '\0';
} else {
port_s = NULL;
}
}
if (port_s != NULL) {
char *endp;
long ll;
*port_s = '\0';
port_s++;
if (! *port_s) {
return LCB_ERR_INVALID_HOST_FORMAT;
}
ll = strtol(port_s, &endp, 10);
if (ll == LONG_MIN || ll == LONG_MAX) {
return LCB_ERR_INVALID_HOST_FORMAT;
}
if (*endp) {
return LCB_ERR_INVALID_HOST_FORMAT;
}
} else {
port_s = const_cast<char*>("");
}
if (strlen(host_s) > sizeof(host->host)-1 ||
strlen(port_s) > sizeof(host->port)-1 ||
*host_s == '\0') {
return LCB_ERR_INVALID_HOST_FORMAT;
}
size_t ii, hostlen = strlen(host_s);
for (ii = 0; ii < hostlen; ii++) {
if (isalnum(host_s[ii])) {
continue;
}
switch (host_s[ii]) {
case '.':
case '-':
case '_':
break;
case ':':
case '[':
case ']':
if (ipv6) {
break;
}
/* fallthrough */
default:
return LCB_ERR_INVALID_HOST_FORMAT;
}
}
strcpy(host->host, host_s);
if (*port_s) {
strcpy(host->port, port_s);
} else {
sprintf(host->port, "%d", deflport);
}
host->ipv6 = ipv6;
return LCB_SUCCESS;
}
int lcb_host_equals(const lcb_host_t *a, const lcb_host_t *b)
{
return strcmp(a->host, b->host) == 0 && strcmp(a->port, b->port) == 0;
}
bool
Hostlist::exists(const lcb_host_t& host) const
{
for (size_t ii = 0; ii < hosts.size(); ++ii) {
if (lcb_host_equals(&host, &hosts[ii])) {
return true;
}
}
return false;
}
bool
Hostlist::exists(const char *s) const
{
lcb_host_t tmp = {"", "", 0};
if (lcb_host_parse(&tmp, s, -1, 1) != LCB_SUCCESS) {
return false;
}
return exists(tmp);
}
void
Hostlist::add(const lcb_host_t& host)
{
if (exists(host)) {
return;
}
hosts.push_back(host);
reset_strlist();
}
lcb_STATUS
Hostlist::add(const char *hostport, long len, int deflport)
{
lcb_STATUS err = LCB_SUCCESS;
if (len < 0) {
len = strlen(hostport);
}
std::string ss(hostport, len);
if (ss.empty()) {
return LCB_SUCCESS;
}
if (ss[ss.length()-1] != ';') {
ss += ';';
}
const char *curstart = ss.c_str();
const char *delim;
while ( (delim = strstr(curstart, ";"))) {
lcb_host_t curhost = {"", "", 0};
size_t curlen;
if (delim == curstart) {
curstart++;
continue;
}
/** { 'f', 'o', 'o', ';' } */
curlen = delim - curstart;
err = lcb_host_parse(&curhost, curstart, curlen, deflport);
if (err != LCB_SUCCESS) {
return err;
}
add(curhost);
curstart = delim + 1;
}
return LCB_SUCCESS;
}
lcb_host_t *
Hostlist::next(bool wrap)
{
lcb_host_t *ret;
if (empty()) {
return NULL;
}
if (ix == size()) {
if (wrap) {
ix = 0;
} else {
return NULL;
}
}
ret = &hosts[ix];
ix++;
return ret;
}
void
Hostlist::randomize()
{
std::random_shuffle(hosts.begin(), hosts.end());
reset_strlist();
}
void Hostlist::ensure_strlist() {
if (hoststrs.size()) {
return;
}
for (size_t ii = 0; ii < hosts.size(); ii++) {
const lcb_host_t& host = hosts[ii];
std::string ss;
if (host.ipv6) {
ss.append("[").append(host.host).append("]");
} else {
ss.append(host.host);
}
ss.append(":").append(host.port);
char *newstr = new char[ss.size() + 1];
newstr[ss.size()] = '\0';
memcpy(newstr, ss.c_str(), ss.size());
hoststrs.push_back(newstr);
}
hoststrs.push_back(NULL);
}
Hostlist&
Hostlist::assign(const Hostlist& src)
{
clear();
reset_strlist();
for (size_t ii = 0; ii < src.size(); ++ii) {
add(src.hosts[ii]);
}
return *this;
}
<commit_msg>Remove use of deprecated function std::random_shuffle<commit_after>/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2013-2020 Couchbase, 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 "hostlist.h"
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include <algorithm>
#include <random>
#include <string>
using namespace lcb;
Hostlist::~Hostlist()
{
reset_strlist();
}
void
Hostlist::reset_strlist()
{
for (size_t ii = 0; ii < hoststrs.size(); ++ii) {
if (hoststrs[ii] != NULL) {
delete[] hoststrs[ii];
}
}
hoststrs.clear();
}
lcb_STATUS
lcb_host_parse(lcb_host_t *host, const char *spec, int speclen, int deflport)
{
std::vector<char> zspec;
char *host_s;
char *port_s;
char *delim;
bool ipv6 = false;
/** Parse the host properly */
if (speclen < 0) {
speclen = strlen(spec);
} else if (speclen == 0) {
return LCB_ERR_INVALID_HOST_FORMAT;
}
if (deflport < 1) {
return LCB_ERR_INVALID_HOST_FORMAT;
}
zspec.assign(spec, spec + speclen);
zspec.push_back('\0');
host_s = &zspec[0];
if ( (delim = strstr(host_s, "://"))) {
host_s = delim + 3;
}
if ((delim = strstr(host_s, "/"))) {
*delim = '\0';
}
port_s = strstr(host_s, ":");
if (port_s != NULL && strstr(port_s + 1, ":") != NULL) {
ipv6 = true;
// treat as IPv6 address
if (host_s[0] == '[') {
host_s++;
char *hostend = strstr(host_s, "]");
if (hostend == NULL) {
return LCB_ERR_INVALID_HOST_FORMAT;
}
port_s = hostend + 1;
if (*port_s != ':' || (size_t)(port_s - host_s) >= strlen(host_s)) {
port_s = NULL;
}
*hostend = '\0';
} else {
port_s = NULL;
}
}
if (port_s != NULL) {
char *endp;
long ll;
*port_s = '\0';
port_s++;
if (! *port_s) {
return LCB_ERR_INVALID_HOST_FORMAT;
}
ll = strtol(port_s, &endp, 10);
if (ll == LONG_MIN || ll == LONG_MAX) {
return LCB_ERR_INVALID_HOST_FORMAT;
}
if (*endp) {
return LCB_ERR_INVALID_HOST_FORMAT;
}
} else {
port_s = const_cast<char*>("");
}
if (strlen(host_s) > sizeof(host->host)-1 ||
strlen(port_s) > sizeof(host->port)-1 ||
*host_s == '\0') {
return LCB_ERR_INVALID_HOST_FORMAT;
}
size_t ii, hostlen = strlen(host_s);
for (ii = 0; ii < hostlen; ii++) {
if (isalnum(host_s[ii])) {
continue;
}
switch (host_s[ii]) {
case '.':
case '-':
case '_':
break;
case ':':
case '[':
case ']':
if (ipv6) {
break;
}
/* fallthrough */
default:
return LCB_ERR_INVALID_HOST_FORMAT;
}
}
strcpy(host->host, host_s);
if (*port_s) {
strcpy(host->port, port_s);
} else {
sprintf(host->port, "%d", deflport);
}
host->ipv6 = ipv6;
return LCB_SUCCESS;
}
int lcb_host_equals(const lcb_host_t *a, const lcb_host_t *b)
{
return strcmp(a->host, b->host) == 0 && strcmp(a->port, b->port) == 0;
}
bool
Hostlist::exists(const lcb_host_t& host) const
{
for (size_t ii = 0; ii < hosts.size(); ++ii) {
if (lcb_host_equals(&host, &hosts[ii])) {
return true;
}
}
return false;
}
bool
Hostlist::exists(const char *s) const
{
lcb_host_t tmp = {"", "", 0};
if (lcb_host_parse(&tmp, s, -1, 1) != LCB_SUCCESS) {
return false;
}
return exists(tmp);
}
void
Hostlist::add(const lcb_host_t& host)
{
if (exists(host)) {
return;
}
hosts.push_back(host);
reset_strlist();
}
lcb_STATUS
Hostlist::add(const char *hostport, long len, int deflport)
{
lcb_STATUS err = LCB_SUCCESS;
if (len < 0) {
len = strlen(hostport);
}
std::string ss(hostport, len);
if (ss.empty()) {
return LCB_SUCCESS;
}
if (ss[ss.length()-1] != ';') {
ss += ';';
}
const char *curstart = ss.c_str();
const char *delim;
while ( (delim = strstr(curstart, ";"))) {
lcb_host_t curhost = {"", "", 0};
size_t curlen;
if (delim == curstart) {
curstart++;
continue;
}
/** { 'f', 'o', 'o', ';' } */
curlen = delim - curstart;
err = lcb_host_parse(&curhost, curstart, curlen, deflport);
if (err != LCB_SUCCESS) {
return err;
}
add(curhost);
curstart = delim + 1;
}
return LCB_SUCCESS;
}
lcb_host_t *
Hostlist::next(bool wrap)
{
lcb_host_t *ret;
if (empty()) {
return NULL;
}
if (ix == size()) {
if (wrap) {
ix = 0;
} else {
return NULL;
}
}
ret = &hosts[ix];
ix++;
return ret;
}
void
Hostlist::randomize()
{
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(hosts.begin(), hosts.end(), g);
reset_strlist();
}
void Hostlist::ensure_strlist() {
if (hoststrs.size()) {
return;
}
for (size_t ii = 0; ii < hosts.size(); ii++) {
const lcb_host_t& host = hosts[ii];
std::string ss;
if (host.ipv6) {
ss.append("[").append(host.host).append("]");
} else {
ss.append(host.host);
}
ss.append(":").append(host.port);
char *newstr = new char[ss.size() + 1];
newstr[ss.size()] = '\0';
memcpy(newstr, ss.c_str(), ss.size());
hoststrs.push_back(newstr);
}
hoststrs.push_back(NULL);
}
Hostlist&
Hostlist::assign(const Hostlist& src)
{
clear();
reset_strlist();
for (size_t ii = 0; ii < src.size(); ++ii) {
add(src.hosts[ii]);
}
return *this;
}
<|endoftext|> |
<commit_before>#include "mvtSource.h"
#include "tileData.h"
#include "tile/tileID.h"
#include "tile/tile.h"
#include "tile/tileTask.h"
#include "util/pbfParser.h"
#include "platform.h"
namespace Tangram {
MVTSource::MVTSource(const std::string& _name, const std::string& _urlTemplate,
int32_t _minDisplayZoom, int32_t _maxDisplayZoom, int32_t _maxZoom) :
DataSource(_name, _urlTemplate, _minDisplayZoom, _maxDisplayZoom, _maxZoom) {
}
std::shared_ptr<TileData> MVTSource::parse(const TileTask& _task, const MapProjection& _projection) const {
auto tileData = std::make_shared<TileData>();
auto& task = static_cast<const DownloadTileTask&>(_task);
protobuf::message item(task.rawTileData->data(), task.rawTileData->size());
PbfParser::ParserContext ctx(m_id);
while(item.next()) {
if(item.tag == 3) {
tileData->layers.push_back(PbfParser::getLayer(ctx, item.getMessage()));
} else {
item.skip();
}
}
return tileData;
}
}
<commit_msg>MVTSource: catch exceptions from protobuf parser (#1105)<commit_after>#include "mvtSource.h"
#include "tileData.h"
#include "tile/tileID.h"
#include "tile/tile.h"
#include "tile/tileTask.h"
#include "util/pbfParser.h"
#include "log.h"
namespace Tangram {
MVTSource::MVTSource(const std::string& _name, const std::string& _urlTemplate,
int32_t _minDisplayZoom, int32_t _maxDisplayZoom, int32_t _maxZoom) :
DataSource(_name, _urlTemplate, _minDisplayZoom, _maxDisplayZoom, _maxZoom) {
}
std::shared_ptr<TileData> MVTSource::parse(const TileTask& _task, const MapProjection& _projection) const {
auto tileData = std::make_shared<TileData>();
auto& task = static_cast<const DownloadTileTask&>(_task);
protobuf::message item(task.rawTileData->data(), task.rawTileData->size());
PbfParser::ParserContext ctx(m_id);
try {
while(item.next()) {
if(item.tag == 3) {
tileData->layers.push_back(PbfParser::getLayer(ctx, item.getMessage()));
} else {
item.skip();
}
}
} catch(const std::invalid_argument& e) {
LOGE("Cannot parse tile %s: %s", _task.tileId().toString().c_str(), e.what());
return {};
} catch(const std::runtime_error& e) {
LOGE("Cannot parse tile %s: %s", _task.tileId().toString().c_str(), e.what());
return {};
} catch(...) {
return {};
}
return tileData;
}
}
<|endoftext|> |
<commit_before>#include "entities/Element.hpp"
#include "LodRange.hpp"
#include "formats/shape/ShapeDataVisitor.hpp"
#include "formats/shape/ShapeParser.hpp"
#include "formats/osm/xml/OsmXmlParser.hpp"
#include "formats/osm/pbf/OsmPbfParser.hpp"
#include "formats/osm/OsmDataVisitor.hpp"
#include "index/GeoStore.hpp"
#include "index/InMemoryElementStore.hpp"
#include "index/PersistentElementStore.hpp"
#include "utils/CoreUtils.hpp"
#include <set>
#include <map>
#include <memory>
using namespace utymap::entities;
using namespace utymap::formats;
using namespace utymap::index;
using namespace utymap::mapcss;
class GeoStore::GeoStoreImpl
{
// Prevents to visit element twice if it exists in multiply stores.
class FilterElementVisitor : public ElementVisitor
{
public:
FilterElementVisitor(const QuadKey& quadKey, const StyleProvider& styleProvider, ElementVisitor& visitor)
: visitor_(visitor), quadKey_(quadKey), styleProvider_(styleProvider), ids_()
{
}
void visitNode(const Node& node) { visitIfNecessary(node); }
void visitWay(const Way& way) { visitIfNecessary(way); }
void visitArea(const Area& area) { visitIfNecessary(area); }
void visitRelation(const Relation& relation) { visitIfNecessary(relation); }
private:
inline void visitIfNecessary(const Element& element)
{
if (element.id == 0 || ids_.find(element.id) == ids_.end() ||
styleProvider_.hasStyle(element, quadKey_.levelOfDetail)) {
element.accept(visitor_);
ids_.insert(element.id);
}
}
const QuadKey& quadKey_;
const StyleProvider& styleProvider_;
ElementVisitor& visitor_;
std::set<std::uint64_t> ids_;
};
public:
GeoStoreImpl(StringTable& stringTable) :
stringTable_(stringTable)
{
}
void registerStore(const std::string& storeKey, const std::shared_ptr<ElementStore>& store)
{
storeMap_[storeKey] = store;
}
void add(const std::string& storeKey, const Element& element, const LodRange& range, const StyleProvider& styleProvider)
{
auto elementStore = storeMap_[storeKey];
elementStore->store(element, range, styleProvider);
elementStore->commit();
}
void add(const std::string& storeKey, const std::string& path, const QuadKey& quadKey, const StyleProvider& styleProvider)
{
auto elementStore = storeMap_[storeKey];
add(path, styleProvider, [&](Element& element) {
return elementStore->store(element, quadKey, styleProvider);
});
elementStore->commit();
}
void add(const std::string& storeKey, const std::string& path, const LodRange& range, const StyleProvider& styleProvider)
{
auto elementStore = storeMap_[storeKey];
add(path, styleProvider, [&](Element& element) {
return elementStore->store(element, range, styleProvider);
});
elementStore->commit();
}
void add(const std::string& storeKey, const std::string& path, const BoundingBox& bbox, const LodRange& range, const StyleProvider& styleProvider)
{
auto elementStore = storeMap_[storeKey];
add(path, styleProvider, [&](Element& element) {
return elementStore->store(element, bbox, range, styleProvider);
});
elementStore->commit();
}
void add(const std::string& path, const StyleProvider& styleProvider, const std::function<bool(Element&)>& functor)
{
switch (getFormatTypeFromPath(path)) {
case FormatType::Shape: {
ShapeParser<ShapeDataVisitor> parser;
ShapeDataVisitor visitor(stringTable_, functor);
parser.parse(path, visitor);
visitor.complete();
break;
}
case FormatType::Xml: {
OsmXmlParser<OsmDataVisitor> parser;
std::ifstream xmlFile(path);
OsmDataVisitor visitor(stringTable_, functor);
parser.parse(xmlFile, visitor);
visitor.complete();
break;
}
case FormatType::Pbf: {
OsmPbfParser<OsmDataVisitor> parser;
std::ifstream pbfFile(path, std::ios::in | std::ios::binary);
OsmDataVisitor visitor(stringTable_, functor);
parser.parse(pbfFile, visitor);
visitor.complete();
break;
}
default:
throw std::domain_error("Not implemented.");
}
}
void search(const QuadKey& quadKey, const utymap::mapcss::StyleProvider& styleProvider, ElementVisitor& visitor)
{
FilterElementVisitor filter(quadKey, styleProvider, visitor);
for (const auto& pair : storeMap_) {
pair.second->search(quadKey, filter);
}
}
void search(const GeoCoordinate& coordinate, double radius, const StyleProvider& styleProvider, ElementVisitor& visitor)
{
throw std::domain_error("Not implemented");
}
bool hasData(const QuadKey& quadKey)
{
for (const auto& pair : storeMap_) {
if (pair.second->hasData(quadKey))
return true;
}
return false;
}
private:
StringTable& stringTable_;
std::map<std::string, std::shared_ptr<ElementStore>> storeMap_;
FormatType getFormatTypeFromPath(const std::string& path)
{
if (utymap::utils::endsWith(path, "pbf"))
return FormatType::Pbf;
if (utymap::utils::endsWith(path, "xml"))
return FormatType::Xml;
return FormatType::Shape;
}
};
GeoStore::GeoStore(StringTable& stringTable) : pimpl_(new GeoStore::GeoStoreImpl(stringTable))
{
}
GeoStore::~GeoStore()
{
// according to docs, should be called only once on app end.
google::protobuf::ShutdownProtobufLibrary();
}
void utymap::index::GeoStore::registerStore(const std::string& storeKey, const std::shared_ptr<ElementStore>& store)
{
pimpl_->registerStore(storeKey, store);
}
void utymap::index::GeoStore::add(const std::string& storeKey, const Element& element, const LodRange& range, const StyleProvider& styleProvider)
{
pimpl_->add(storeKey, element, range, styleProvider);
}
void utymap::index::GeoStore::add(const std::string& storeKey, const std::string& path, const LodRange& range, const StyleProvider& styleProvider)
{
pimpl_->add(storeKey, path, range, styleProvider);
}
void utymap::index::GeoStore::add(const std::string& storeKey, const std::string& path, const QuadKey& quadKey, const StyleProvider& styleProvider)
{
pimpl_->add(storeKey, path, quadKey, styleProvider);
}
void utymap::index::GeoStore::add(const std::string &storeKey, const std::string &path, const utymap::BoundingBox& bbox, const LodRange& range, const utymap::mapcss::StyleProvider& styleProvider)
{
pimpl_->add(storeKey, path, bbox, range, styleProvider);
}
void utymap::index::GeoStore::search(const QuadKey& quadKey, const utymap::mapcss::StyleProvider& styleProvider, ElementVisitor& visitor)
{
pimpl_->search(quadKey, styleProvider, visitor);
}
void utymap::index::GeoStore::search(const GeoCoordinate& coordinate, double radius, const StyleProvider& styleProvider, ElementVisitor& visitor)
{
pimpl_->search(coordinate, radius, styleProvider, visitor);
}
bool utymap::index::GeoStore::hasData(const QuadKey& quadKey)
{
return pimpl_->hasData(quadKey);
}
<commit_msg>core: fix side effect for searching in empty persistent store<commit_after>#include "entities/Element.hpp"
#include "LodRange.hpp"
#include "formats/shape/ShapeDataVisitor.hpp"
#include "formats/shape/ShapeParser.hpp"
#include "formats/osm/xml/OsmXmlParser.hpp"
#include "formats/osm/pbf/OsmPbfParser.hpp"
#include "formats/osm/OsmDataVisitor.hpp"
#include "index/GeoStore.hpp"
#include "index/InMemoryElementStore.hpp"
#include "index/PersistentElementStore.hpp"
#include "utils/CoreUtils.hpp"
#include <set>
#include <map>
#include <memory>
using namespace utymap::entities;
using namespace utymap::formats;
using namespace utymap::index;
using namespace utymap::mapcss;
class GeoStore::GeoStoreImpl
{
// Prevents to visit element twice if it exists in multiply stores.
class FilterElementVisitor : public ElementVisitor
{
public:
FilterElementVisitor(const QuadKey& quadKey, const StyleProvider& styleProvider, ElementVisitor& visitor)
: visitor_(visitor), quadKey_(quadKey), styleProvider_(styleProvider), ids_()
{
}
void visitNode(const Node& node) { visitIfNecessary(node); }
void visitWay(const Way& way) { visitIfNecessary(way); }
void visitArea(const Area& area) { visitIfNecessary(area); }
void visitRelation(const Relation& relation) { visitIfNecessary(relation); }
private:
inline void visitIfNecessary(const Element& element)
{
if (element.id == 0 || ids_.find(element.id) == ids_.end() ||
styleProvider_.hasStyle(element, quadKey_.levelOfDetail)) {
element.accept(visitor_);
ids_.insert(element.id);
}
}
const QuadKey& quadKey_;
const StyleProvider& styleProvider_;
ElementVisitor& visitor_;
std::set<std::uint64_t> ids_;
};
public:
GeoStoreImpl(StringTable& stringTable) :
stringTable_(stringTable)
{
}
void registerStore(const std::string& storeKey, const std::shared_ptr<ElementStore>& store)
{
storeMap_[storeKey] = store;
}
void add(const std::string& storeKey, const Element& element, const LodRange& range, const StyleProvider& styleProvider)
{
auto elementStore = storeMap_[storeKey];
elementStore->store(element, range, styleProvider);
elementStore->commit();
}
void add(const std::string& storeKey, const std::string& path, const QuadKey& quadKey, const StyleProvider& styleProvider)
{
auto elementStore = storeMap_[storeKey];
add(path, styleProvider, [&](Element& element) {
return elementStore->store(element, quadKey, styleProvider);
});
elementStore->commit();
}
void add(const std::string& storeKey, const std::string& path, const LodRange& range, const StyleProvider& styleProvider)
{
auto elementStore = storeMap_[storeKey];
add(path, styleProvider, [&](Element& element) {
return elementStore->store(element, range, styleProvider);
});
elementStore->commit();
}
void add(const std::string& storeKey, const std::string& path, const BoundingBox& bbox, const LodRange& range, const StyleProvider& styleProvider)
{
auto elementStore = storeMap_[storeKey];
add(path, styleProvider, [&](Element& element) {
return elementStore->store(element, bbox, range, styleProvider);
});
elementStore->commit();
}
void add(const std::string& path, const StyleProvider& styleProvider, const std::function<bool(Element&)>& functor)
{
switch (getFormatTypeFromPath(path)) {
case FormatType::Shape: {
ShapeParser<ShapeDataVisitor> parser;
ShapeDataVisitor visitor(stringTable_, functor);
parser.parse(path, visitor);
visitor.complete();
break;
}
case FormatType::Xml: {
OsmXmlParser<OsmDataVisitor> parser;
std::ifstream xmlFile(path);
OsmDataVisitor visitor(stringTable_, functor);
parser.parse(xmlFile, visitor);
visitor.complete();
break;
}
case FormatType::Pbf: {
OsmPbfParser<OsmDataVisitor> parser;
std::ifstream pbfFile(path, std::ios::in | std::ios::binary);
OsmDataVisitor visitor(stringTable_, functor);
parser.parse(pbfFile, visitor);
visitor.complete();
break;
}
default:
throw std::domain_error("Not implemented.");
}
}
void search(const QuadKey& quadKey, const utymap::mapcss::StyleProvider& styleProvider, ElementVisitor& visitor)
{
FilterElementVisitor filter(quadKey, styleProvider, visitor);
for (const auto& pair : storeMap_) {
// Search only if store has data
if (pair.second->hasData(quadKey))
pair.second->search(quadKey, filter);
}
}
void search(const GeoCoordinate& coordinate, double radius, const StyleProvider& styleProvider, ElementVisitor& visitor)
{
throw std::domain_error("Not implemented");
}
bool hasData(const QuadKey& quadKey)
{
for (const auto& pair : storeMap_) {
if (pair.second->hasData(quadKey))
return true;
}
return false;
}
private:
StringTable& stringTable_;
std::map<std::string, std::shared_ptr<ElementStore>> storeMap_;
FormatType getFormatTypeFromPath(const std::string& path)
{
if (utymap::utils::endsWith(path, "pbf"))
return FormatType::Pbf;
if (utymap::utils::endsWith(path, "xml"))
return FormatType::Xml;
return FormatType::Shape;
}
};
GeoStore::GeoStore(StringTable& stringTable) : pimpl_(new GeoStore::GeoStoreImpl(stringTable))
{
}
GeoStore::~GeoStore()
{
// according to docs, should be called only once on app end.
google::protobuf::ShutdownProtobufLibrary();
}
void utymap::index::GeoStore::registerStore(const std::string& storeKey, const std::shared_ptr<ElementStore>& store)
{
pimpl_->registerStore(storeKey, store);
}
void utymap::index::GeoStore::add(const std::string& storeKey, const Element& element, const LodRange& range, const StyleProvider& styleProvider)
{
pimpl_->add(storeKey, element, range, styleProvider);
}
void utymap::index::GeoStore::add(const std::string& storeKey, const std::string& path, const LodRange& range, const StyleProvider& styleProvider)
{
pimpl_->add(storeKey, path, range, styleProvider);
}
void utymap::index::GeoStore::add(const std::string& storeKey, const std::string& path, const QuadKey& quadKey, const StyleProvider& styleProvider)
{
pimpl_->add(storeKey, path, quadKey, styleProvider);
}
void utymap::index::GeoStore::add(const std::string &storeKey, const std::string &path, const utymap::BoundingBox& bbox, const LodRange& range, const utymap::mapcss::StyleProvider& styleProvider)
{
pimpl_->add(storeKey, path, bbox, range, styleProvider);
}
void utymap::index::GeoStore::search(const QuadKey& quadKey, const utymap::mapcss::StyleProvider& styleProvider, ElementVisitor& visitor)
{
pimpl_->search(quadKey, styleProvider, visitor);
}
void utymap::index::GeoStore::search(const GeoCoordinate& coordinate, double radius, const StyleProvider& styleProvider, ElementVisitor& visitor)
{
pimpl_->search(coordinate, radius, styleProvider, visitor);
}
bool utymap::index::GeoStore::hasData(const QuadKey& quadKey)
{
return pimpl_->hasData(quadKey);
}
<|endoftext|> |
<commit_before>#include "drawRule.h"
#include "csscolorparser.hpp"
#include "geom.h" // for CLAMP
#include "platform.h"
#include <algorithm>
#include <map>
namespace Tangram {
const StyleParam NONE;
const std::map<std::string, StyleParamKey> s_StyleParamMap = {
{"none", StyleParamKey::none},
{"order", StyleParamKey::order},
{"color", StyleParamKey::color},
{"width", StyleParamKey::width},
{"cap", StyleParamKey::cap},
{"join", StyleParamKey::join},
{"outline:color", StyleParamKey::outline_color},
{"outline:width", StyleParamKey::outline_width},
{"outline:cap", StyleParamKey::outline_cap},
{"outline:join", StyleParamKey::outline_join},
};
StyleParam::StyleParam(const std::string& _key, const std::string& _value) {
auto it = s_StyleParamMap.find(_key);
if (it == s_StyleParamMap.end()) {
logMsg("Unknown StyleParam %s:%s\n", _key.c_str(), _value.c_str());
value = "";
return;
}
key = it->second;
switch (key) {
case StyleParamKey::order:
value = static_cast<int32_t>(std::stoi(_value));
break;
case StyleParamKey::width:
case StyleParamKey::outline_width:
value = static_cast<float>(std::stof(_value));
break;
case StyleParamKey::color:
case StyleParamKey::outline_color:
value = DrawRule::parseColor(_value);
break;
case StyleParamKey::cap:
case StyleParamKey::outline_cap:
value = CapTypeFromString(_value);
break;
case StyleParamKey::join:
case StyleParamKey::outline_join:
value = JoinTypeFromString(_value);
break;
default:
value = none_type{};
}
}
std::string StyleParam::toString() const {
// TODO: cap, join and color toString()
switch (key) {
case StyleParamKey::order:
return std::to_string(value.get<int32_t>());
case StyleParamKey::width:
case StyleParamKey::outline_width:
return std::to_string(value.get<float>());
case StyleParamKey::color:
case StyleParamKey::outline_color:
return std::to_string(value.get<Color>().getInt());
case StyleParamKey::cap:
case StyleParamKey::outline_cap:
return std::to_string(static_cast<int>(value.get<CapTypes>()));
case StyleParamKey::join:
case StyleParamKey::outline_join:
return std::to_string(static_cast<int>(value.get<CapTypes>()));
case StyleParamKey::none:
break;
}
return "undefined";
}
DrawRule::DrawRule(const std::string& _style, const std::vector<StyleParam>& _parameters) :
style(_style),
parameters(_parameters) {
// Parameters within each rule must be sorted lexicographically by key to merge correctly
std::sort(parameters.begin(), parameters.end());
}
DrawRule DrawRule::merge(DrawRule& _other) const {
decltype(parameters) merged;
auto myIt = parameters.begin(), myEnd = parameters.end();
auto otherIt = _other.parameters.begin(), otherEnd = _other.parameters.end();
while (myIt != myEnd && otherIt != otherEnd) {
if (*myIt < *otherIt) {
merged.push_back(*myIt++);
} else if (*otherIt < *myIt) {
merged.push_back(std::move(*otherIt++));
} else {
merged.push_back(*otherIt++);
myIt++;
}
}
while (myIt != myEnd) { merged.push_back(*myIt++); }
while (otherIt != otherEnd) { merged.push_back(std::move(*otherIt++)); }
return { style, merged };
}
std::string DrawRule::toString() const {
std::string str = "{\n";
for (auto& p : parameters) {
str += " { " + std::to_string(static_cast<int>(p.key)) + ", " + p.toString() + " }\n";
}
str += "}\n";
return str;
}
const StyleParam& DrawRule::findParameter(StyleParamKey _key) const {
auto it = std::lower_bound(parameters.begin(), parameters.end(), _key,
[](auto& p, auto& k) { return p.key < k; });
if (it != parameters.end() && it->key == _key) {
return *it;
}
return NONE;
}
bool DrawRule::getValue(StyleParamKey _key, std::string& _value) const {
auto& param = findParameter(_key);
if (!param) { return false; }
if (!param.value.is<std::string>()) {
logMsg("Error: not a string type\n");
return false;
}
_value = param.value.get<std::string>();
return true;
};
bool DrawRule::getValue(StyleParamKey _key, float& _value) const {
auto& param = findParameter(_key);
if (!param) { return false; }
if (!param.value.is<float>()) {
logMsg("Error: not a float type\n");
return false;
}
_value = param.value.get<float>();
return true;
}
bool DrawRule::getValue(StyleParamKey _key, int32_t& _value) const {
auto& param = findParameter(_key);
if (!param) { return false; }
if (!param.value.is<int32_t>()) {
logMsg("Error: not a int32_t\n");
return false;
}
_value = param.value.get<int32_t>();
return true;
}
bool DrawRule::getColor(StyleParamKey _key, uint32_t& _value) const {
auto& param = findParameter(_key);
if (!param) { return false; }
if (!param.value.is<Color>()) {
logMsg("Error: not a Color\n");
return false;
}
_value = param.value.get<Color>().getInt();
return true;
}
bool DrawRule::getLineCap(StyleParamKey _key, CapTypes& _value) const {
auto& param = findParameter(_key);
if (!param) { return false; }
if (!param.value.is<CapTypes>()) {
logMsg("Error: not a CapType\n");
return false;
}
_value = param.value.get<CapTypes>();
return true;
}
bool DrawRule::getLineJoin(StyleParamKey _key, JoinTypes& _value) const {
auto& param = findParameter(_key);
if (!param) { return false; }
if (!param.value.is<JoinTypes>()) {
logMsg("Error: not a JoinType\n");
return false;
}
_value = param.value.get<JoinTypes>();
return true;
}
bool DrawRule::operator<(const DrawRule& _rhs) const {
return style < _rhs.style;
}
Color DrawRule::parseColor(const std::string& _color) {
Color color;
if (isdigit(_color.front())) {
// try to parse as comma-separated rgba components
float r, g, b, a = 1.;
if (sscanf(_color.c_str(), "%f,%f,%f,%f", &r, &g, &b, &a) >= 3) {
color = Color {
static_cast<uint8_t>(CLAMP((r * 255.), 0, 255)),
static_cast<uint8_t>(CLAMP((g * 255.), 0, 255)),
static_cast<uint8_t>(CLAMP((b * 255.), 0, 255)),
CLAMP(a, 0, 1)
};
}
} else {
// parse as css color or #hex-num
color = CSSColorParser::parse(_color);
}
return color;
}
}
<commit_msg>fix: unitialized key<commit_after>#include "drawRule.h"
#include "csscolorparser.hpp"
#include "geom.h" // for CLAMP
#include "platform.h"
#include <algorithm>
#include <map>
namespace Tangram {
const StyleParam NONE;
const std::map<std::string, StyleParamKey> s_StyleParamMap = {
{"none", StyleParamKey::none},
{"order", StyleParamKey::order},
{"color", StyleParamKey::color},
{"width", StyleParamKey::width},
{"cap", StyleParamKey::cap},
{"join", StyleParamKey::join},
{"outline:color", StyleParamKey::outline_color},
{"outline:width", StyleParamKey::outline_width},
{"outline:cap", StyleParamKey::outline_cap},
{"outline:join", StyleParamKey::outline_join},
};
StyleParam::StyleParam(const std::string& _key, const std::string& _value) {
auto it = s_StyleParamMap.find(_key);
if (it == s_StyleParamMap.end()) {
logMsg("Unknown StyleParam %s:%s\n", _key.c_str(), _value.c_str());
key = StyleParamKey::none;
value = none_type{};
return;
}
key = it->second;
switch (key) {
case StyleParamKey::order:
value = static_cast<int32_t>(std::stoi(_value));
break;
case StyleParamKey::width:
case StyleParamKey::outline_width:
value = static_cast<float>(std::stof(_value));
break;
case StyleParamKey::color:
case StyleParamKey::outline_color:
value = DrawRule::parseColor(_value);
break;
case StyleParamKey::cap:
case StyleParamKey::outline_cap:
value = CapTypeFromString(_value);
break;
case StyleParamKey::join:
case StyleParamKey::outline_join:
value = JoinTypeFromString(_value);
break;
default:
value = none_type{};
}
}
std::string StyleParam::toString() const {
// TODO: cap, join and color toString()
switch (key) {
case StyleParamKey::order:
return std::to_string(value.get<int32_t>());
case StyleParamKey::width:
case StyleParamKey::outline_width:
return std::to_string(value.get<float>());
case StyleParamKey::color:
case StyleParamKey::outline_color:
return std::to_string(value.get<Color>().getInt());
case StyleParamKey::cap:
case StyleParamKey::outline_cap:
return std::to_string(static_cast<int>(value.get<CapTypes>()));
case StyleParamKey::join:
case StyleParamKey::outline_join:
return std::to_string(static_cast<int>(value.get<CapTypes>()));
case StyleParamKey::none:
break;
}
return "undefined";
}
DrawRule::DrawRule(const std::string& _style, const std::vector<StyleParam>& _parameters) :
style(_style),
parameters(_parameters) {
// Parameters within each rule must be sorted lexicographically by key to merge correctly
std::sort(parameters.begin(), parameters.end());
}
DrawRule DrawRule::merge(DrawRule& _other) const {
decltype(parameters) merged;
auto myIt = parameters.begin(), myEnd = parameters.end();
auto otherIt = _other.parameters.begin(), otherEnd = _other.parameters.end();
while (myIt != myEnd && otherIt != otherEnd) {
if (*myIt < *otherIt) {
merged.push_back(*myIt++);
} else if (*otherIt < *myIt) {
merged.push_back(std::move(*otherIt++));
} else {
merged.push_back(*otherIt++);
myIt++;
}
}
while (myIt != myEnd) { merged.push_back(*myIt++); }
while (otherIt != otherEnd) { merged.push_back(std::move(*otherIt++)); }
return { style, merged };
}
std::string DrawRule::toString() const {
std::string str = "{\n";
for (auto& p : parameters) {
str += " { " + std::to_string(static_cast<int>(p.key)) + ", " + p.toString() + " }\n";
}
str += "}\n";
return str;
}
const StyleParam& DrawRule::findParameter(StyleParamKey _key) const {
auto it = std::lower_bound(parameters.begin(), parameters.end(), _key,
[](auto& p, auto& k) { return p.key < k; });
if (it != parameters.end() && it->key == _key) {
return *it;
}
return NONE;
}
bool DrawRule::getValue(StyleParamKey _key, std::string& _value) const {
auto& param = findParameter(_key);
if (!param) { return false; }
if (!param.value.is<std::string>()) {
logMsg("Error: not a string type\n");
return false;
}
_value = param.value.get<std::string>();
return true;
};
bool DrawRule::getValue(StyleParamKey _key, float& _value) const {
auto& param = findParameter(_key);
if (!param) { return false; }
if (!param.value.is<float>()) {
logMsg("Error: not a float type\n");
return false;
}
_value = param.value.get<float>();
return true;
}
bool DrawRule::getValue(StyleParamKey _key, int32_t& _value) const {
auto& param = findParameter(_key);
if (!param) { return false; }
if (!param.value.is<int32_t>()) {
logMsg("Error: not a int32_t\n");
return false;
}
_value = param.value.get<int32_t>();
return true;
}
bool DrawRule::getColor(StyleParamKey _key, uint32_t& _value) const {
auto& param = findParameter(_key);
if (!param) { return false; }
if (!param.value.is<Color>()) {
logMsg("Error: not a Color\n");
return false;
}
_value = param.value.get<Color>().getInt();
return true;
}
bool DrawRule::getLineCap(StyleParamKey _key, CapTypes& _value) const {
auto& param = findParameter(_key);
if (!param) { return false; }
if (!param.value.is<CapTypes>()) {
logMsg("Error: not a CapType\n");
return false;
}
_value = param.value.get<CapTypes>();
return true;
}
bool DrawRule::getLineJoin(StyleParamKey _key, JoinTypes& _value) const {
auto& param = findParameter(_key);
if (!param) { return false; }
if (!param.value.is<JoinTypes>()) {
logMsg("Error: not a JoinType\n");
return false;
}
_value = param.value.get<JoinTypes>();
return true;
}
bool DrawRule::operator<(const DrawRule& _rhs) const {
return style < _rhs.style;
}
Color DrawRule::parseColor(const std::string& _color) {
Color color;
if (isdigit(_color.front())) {
// try to parse as comma-separated rgba components
float r, g, b, a = 1.;
if (sscanf(_color.c_str(), "%f,%f,%f,%f", &r, &g, &b, &a) >= 3) {
color = Color {
static_cast<uint8_t>(CLAMP((r * 255.), 0, 255)),
static_cast<uint8_t>(CLAMP((g * 255.), 0, 255)),
static_cast<uint8_t>(CLAMP((b * 255.), 0, 255)),
CLAMP(a, 0, 1)
};
}
} else {
// parse as css color or #hex-num
color = CSSColorParser::parse(_color);
}
return color;
}
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* 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 "RequestManagerChown.h"
#include "PoolObjectSQL.h"
#include "NebulaLog.h"
#include "Nebula.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
PoolObjectSQL * RequestManagerChown::get_and_quota(
int oid,
int new_uid,
int new_gid,
RequestAttributes& att)
{
Template * tmpl;
int old_uid;
int old_gid;
PoolObjectSQL * object;
Quotas::QuotaType qtype;
string error_str;
object = pool->get(oid,true);
if ( object == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(auth_object), oid),
att);
return 0;
}
if ( auth_object == PoolObjectSQL::VM )
{
tmpl = (static_cast<VirtualMachine*>(object))->clone_template();
qtype = Quotas::VIRTUALMACHINE;
}
else
{
Image * img = static_cast<Image *>(object);
tmpl = new Template;
tmpl->add("DATASTORE", img->get_ds_id());
tmpl->add("SIZE", img->get_size());
qtype = Quotas::DATASTORE;
}
if ( new_uid == -1 )
{
old_uid = -1;
}
else
{
old_uid = object->get_uid();
}
if ( new_gid == -1 )
{
old_gid = -1;
}
else
{
old_gid = object->get_gid();
}
object->unlock();
RequestAttributes att_new(new_uid, new_gid, att);
RequestAttributes att_old(old_uid, old_gid, att);
if ( quota_authorization(tmpl, qtype, att_new, error_str) == false )
{
failure_response(AUTHORIZATION,
request_error(error_str, ""),
att);
delete tmpl;
return 0;
}
quota_rollback(tmpl, qtype, att_old);
object = pool->get(oid,true);
if ( object == 0 )
{
quota_rollback(tmpl, qtype, att_new);
quota_authorization(tmpl, qtype, att_old, error_str);
failure_response(NO_EXISTS,
get_error(object_name(auth_object), oid),
att);
}
delete tmpl;
return object;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int RequestManagerChown::check_name_unique(int oid, int noid, RequestAttributes& att)
{
PoolObjectSQL * object;
string name;
int obj_oid;
ostringstream oss;
object = pool->get(oid, true);
if ( object == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(auth_object), oid),
att);
return -1;
}
name = object->get_name();
object->unlock();
object = get(name, noid, true);
if ( object != 0 )
{
obj_oid = object->get_oid();
object->unlock();
oss << PoolObjectSQL::type_to_str(PoolObjectSQL::USER)
<< " [" << noid << "] already owns "
<< PoolObjectSQL::type_to_str(auth_object) << " ["
<< obj_oid << "] with NAME " << name;
failure_response(INTERNAL, request_error(oss.str(), ""), att);
return -1;
}
return 0;
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void RequestManagerChown::request_execute(xmlrpc_c::paramList const& paramList,
RequestAttributes& att)
{
int oid = xmlrpc_c::value_int(paramList.getInt(1));
int noid = xmlrpc_c::value_int(paramList.getInt(2));
int ngid = xmlrpc_c::value_int(paramList.getInt(3));
int rc;
string oname;
string nuname;
string ngname;
PoolObjectAuth operms;
PoolObjectAuth nuperms;
PoolObjectAuth ngperms;
PoolObjectSQL * object;
string obj_name;
int old_uid;
// ------------- Check new user and group id's ---------------------
if ( noid > -1 )
{
rc = get_info(upool, noid, PoolObjectSQL::USER, att, nuperms, nuname);
if ( rc == -1 )
{
return;
}
}
if ( ngid > -1 )
{
rc = get_info(gpool, ngid, PoolObjectSQL::GROUP, att, ngperms, ngname);
if ( rc == -1 )
{
return;
}
}
// ------------- Set authorization request for non-oneadmin's --------------
if ( att.uid != 0 )
{
AuthRequest ar(att.uid, att.group_ids);
rc = get_info(pool, oid, auth_object, att, operms, oname);
if ( rc == -1 )
{
return;
}
ar.add_auth(auth_op, operms); // MANAGE OBJECT
if ( noid > -1 )
{
ar.add_auth(AuthRequest::MANAGE, nuperms); // MANAGE USER
}
if ( ngid > -1 )
{
ar.add_auth(AuthRequest::USE, ngperms); // USE GROUP
}
if (UserPool::authorize(ar) == -1)
{
failure_response(AUTHORIZATION,
authorization_error(ar.message, att),
att);
return;
}
}
// --------------- Check name uniqueness -----------------------------------
if ( noid != -1 )
{
if ( check_name_unique(oid, noid, att) != 0 )
{
return;
}
}
// --------------- Update the object and check quotas ----------------------
if ( auth_object == PoolObjectSQL::VM ||
auth_object == PoolObjectSQL::IMAGE )
{
object = get_and_quota(oid, noid, ngid, att);
}
else
{
object = pool->get(oid,true);
if ( object == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(auth_object), oid),
att);
}
}
if ( object == 0 )
{
return;
}
if ( noid != -1 )
{
obj_name = object->get_name();
old_uid = object->get_uid();
object->set_user(noid,nuname);
}
if ( ngid != -1 )
{
object->set_group(ngid,ngname);
}
pool->update(object);
object->unlock();
if ( noid != -1 )
{
pool->update_cache_index(obj_name, old_uid, obj_name, noid);
}
success_response(oid, att);
return;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void UserChown::request_execute(xmlrpc_c::paramList const& paramList,
RequestAttributes& att)
{
int oid = xmlrpc_c::value_int(paramList.getInt(1));
int ngid = xmlrpc_c::value_int(paramList.getInt(2));
int old_gid;
int rc;
string ngname;
string uname;
User * user;
Group * group;
PoolObjectAuth uperms;
PoolObjectAuth ngperms;
if ( ngid < 0 )
{
failure_response(XML_RPC_API,request_error("Wrong group ID",""), att);
return;
}
rc = get_info(upool, oid, PoolObjectSQL::USER, att, uperms, uname);
if ( rc == -1 )
{
return;
}
rc = get_info(gpool, ngid, PoolObjectSQL::GROUP, att, ngperms, ngname);
if ( rc == -1 )
{
return;
}
if ( oid == UserPool::ONEADMIN_ID )
{
ostringstream oss;
oss << PoolObjectSQL::type_to_str(PoolObjectSQL::USER)
<< " [" << UserPool::ONEADMIN_ID << "] " << UserPool::oneadmin_name
<< " cannot be moved outside of the "
<< PoolObjectSQL::type_to_str(PoolObjectSQL::GROUP)
<< " [" << GroupPool::ONEADMIN_ID << "] "
<< GroupPool::ONEADMIN_NAME;
failure_response(INTERNAL, request_error(oss.str(), ""), att);
return;
}
if ( att.uid != 0 )
{
AuthRequest ar(att.uid, att.group_ids);
ar.add_auth(auth_op, uperms); // MANAGE USER
ar.add_auth(AuthRequest::USE, ngperms); // USE GROUP
if (UserPool::authorize(ar) == -1)
{
failure_response(AUTHORIZATION,
authorization_error(ar.message, att),
att);
return;
}
}
// ------------- Change users primary group ---------------------
user = upool->get(oid,true);
if ( user == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(PoolObjectSQL::USER),oid),
att);
return;
}
if ((old_gid = user->get_gid()) == ngid)
{
user->unlock();
success_response(oid, att);
return;
}
user->set_group(ngid,ngname);
user->add_group(ngid);
user->del_group(old_gid);
upool->update(user);
user->unlock();
// ------------- Updates new group with this new user ---------------------
group = gpool->get(ngid, true);
if( group == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(PoolObjectSQL::GROUP),ngid),
att);//TODO Rollback
return;
}
group->add_user(oid);
gpool->update(group);
group->unlock();
// ------------- Updates old group removing the user ---------------------
group = gpool->get(old_gid, true);
if( group != 0 )
{
group->del_user(oid);
gpool->update(group);
group->unlock();
}
success_response(oid, att);
return;
}
<commit_msg>Feature #1742: chgrp does not delete the user from the previous group<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* 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 "RequestManagerChown.h"
#include "PoolObjectSQL.h"
#include "NebulaLog.h"
#include "Nebula.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
PoolObjectSQL * RequestManagerChown::get_and_quota(
int oid,
int new_uid,
int new_gid,
RequestAttributes& att)
{
Template * tmpl;
int old_uid;
int old_gid;
PoolObjectSQL * object;
Quotas::QuotaType qtype;
string error_str;
object = pool->get(oid,true);
if ( object == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(auth_object), oid),
att);
return 0;
}
if ( auth_object == PoolObjectSQL::VM )
{
tmpl = (static_cast<VirtualMachine*>(object))->clone_template();
qtype = Quotas::VIRTUALMACHINE;
}
else
{
Image * img = static_cast<Image *>(object);
tmpl = new Template;
tmpl->add("DATASTORE", img->get_ds_id());
tmpl->add("SIZE", img->get_size());
qtype = Quotas::DATASTORE;
}
if ( new_uid == -1 )
{
old_uid = -1;
}
else
{
old_uid = object->get_uid();
}
if ( new_gid == -1 )
{
old_gid = -1;
}
else
{
old_gid = object->get_gid();
}
object->unlock();
RequestAttributes att_new(new_uid, new_gid, att);
RequestAttributes att_old(old_uid, old_gid, att);
if ( quota_authorization(tmpl, qtype, att_new, error_str) == false )
{
failure_response(AUTHORIZATION,
request_error(error_str, ""),
att);
delete tmpl;
return 0;
}
quota_rollback(tmpl, qtype, att_old);
object = pool->get(oid,true);
if ( object == 0 )
{
quota_rollback(tmpl, qtype, att_new);
quota_authorization(tmpl, qtype, att_old, error_str);
failure_response(NO_EXISTS,
get_error(object_name(auth_object), oid),
att);
}
delete tmpl;
return object;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int RequestManagerChown::check_name_unique(int oid, int noid, RequestAttributes& att)
{
PoolObjectSQL * object;
string name;
int obj_oid;
ostringstream oss;
object = pool->get(oid, true);
if ( object == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(auth_object), oid),
att);
return -1;
}
name = object->get_name();
object->unlock();
object = get(name, noid, true);
if ( object != 0 )
{
obj_oid = object->get_oid();
object->unlock();
oss << PoolObjectSQL::type_to_str(PoolObjectSQL::USER)
<< " [" << noid << "] already owns "
<< PoolObjectSQL::type_to_str(auth_object) << " ["
<< obj_oid << "] with NAME " << name;
failure_response(INTERNAL, request_error(oss.str(), ""), att);
return -1;
}
return 0;
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void RequestManagerChown::request_execute(xmlrpc_c::paramList const& paramList,
RequestAttributes& att)
{
int oid = xmlrpc_c::value_int(paramList.getInt(1));
int noid = xmlrpc_c::value_int(paramList.getInt(2));
int ngid = xmlrpc_c::value_int(paramList.getInt(3));
int rc;
string oname;
string nuname;
string ngname;
PoolObjectAuth operms;
PoolObjectAuth nuperms;
PoolObjectAuth ngperms;
PoolObjectSQL * object;
string obj_name;
int old_uid;
// ------------- Check new user and group id's ---------------------
if ( noid > -1 )
{
rc = get_info(upool, noid, PoolObjectSQL::USER, att, nuperms, nuname);
if ( rc == -1 )
{
return;
}
}
if ( ngid > -1 )
{
rc = get_info(gpool, ngid, PoolObjectSQL::GROUP, att, ngperms, ngname);
if ( rc == -1 )
{
return;
}
}
// ------------- Set authorization request for non-oneadmin's --------------
if ( att.uid != 0 )
{
AuthRequest ar(att.uid, att.group_ids);
rc = get_info(pool, oid, auth_object, att, operms, oname);
if ( rc == -1 )
{
return;
}
ar.add_auth(auth_op, operms); // MANAGE OBJECT
if ( noid > -1 )
{
ar.add_auth(AuthRequest::MANAGE, nuperms); // MANAGE USER
}
if ( ngid > -1 )
{
ar.add_auth(AuthRequest::USE, ngperms); // USE GROUP
}
if (UserPool::authorize(ar) == -1)
{
failure_response(AUTHORIZATION,
authorization_error(ar.message, att),
att);
return;
}
}
// --------------- Check name uniqueness -----------------------------------
if ( noid != -1 )
{
if ( check_name_unique(oid, noid, att) != 0 )
{
return;
}
}
// --------------- Update the object and check quotas ----------------------
if ( auth_object == PoolObjectSQL::VM ||
auth_object == PoolObjectSQL::IMAGE )
{
object = get_and_quota(oid, noid, ngid, att);
}
else
{
object = pool->get(oid,true);
if ( object == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(auth_object), oid),
att);
}
}
if ( object == 0 )
{
return;
}
if ( noid != -1 )
{
obj_name = object->get_name();
old_uid = object->get_uid();
object->set_user(noid,nuname);
}
if ( ngid != -1 )
{
object->set_group(ngid,ngname);
}
pool->update(object);
object->unlock();
if ( noid != -1 )
{
pool->update_cache_index(obj_name, old_uid, obj_name, noid);
}
success_response(oid, att);
return;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void UserChown::request_execute(xmlrpc_c::paramList const& paramList,
RequestAttributes& att)
{
int oid = xmlrpc_c::value_int(paramList.getInt(1));
int ngid = xmlrpc_c::value_int(paramList.getInt(2));
int old_gid;
int rc;
bool remove_old_group;
string ngname;
string uname;
User * user;
Group * group;
PoolObjectAuth uperms;
PoolObjectAuth ngperms;
if ( ngid < 0 )
{
failure_response(XML_RPC_API,request_error("Wrong group ID",""), att);
return;
}
rc = get_info(upool, oid, PoolObjectSQL::USER, att, uperms, uname);
if ( rc == -1 )
{
return;
}
rc = get_info(gpool, ngid, PoolObjectSQL::GROUP, att, ngperms, ngname);
if ( rc == -1 )
{
return;
}
if ( oid == UserPool::ONEADMIN_ID )
{
ostringstream oss;
oss << PoolObjectSQL::type_to_str(PoolObjectSQL::USER)
<< " [" << UserPool::ONEADMIN_ID << "] " << UserPool::oneadmin_name
<< " cannot be moved outside of the "
<< PoolObjectSQL::type_to_str(PoolObjectSQL::GROUP)
<< " [" << GroupPool::ONEADMIN_ID << "] "
<< GroupPool::ONEADMIN_NAME;
failure_response(INTERNAL, request_error(oss.str(), ""), att);
return;
}
if ( att.uid != 0 )
{
AuthRequest ar(att.uid, att.group_ids);
ar.add_auth(auth_op, uperms); // MANAGE USER
ar.add_auth(AuthRequest::USE, ngperms); // USE GROUP
if (UserPool::authorize(ar) == -1)
{
failure_response(AUTHORIZATION,
authorization_error(ar.message, att),
att);
return;
}
}
// ------------- Change users primary group ---------------------
user = upool->get(oid,true);
if ( user == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(PoolObjectSQL::USER),oid),
att);
return;
}
if ((old_gid = user->get_gid()) == ngid)
{
user->unlock();
success_response(oid, att);
return;
}
user->set_group(ngid,ngname);
// The user is removed from the old group only if the new group is not a
// secondary one
rc = user->add_group(ngid);
remove_old_group = (rc == 0);
if (remove_old_group)
{
user->del_group(old_gid);
}
upool->update(user);
user->unlock();
// ------------- Updates new group with this new user ---------------------
group = gpool->get(ngid, true);
if( group == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(PoolObjectSQL::GROUP),ngid),
att);//TODO Rollback
return;
}
group->add_user(oid);
gpool->update(group);
group->unlock();
// ------------- Updates old group removing the user ---------------------
if (remove_old_group)
{
group = gpool->get(old_gid, true);
if( group != 0 )
{
group->del_user(oid);
gpool->update(group);
group->unlock();
}
}
success_response(oid, att);
return;
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 "itkPolygonSpatialObject.h"
#include "itkGroupSpatialObject.h"
#include "itkSpatialObjectToImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkTestingMacros.h"
#include <iostream>
#include <fstream>
#include <sstream>
// -------------------------------------------------------------------------------------
// The purpose of this test is to make sure that the function
// ObjectIsInsideInObjectSpace is working as expected.
// This is related to a regression that was fixed under case 1082
// which showed that certain contours that were created from the polygonSpatialObject
// had trailing tails that were not supposed to be there.
// In order to test this we take a known regression list of contour points
// and create a contour image from these points.
// We compare the resulting image with the known baseline contour image.
// ---------------------------------------------------------------------------------------
int
itkPolygonSpatialObjectIsInsideInObjectSpaceTest(int argc, char * argv[])
{
if (argc < 3)
{
std::cerr << "Missing Parameters" << std::endl;
std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv);
std::cerr << " polygonPointsCSVFile baselineImageFileName outImageFileName ";
std::cerr << std::endl;
return EXIT_FAILURE;
}
constexpr unsigned int Dimension = 2;
using PointType = itk::ImageBase<Dimension>::PointType;
using PolygonPointType = itk::PolygonSpatialObject<Dimension>::PolygonPointType;
using PolygonPointListType = itk::PolygonSpatialObject<Dimension>::PolygonPointListType;
using PixelType = uint16_t;
using Group = itk::GroupSpatialObject<Dimension>;
using ImageType = itk::Image<PixelType, Dimension>;
using SpatialObjectToImageFilterType = itk::SpatialObjectToImageFilter<Group, ImageType>;
const char * csvFileName = argv[1];
const char * baselineFileName = argv[2];
const char * outFileName = argv[3];
// Get polygon points from CSV file
PolygonPointListType polygonPointList;
std::ifstream fs;
char data[100];
fs.open(csvFileName);
if (fs.good())
{
// read over first line
fs.getline(data, sizeof(data), '\n');
char commaDelim;
while (fs.getline(data, sizeof(data), '\n'))
{
std::stringstream ss(data);
PolygonPointType polygonPt;
itk::SpatialObject<Dimension>::Pointer so = itk::SpatialObject<Dimension>::New();
polygonPt.SetSpatialObject(so);
PointType pt;
ss >> pt[0];
ss >> commaDelim;
ss >> pt[1];
polygonPt.SetPositionInWorldSpace(pt);
polygonPointList.push_back(polygonPt);
}
}
else
{
fs.close();
std::cerr << "Error reading CSV file" << csvFileName << std::endl;
return EXIT_FAILURE;
}
// Create polygon spatial group
auto groupPtr = Group::New();
auto polygonPtr = itk::PolygonSpatialObject<Dimension>::New();
groupPtr->AddChild(polygonPtr);
polygonPtr->SetPoints(polygonPointList);
polygonPtr->SetDefaultInsideValue(1.0);
polygonPtr->SetDefaultOutsideValue(0.0);
ITK_TRY_EXPECT_NO_EXCEPTION(polygonPtr->Update());
// Read baseline image
ImageType::Pointer baselineImagePtr = nullptr;
itk::ImageFileReader<ImageType>::Pointer reader = itk::ImageFileReader<ImageType>::New();
reader->SetFileName(baselineFileName);
ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update());
baselineImagePtr = reader->GetOutput();
// create image
auto toImageFilter = SpatialObjectToImageFilterType::New();
toImageFilter->SetInput(groupPtr);
toImageFilter->SetSize(baselineImagePtr->GetLargestPossibleRegion().GetSize());
toImageFilter->SetSpacing(baselineImagePtr->GetSpacing());
ITK_TRY_EXPECT_NO_EXCEPTION(toImageFilter->Update());
// write image
using FileWriterType = itk::ImageFileWriter<ImageType>;
auto fileWriter = FileWriterType::New();
fileWriter->SetInput(toImageFilter->GetOutput());
fileWriter->SetFileName(outFileName);
ITK_TRY_EXPECT_NO_EXCEPTION(fileWriter->Update());
return EXIT_SUCCESS;
}
<commit_msg>STYLE: use ReadImage and WriteImage in PolygonSpatialObjectIsInsideTest<commit_after>/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 "itkPolygonSpatialObject.h"
#include "itkGroupSpatialObject.h"
#include "itkSpatialObjectToImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkTestingMacros.h"
#include <iostream>
#include <fstream>
#include <sstream>
// -------------------------------------------------------------------------------------
// The purpose of this test is to make sure that the function
// ObjectIsInsideInObjectSpace is working as expected.
// This is related to a regression that was fixed under case 1082
// which showed that certain contours that were created from the polygonSpatialObject
// had trailing tails that were not supposed to be there.
// In order to test this we take a known regression list of contour points
// and create a contour image from these points.
// We compare the resulting image with the known baseline contour image.
// ---------------------------------------------------------------------------------------
int
itkPolygonSpatialObjectIsInsideInObjectSpaceTest(int argc, char * argv[])
{
if (argc < 3)
{
std::cerr << "Missing Parameters" << std::endl;
std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv);
std::cerr << " polygonPointsCSVFile baselineImageFileName outImageFileName ";
std::cerr << std::endl;
return EXIT_FAILURE;
}
constexpr unsigned int Dimension = 2;
using PointType = itk::ImageBase<Dimension>::PointType;
using PolygonPointType = itk::PolygonSpatialObject<Dimension>::PolygonPointType;
using PolygonPointListType = itk::PolygonSpatialObject<Dimension>::PolygonPointListType;
using PixelType = uint16_t;
using Group = itk::GroupSpatialObject<Dimension>;
using ImageType = itk::Image<PixelType, Dimension>;
using SpatialObjectToImageFilterType = itk::SpatialObjectToImageFilter<Group, ImageType>;
const char * csvFileName = argv[1];
const char * baselineFileName = argv[2];
const char * outFileName = argv[3];
// Get polygon points from CSV file
PolygonPointListType polygonPointList;
std::ifstream fs;
char data[100];
fs.open(csvFileName);
if (fs.good())
{
// read over first line
fs.getline(data, sizeof(data), '\n');
char commaDelim;
while (fs.getline(data, sizeof(data), '\n'))
{
std::stringstream ss(data);
PolygonPointType polygonPt;
itk::SpatialObject<Dimension>::Pointer so = itk::SpatialObject<Dimension>::New();
polygonPt.SetSpatialObject(so);
PointType pt;
ss >> pt[0];
ss >> commaDelim;
ss >> pt[1];
polygonPt.SetPositionInWorldSpace(pt);
polygonPointList.push_back(polygonPt);
}
}
else
{
fs.close();
std::cerr << "Error reading CSV file" << csvFileName << std::endl;
return EXIT_FAILURE;
}
// Create polygon spatial group
auto groupPtr = Group::New();
auto polygonPtr = itk::PolygonSpatialObject<Dimension>::New();
groupPtr->AddChild(polygonPtr);
polygonPtr->SetPoints(polygonPointList);
polygonPtr->SetDefaultInsideValue(1.0);
polygonPtr->SetDefaultOutsideValue(0.0);
ITK_TRY_EXPECT_NO_EXCEPTION(polygonPtr->Update());
// Read baseline image
ImageType::Pointer baselineImagePtr = nullptr;
ITK_TRY_EXPECT_NO_EXCEPTION(baselineImagePtr = itk::ReadImage<ImageType>(baselineFileName));
// create image
auto toImageFilter = SpatialObjectToImageFilterType::New();
toImageFilter->SetInput(groupPtr);
toImageFilter->SetSize(baselineImagePtr->GetLargestPossibleRegion().GetSize());
toImageFilter->SetSpacing(baselineImagePtr->GetSpacing());
ITK_TRY_EXPECT_NO_EXCEPTION(toImageFilter->Update());
// write image
ITK_TRY_EXPECT_NO_EXCEPTION(itk::WriteImage(toImageFilter->GetOutput(), outFileName));
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>//===--- LivePhysRegs.cpp - Live Physical Register Set --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the LivePhysRegs utility for tracking liveness of
// physical registers across machine instructions in forward or backward order.
// A more detailed description can be found in the corresponding header file.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/LivePhysRegs.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBundle.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
/// \brief Remove all registers from the set that get clobbered by the register
/// mask.
/// The clobbers set will be the list of live registers clobbered
/// by the regmask.
void LivePhysRegs::removeRegsInMask(const MachineOperand &MO,
SmallVectorImpl<std::pair<unsigned, const MachineOperand*>> *Clobbers) {
SparseSet<unsigned>::iterator LRI = LiveRegs.begin();
while (LRI != LiveRegs.end()) {
if (MO.clobbersPhysReg(*LRI)) {
if (Clobbers)
Clobbers->push_back(std::make_pair(*LRI, &MO));
LRI = LiveRegs.erase(LRI);
} else
++LRI;
}
}
/// Simulates liveness when stepping backwards over an instruction(bundle):
/// Remove Defs, add uses. This is the recommended way of calculating liveness.
void LivePhysRegs::stepBackward(const MachineInstr &MI) {
// Remove defined registers and regmask kills from the set.
for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
if (O->isReg()) {
if (!O->isDef())
continue;
unsigned Reg = O->getReg();
if (Reg == 0)
continue;
removeReg(Reg);
} else if (O->isRegMask())
removeRegsInMask(*O, nullptr);
}
// Add uses to the set.
for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
if (!O->isReg() || !O->readsReg() || O->isUndef())
continue;
unsigned Reg = O->getReg();
if (Reg == 0)
continue;
addReg(Reg);
}
}
/// Simulates liveness when stepping forward over an instruction(bundle): Remove
/// killed-uses, add defs. This is the not recommended way, because it depends
/// on accurate kill flags. If possible use stepBackward() instead of this
/// function.
void LivePhysRegs::stepForward(const MachineInstr &MI,
SmallVectorImpl<std::pair<unsigned, const MachineOperand*>> &Clobbers) {
// Remove killed registers from the set.
for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
if (O->isReg()) {
unsigned Reg = O->getReg();
if (Reg == 0)
continue;
if (O->isDef()) {
// Note, dead defs are still recorded. The caller should decide how to
// handle them.
Clobbers.push_back(std::make_pair(Reg, &*O));
} else {
if (!O->isKill())
continue;
assert(O->isUse());
removeReg(Reg);
}
} else if (O->isRegMask())
removeRegsInMask(*O, &Clobbers);
}
// Add defs to the set.
for (auto Reg : Clobbers) {
// Skip dead defs. They shouldn't be added to the set.
if (Reg.second->isReg() && Reg.second->isDead())
continue;
addReg(Reg.first);
}
}
/// Prin the currently live registers to OS.
void LivePhysRegs::print(raw_ostream &OS) const {
OS << "Live Registers:";
if (!TRI) {
OS << " (uninitialized)\n";
return;
}
if (empty()) {
OS << " (empty)\n";
return;
}
for (const_iterator I = begin(), E = end(); I != E; ++I)
OS << " " << PrintReg(*I, TRI);
OS << "\n";
}
/// Dumps the currently live registers to the debug output.
LLVM_DUMP_METHOD void LivePhysRegs::dump() const {
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dbgs() << " " << *this;
#endif
}
/// Add live-in registers of basic block \p MBB to \p LiveRegs.
static void addLiveIns(LivePhysRegs &LiveRegs, const MachineBasicBlock &MBB) {
for (const auto &LI : MBB.liveins())
LiveRegs.addReg(LI.PhysReg);
}
/// Add pristine registers to the given \p LiveRegs. This function removes
/// actually saved callee save registers when \p InPrologueEpilogue is false.
static void addPristines(LivePhysRegs &LiveRegs, const MachineFunction &MF,
const TargetRegisterInfo &TRI) {
const MachineFrameInfo &MFI = *MF.getFrameInfo();
if (!MFI.isCalleeSavedInfoValid())
return;
for (const MCPhysReg *CSR = TRI.getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
LiveRegs.addReg(*CSR);
for (const CalleeSavedInfo &Info : MFI.getCalleeSavedInfo())
LiveRegs.removeReg(Info.getReg());
}
void LivePhysRegs::addLiveOuts(const MachineBasicBlock *MBB,
bool AddPristinesAndCSRs) {
if (AddPristinesAndCSRs) {
const MachineFunction &MF = *MBB->getParent();
addPristines(*this, MF, *TRI);
if (MBB->isReturnBlock()) {
// The return block has no successors whose live-ins we could merge
// below. So instead we add the callee saved registers manually.
for (const MCPhysReg *I = TRI->getCalleeSavedRegs(&MF); *I; ++I)
addReg(*I);
}
}
// To get the live-outs we simply merge the live-ins of all successors.
for (const MachineBasicBlock *Succ : MBB->successors())
::addLiveIns(*this, *Succ);
}
void LivePhysRegs::addLiveIns(const MachineBasicBlock *MBB,
bool AddPristines) {
if (AddPristines) {
const MachineFunction &MF = *MBB->getParent();
addPristines(*this, MF, *TRI);
}
::addLiveIns(*this, *MBB);
}
<commit_msg>LivePhysRegs: Remove redundant check<commit_after>//===--- LivePhysRegs.cpp - Live Physical Register Set --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the LivePhysRegs utility for tracking liveness of
// physical registers across machine instructions in forward or backward order.
// A more detailed description can be found in the corresponding header file.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/LivePhysRegs.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBundle.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
/// \brief Remove all registers from the set that get clobbered by the register
/// mask.
/// The clobbers set will be the list of live registers clobbered
/// by the regmask.
void LivePhysRegs::removeRegsInMask(const MachineOperand &MO,
SmallVectorImpl<std::pair<unsigned, const MachineOperand*>> *Clobbers) {
SparseSet<unsigned>::iterator LRI = LiveRegs.begin();
while (LRI != LiveRegs.end()) {
if (MO.clobbersPhysReg(*LRI)) {
if (Clobbers)
Clobbers->push_back(std::make_pair(*LRI, &MO));
LRI = LiveRegs.erase(LRI);
} else
++LRI;
}
}
/// Simulates liveness when stepping backwards over an instruction(bundle):
/// Remove Defs, add uses. This is the recommended way of calculating liveness.
void LivePhysRegs::stepBackward(const MachineInstr &MI) {
// Remove defined registers and regmask kills from the set.
for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
if (O->isReg()) {
if (!O->isDef())
continue;
unsigned Reg = O->getReg();
if (Reg == 0)
continue;
removeReg(Reg);
} else if (O->isRegMask())
removeRegsInMask(*O, nullptr);
}
// Add uses to the set.
for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
if (!O->isReg() || !O->readsReg())
continue;
unsigned Reg = O->getReg();
if (Reg == 0)
continue;
addReg(Reg);
}
}
/// Simulates liveness when stepping forward over an instruction(bundle): Remove
/// killed-uses, add defs. This is the not recommended way, because it depends
/// on accurate kill flags. If possible use stepBackward() instead of this
/// function.
void LivePhysRegs::stepForward(const MachineInstr &MI,
SmallVectorImpl<std::pair<unsigned, const MachineOperand*>> &Clobbers) {
// Remove killed registers from the set.
for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
if (O->isReg()) {
unsigned Reg = O->getReg();
if (Reg == 0)
continue;
if (O->isDef()) {
// Note, dead defs are still recorded. The caller should decide how to
// handle them.
Clobbers.push_back(std::make_pair(Reg, &*O));
} else {
if (!O->isKill())
continue;
assert(O->isUse());
removeReg(Reg);
}
} else if (O->isRegMask())
removeRegsInMask(*O, &Clobbers);
}
// Add defs to the set.
for (auto Reg : Clobbers) {
// Skip dead defs. They shouldn't be added to the set.
if (Reg.second->isReg() && Reg.second->isDead())
continue;
addReg(Reg.first);
}
}
/// Prin the currently live registers to OS.
void LivePhysRegs::print(raw_ostream &OS) const {
OS << "Live Registers:";
if (!TRI) {
OS << " (uninitialized)\n";
return;
}
if (empty()) {
OS << " (empty)\n";
return;
}
for (const_iterator I = begin(), E = end(); I != E; ++I)
OS << " " << PrintReg(*I, TRI);
OS << "\n";
}
/// Dumps the currently live registers to the debug output.
LLVM_DUMP_METHOD void LivePhysRegs::dump() const {
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dbgs() << " " << *this;
#endif
}
/// Add live-in registers of basic block \p MBB to \p LiveRegs.
static void addLiveIns(LivePhysRegs &LiveRegs, const MachineBasicBlock &MBB) {
for (const auto &LI : MBB.liveins())
LiveRegs.addReg(LI.PhysReg);
}
/// Add pristine registers to the given \p LiveRegs. This function removes
/// actually saved callee save registers when \p InPrologueEpilogue is false.
static void addPristines(LivePhysRegs &LiveRegs, const MachineFunction &MF,
const TargetRegisterInfo &TRI) {
const MachineFrameInfo &MFI = *MF.getFrameInfo();
if (!MFI.isCalleeSavedInfoValid())
return;
for (const MCPhysReg *CSR = TRI.getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
LiveRegs.addReg(*CSR);
for (const CalleeSavedInfo &Info : MFI.getCalleeSavedInfo())
LiveRegs.removeReg(Info.getReg());
}
void LivePhysRegs::addLiveOuts(const MachineBasicBlock *MBB,
bool AddPristinesAndCSRs) {
if (AddPristinesAndCSRs) {
const MachineFunction &MF = *MBB->getParent();
addPristines(*this, MF, *TRI);
if (MBB->isReturnBlock()) {
// The return block has no successors whose live-ins we could merge
// below. So instead we add the callee saved registers manually.
for (const MCPhysReg *I = TRI->getCalleeSavedRegs(&MF); *I; ++I)
addReg(*I);
}
}
// To get the live-outs we simply merge the live-ins of all successors.
for (const MachineBasicBlock *Succ : MBB->successors())
::addLiveIns(*this, *Succ);
}
void LivePhysRegs::addLiveIns(const MachineBasicBlock *MBB,
bool AddPristines) {
if (AddPristines) {
const MachineFunction &MF = *MBB->getParent();
addPristines(*this, MF, *TRI);
}
::addLiveIns(*this, *MBB);
}
<|endoftext|> |
<commit_before>//===-- LowerSubregs.cpp - Subregister Lowering instruction pass ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a MachineFunction pass which runs after register
// allocation that turns subreg insert/extract instructions into register
// copies, as needed. This ensures correct codegen even if the coalescer
// isn't able to remove all subreg instructions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "lowersubregs"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Function.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
struct VISIBILITY_HIDDEN LowerSubregsInstructionPass
: public MachineFunctionPass {
static char ID; // Pass identification, replacement for typeid
LowerSubregsInstructionPass() : MachineFunctionPass(&ID) {}
const char *getPassName() const {
return "Subregister lowering instruction pass";
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addPreservedID(MachineLoopInfoID);
AU.addPreservedID(MachineDominatorsID);
MachineFunctionPass::getAnalysisUsage(AU);
}
/// runOnMachineFunction - pass entry point
bool runOnMachineFunction(MachineFunction&);
bool LowerExtract(MachineInstr *MI);
bool LowerInsert(MachineInstr *MI);
bool LowerSubregToReg(MachineInstr *MI);
void TransferDeadFlag(MachineInstr *MI, unsigned DstReg,
const TargetRegisterInfo &TRI);
void TransferKillFlag(MachineInstr *MI, unsigned SrcReg,
const TargetRegisterInfo &TRI,
bool AddIfNotFound = false);
};
char LowerSubregsInstructionPass::ID = 0;
}
FunctionPass *llvm::createLowerSubregsPass() {
return new LowerSubregsInstructionPass();
}
/// TransferDeadFlag - MI is a pseudo-instruction with DstReg dead,
/// and the lowered replacement instructions immediately precede it.
/// Mark the replacement instructions with the dead flag.
void
LowerSubregsInstructionPass::TransferDeadFlag(MachineInstr *MI,
unsigned DstReg,
const TargetRegisterInfo &TRI) {
for (MachineBasicBlock::iterator MII =
prior(MachineBasicBlock::iterator(MI)); ; --MII) {
if (MII->addRegisterDead(DstReg, &TRI))
break;
assert(MII != MI->getParent()->begin() &&
"copyRegToReg output doesn't reference destination register!");
}
}
/// TransferKillFlag - MI is a pseudo-instruction with SrcReg killed,
/// and the lowered replacement instructions immediately precede it.
/// Mark the replacement instructions with the kill flag.
void
LowerSubregsInstructionPass::TransferKillFlag(MachineInstr *MI,
unsigned SrcReg,
const TargetRegisterInfo &TRI,
bool AddIfNotFound) {
for (MachineBasicBlock::iterator MII =
prior(MachineBasicBlock::iterator(MI)); ; --MII) {
if (MII->addRegisterKilled(SrcReg, &TRI, AddIfNotFound))
break;
assert(MII != MI->getParent()->begin() &&
"copyRegToReg output doesn't reference source register!");
}
}
bool LowerSubregsInstructionPass::LowerExtract(MachineInstr *MI) {
MachineBasicBlock *MBB = MI->getParent();
MachineFunction &MF = *MBB->getParent();
const TargetRegisterInfo &TRI = *MF.getTarget().getRegisterInfo();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
assert(MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
MI->getOperand(1).isReg() && MI->getOperand(1).isUse() &&
MI->getOperand(2).isImm() && "Malformed extract_subreg");
unsigned DstReg = MI->getOperand(0).getReg();
unsigned SuperReg = MI->getOperand(1).getReg();
unsigned SubIdx = MI->getOperand(2).getImm();
unsigned SrcReg = TRI.getSubReg(SuperReg, SubIdx);
assert(TargetRegisterInfo::isPhysicalRegister(SuperReg) &&
"Extract supperg source must be a physical register");
assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
"Extract destination must be in a physical register");
assert(SrcReg && "invalid subregister index for register");
DEBUG(errs() << "subreg: CONVERTING: " << *MI);
if (SrcReg == DstReg) {
// No need to insert an identity copy instruction.
if (MI->getOperand(1).isKill()) {
// We must make sure the super-register gets killed. Replace the
// instruction with KILL.
MI->setDesc(TII.get(TargetInstrInfo::KILL));
MI->RemoveOperand(2); // SubIdx
DEBUG(errs() << "subreg: replace by: " << *MI);
return true;
}
DEBUG(errs() << "subreg: eliminated!");
} else {
// Insert copy
const TargetRegisterClass *TRCS = TRI.getPhysicalRegisterRegClass(DstReg);
const TargetRegisterClass *TRCD = TRI.getPhysicalRegisterRegClass(SrcReg);
bool Emitted = TII.copyRegToReg(*MBB, MI, DstReg, SrcReg, TRCD, TRCS);
(void)Emitted;
assert(Emitted && "Subreg and Dst must be of compatible register class");
// Transfer the kill/dead flags, if needed.
if (MI->getOperand(0).isDead())
TransferDeadFlag(MI, DstReg, TRI);
if (MI->getOperand(1).isKill())
TransferKillFlag(MI, SuperReg, TRI, true);
DEBUG({
MachineBasicBlock::iterator dMI = MI;
errs() << "subreg: " << *(--dMI);
});
}
DEBUG(errs() << '\n');
MBB->erase(MI);
return true;
}
bool LowerSubregsInstructionPass::LowerSubregToReg(MachineInstr *MI) {
MachineBasicBlock *MBB = MI->getParent();
MachineFunction &MF = *MBB->getParent();
const TargetRegisterInfo &TRI = *MF.getTarget().getRegisterInfo();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
assert((MI->getOperand(0).isReg() && MI->getOperand(0).isDef()) &&
MI->getOperand(1).isImm() &&
(MI->getOperand(2).isReg() && MI->getOperand(2).isUse()) &&
MI->getOperand(3).isImm() && "Invalid subreg_to_reg");
unsigned DstReg = MI->getOperand(0).getReg();
unsigned InsReg = MI->getOperand(2).getReg();
unsigned InsSIdx = MI->getOperand(2).getSubReg();
unsigned SubIdx = MI->getOperand(3).getImm();
assert(SubIdx != 0 && "Invalid index for insert_subreg");
unsigned DstSubReg = TRI.getSubReg(DstReg, SubIdx);
assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
"Insert destination must be in a physical register");
assert(TargetRegisterInfo::isPhysicalRegister(InsReg) &&
"Inserted value must be in a physical register");
DEBUG(errs() << "subreg: CONVERTING: " << *MI);
if (DstSubReg == InsReg && InsSIdx == 0) {
// No need to insert an identify copy instruction.
// Watch out for case like this:
// %RAX<def> = ...
// %RAX<def> = SUBREG_TO_REG 0, %EAX:3<kill>, 3
// The first def is defining RAX, not EAX so the top bits were not
// zero extended.
DEBUG(errs() << "subreg: eliminated!");
} else {
// Insert sub-register copy
const TargetRegisterClass *TRC0= TRI.getPhysicalRegisterRegClass(DstSubReg);
const TargetRegisterClass *TRC1= TRI.getPhysicalRegisterRegClass(InsReg);
TII.copyRegToReg(*MBB, MI, DstSubReg, InsReg, TRC0, TRC1);
// Transfer the kill/dead flags, if needed.
if (MI->getOperand(0).isDead())
TransferDeadFlag(MI, DstSubReg, TRI);
if (MI->getOperand(2).isKill())
TransferKillFlag(MI, InsReg, TRI);
DEBUG({
MachineBasicBlock::iterator dMI = MI;
errs() << "subreg: " << *(--dMI);
});
}
DEBUG(errs() << '\n');
MBB->erase(MI);
return true;
}
bool LowerSubregsInstructionPass::LowerInsert(MachineInstr *MI) {
MachineBasicBlock *MBB = MI->getParent();
MachineFunction &MF = *MBB->getParent();
const TargetRegisterInfo &TRI = *MF.getTarget().getRegisterInfo();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
assert((MI->getOperand(0).isReg() && MI->getOperand(0).isDef()) &&
(MI->getOperand(1).isReg() && MI->getOperand(1).isUse()) &&
(MI->getOperand(2).isReg() && MI->getOperand(2).isUse()) &&
MI->getOperand(3).isImm() && "Invalid insert_subreg");
unsigned DstReg = MI->getOperand(0).getReg();
#ifndef NDEBUG
unsigned SrcReg = MI->getOperand(1).getReg();
#endif
unsigned InsReg = MI->getOperand(2).getReg();
unsigned SubIdx = MI->getOperand(3).getImm();
assert(DstReg == SrcReg && "insert_subreg not a two-address instruction?");
assert(SubIdx != 0 && "Invalid index for insert_subreg");
unsigned DstSubReg = TRI.getSubReg(DstReg, SubIdx);
assert(DstSubReg && "invalid subregister index for register");
assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
"Insert superreg source must be in a physical register");
assert(TargetRegisterInfo::isPhysicalRegister(InsReg) &&
"Inserted value must be in a physical register");
DEBUG(errs() << "subreg: CONVERTING: " << *MI);
if (DstSubReg == InsReg) {
// No need to insert an identity copy instruction. If the SrcReg was
// <undef>, we need to make sure it is alive by inserting a KILL
if (MI->getOperand(1).isUndef() && !MI->getOperand(0).isDead()) {
MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
TII.get(TargetInstrInfo::KILL), DstReg);
if (MI->getOperand(2).isUndef())
MIB.addReg(InsReg, RegState::Undef);
else
MIB.addReg(InsReg, RegState::Kill);
} else {
DEBUG(errs() << "subreg: eliminated!\n");
MBB->erase(MI);
return true;
}
} else {
// Insert sub-register copy
const TargetRegisterClass *TRC0= TRI.getPhysicalRegisterRegClass(DstSubReg);
const TargetRegisterClass *TRC1= TRI.getPhysicalRegisterRegClass(InsReg);
if (MI->getOperand(2).isUndef())
// If the source register being inserted is undef, then this becomes a
// KILL.
BuildMI(*MBB, MI, MI->getDebugLoc(),
TII.get(TargetInstrInfo::KILL), DstSubReg);
else
TII.copyRegToReg(*MBB, MI, DstSubReg, InsReg, TRC0, TRC1);
MachineBasicBlock::iterator CopyMI = MI;
--CopyMI;
// INSERT_SUBREG is a two-address instruction so it implicitly kills SrcReg.
if (!MI->getOperand(1).isUndef())
CopyMI->addOperand(MachineOperand::CreateReg(DstReg, false, true, true));
// Transfer the kill/dead flags, if needed.
if (MI->getOperand(0).isDead()) {
TransferDeadFlag(MI, DstSubReg, TRI);
} else {
// Make sure the full DstReg is live after this replacement.
CopyMI->addOperand(MachineOperand::CreateReg(DstReg, true, true));
}
// Make sure the inserted register gets killed
if (MI->getOperand(2).isKill() && !MI->getOperand(2).isUndef())
TransferKillFlag(MI, InsReg, TRI);
}
DEBUG({
MachineBasicBlock::iterator dMI = MI;
errs() << "subreg: " << *(--dMI) << "\n";
});
MBB->erase(MI);
return true;
}
/// runOnMachineFunction - Reduce subregister inserts and extracts to register
/// copies.
///
bool LowerSubregsInstructionPass::runOnMachineFunction(MachineFunction &MF) {
DEBUG(errs() << "Machine Function\n"
<< "********** LOWERING SUBREG INSTRS **********\n"
<< "********** Function: "
<< MF.getFunction()->getName() << '\n');
bool MadeChange = false;
for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
mbbi != mbbe; ++mbbi) {
for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
mi != me;) {
MachineInstr *MI = mi++;
if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
MadeChange |= LowerExtract(MI);
} else if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
MadeChange |= LowerInsert(MI);
} else if (MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
MadeChange |= LowerSubregToReg(MI);
}
}
}
return MadeChange;
}
<commit_msg>Add some asserts to catch copyRegToReg() fails early<commit_after>//===-- LowerSubregs.cpp - Subregister Lowering instruction pass ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a MachineFunction pass which runs after register
// allocation that turns subreg insert/extract instructions into register
// copies, as needed. This ensures correct codegen even if the coalescer
// isn't able to remove all subreg instructions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "lowersubregs"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Function.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
struct VISIBILITY_HIDDEN LowerSubregsInstructionPass
: public MachineFunctionPass {
static char ID; // Pass identification, replacement for typeid
LowerSubregsInstructionPass() : MachineFunctionPass(&ID) {}
const char *getPassName() const {
return "Subregister lowering instruction pass";
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addPreservedID(MachineLoopInfoID);
AU.addPreservedID(MachineDominatorsID);
MachineFunctionPass::getAnalysisUsage(AU);
}
/// runOnMachineFunction - pass entry point
bool runOnMachineFunction(MachineFunction&);
bool LowerExtract(MachineInstr *MI);
bool LowerInsert(MachineInstr *MI);
bool LowerSubregToReg(MachineInstr *MI);
void TransferDeadFlag(MachineInstr *MI, unsigned DstReg,
const TargetRegisterInfo &TRI);
void TransferKillFlag(MachineInstr *MI, unsigned SrcReg,
const TargetRegisterInfo &TRI,
bool AddIfNotFound = false);
};
char LowerSubregsInstructionPass::ID = 0;
}
FunctionPass *llvm::createLowerSubregsPass() {
return new LowerSubregsInstructionPass();
}
/// TransferDeadFlag - MI is a pseudo-instruction with DstReg dead,
/// and the lowered replacement instructions immediately precede it.
/// Mark the replacement instructions with the dead flag.
void
LowerSubregsInstructionPass::TransferDeadFlag(MachineInstr *MI,
unsigned DstReg,
const TargetRegisterInfo &TRI) {
for (MachineBasicBlock::iterator MII =
prior(MachineBasicBlock::iterator(MI)); ; --MII) {
if (MII->addRegisterDead(DstReg, &TRI))
break;
assert(MII != MI->getParent()->begin() &&
"copyRegToReg output doesn't reference destination register!");
}
}
/// TransferKillFlag - MI is a pseudo-instruction with SrcReg killed,
/// and the lowered replacement instructions immediately precede it.
/// Mark the replacement instructions with the kill flag.
void
LowerSubregsInstructionPass::TransferKillFlag(MachineInstr *MI,
unsigned SrcReg,
const TargetRegisterInfo &TRI,
bool AddIfNotFound) {
for (MachineBasicBlock::iterator MII =
prior(MachineBasicBlock::iterator(MI)); ; --MII) {
if (MII->addRegisterKilled(SrcReg, &TRI, AddIfNotFound))
break;
assert(MII != MI->getParent()->begin() &&
"copyRegToReg output doesn't reference source register!");
}
}
bool LowerSubregsInstructionPass::LowerExtract(MachineInstr *MI) {
MachineBasicBlock *MBB = MI->getParent();
MachineFunction &MF = *MBB->getParent();
const TargetRegisterInfo &TRI = *MF.getTarget().getRegisterInfo();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
assert(MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
MI->getOperand(1).isReg() && MI->getOperand(1).isUse() &&
MI->getOperand(2).isImm() && "Malformed extract_subreg");
unsigned DstReg = MI->getOperand(0).getReg();
unsigned SuperReg = MI->getOperand(1).getReg();
unsigned SubIdx = MI->getOperand(2).getImm();
unsigned SrcReg = TRI.getSubReg(SuperReg, SubIdx);
assert(TargetRegisterInfo::isPhysicalRegister(SuperReg) &&
"Extract supperg source must be a physical register");
assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
"Extract destination must be in a physical register");
assert(SrcReg && "invalid subregister index for register");
DEBUG(errs() << "subreg: CONVERTING: " << *MI);
if (SrcReg == DstReg) {
// No need to insert an identity copy instruction.
if (MI->getOperand(1).isKill()) {
// We must make sure the super-register gets killed. Replace the
// instruction with KILL.
MI->setDesc(TII.get(TargetInstrInfo::KILL));
MI->RemoveOperand(2); // SubIdx
DEBUG(errs() << "subreg: replace by: " << *MI);
return true;
}
DEBUG(errs() << "subreg: eliminated!");
} else {
// Insert copy
const TargetRegisterClass *TRCS = TRI.getPhysicalRegisterRegClass(DstReg);
const TargetRegisterClass *TRCD = TRI.getPhysicalRegisterRegClass(SrcReg);
bool Emitted = TII.copyRegToReg(*MBB, MI, DstReg, SrcReg, TRCD, TRCS);
(void)Emitted;
assert(Emitted && "Subreg and Dst must be of compatible register class");
// Transfer the kill/dead flags, if needed.
if (MI->getOperand(0).isDead())
TransferDeadFlag(MI, DstReg, TRI);
if (MI->getOperand(1).isKill())
TransferKillFlag(MI, SuperReg, TRI, true);
DEBUG({
MachineBasicBlock::iterator dMI = MI;
errs() << "subreg: " << *(--dMI);
});
}
DEBUG(errs() << '\n');
MBB->erase(MI);
return true;
}
bool LowerSubregsInstructionPass::LowerSubregToReg(MachineInstr *MI) {
MachineBasicBlock *MBB = MI->getParent();
MachineFunction &MF = *MBB->getParent();
const TargetRegisterInfo &TRI = *MF.getTarget().getRegisterInfo();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
assert((MI->getOperand(0).isReg() && MI->getOperand(0).isDef()) &&
MI->getOperand(1).isImm() &&
(MI->getOperand(2).isReg() && MI->getOperand(2).isUse()) &&
MI->getOperand(3).isImm() && "Invalid subreg_to_reg");
unsigned DstReg = MI->getOperand(0).getReg();
unsigned InsReg = MI->getOperand(2).getReg();
unsigned InsSIdx = MI->getOperand(2).getSubReg();
unsigned SubIdx = MI->getOperand(3).getImm();
assert(SubIdx != 0 && "Invalid index for insert_subreg");
unsigned DstSubReg = TRI.getSubReg(DstReg, SubIdx);
assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
"Insert destination must be in a physical register");
assert(TargetRegisterInfo::isPhysicalRegister(InsReg) &&
"Inserted value must be in a physical register");
DEBUG(errs() << "subreg: CONVERTING: " << *MI);
if (DstSubReg == InsReg && InsSIdx == 0) {
// No need to insert an identify copy instruction.
// Watch out for case like this:
// %RAX<def> = ...
// %RAX<def> = SUBREG_TO_REG 0, %EAX:3<kill>, 3
// The first def is defining RAX, not EAX so the top bits were not
// zero extended.
DEBUG(errs() << "subreg: eliminated!");
} else {
// Insert sub-register copy
const TargetRegisterClass *TRC0= TRI.getPhysicalRegisterRegClass(DstSubReg);
const TargetRegisterClass *TRC1= TRI.getPhysicalRegisterRegClass(InsReg);
bool Emitted = TII.copyRegToReg(*MBB, MI, DstSubReg, InsReg, TRC0, TRC1);
(void)Emitted;
assert(Emitted && "Subreg and Dst must be of compatible register class");
// Transfer the kill/dead flags, if needed.
if (MI->getOperand(0).isDead())
TransferDeadFlag(MI, DstSubReg, TRI);
if (MI->getOperand(2).isKill())
TransferKillFlag(MI, InsReg, TRI);
DEBUG({
MachineBasicBlock::iterator dMI = MI;
errs() << "subreg: " << *(--dMI);
});
}
DEBUG(errs() << '\n');
MBB->erase(MI);
return true;
}
bool LowerSubregsInstructionPass::LowerInsert(MachineInstr *MI) {
MachineBasicBlock *MBB = MI->getParent();
MachineFunction &MF = *MBB->getParent();
const TargetRegisterInfo &TRI = *MF.getTarget().getRegisterInfo();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
assert((MI->getOperand(0).isReg() && MI->getOperand(0).isDef()) &&
(MI->getOperand(1).isReg() && MI->getOperand(1).isUse()) &&
(MI->getOperand(2).isReg() && MI->getOperand(2).isUse()) &&
MI->getOperand(3).isImm() && "Invalid insert_subreg");
unsigned DstReg = MI->getOperand(0).getReg();
#ifndef NDEBUG
unsigned SrcReg = MI->getOperand(1).getReg();
#endif
unsigned InsReg = MI->getOperand(2).getReg();
unsigned SubIdx = MI->getOperand(3).getImm();
assert(DstReg == SrcReg && "insert_subreg not a two-address instruction?");
assert(SubIdx != 0 && "Invalid index for insert_subreg");
unsigned DstSubReg = TRI.getSubReg(DstReg, SubIdx);
assert(DstSubReg && "invalid subregister index for register");
assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
"Insert superreg source must be in a physical register");
assert(TargetRegisterInfo::isPhysicalRegister(InsReg) &&
"Inserted value must be in a physical register");
DEBUG(errs() << "subreg: CONVERTING: " << *MI);
if (DstSubReg == InsReg) {
// No need to insert an identity copy instruction. If the SrcReg was
// <undef>, we need to make sure it is alive by inserting a KILL
if (MI->getOperand(1).isUndef() && !MI->getOperand(0).isDead()) {
MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
TII.get(TargetInstrInfo::KILL), DstReg);
if (MI->getOperand(2).isUndef())
MIB.addReg(InsReg, RegState::Undef);
else
MIB.addReg(InsReg, RegState::Kill);
} else {
DEBUG(errs() << "subreg: eliminated!\n");
MBB->erase(MI);
return true;
}
} else {
// Insert sub-register copy
const TargetRegisterClass *TRC0= TRI.getPhysicalRegisterRegClass(DstSubReg);
const TargetRegisterClass *TRC1= TRI.getPhysicalRegisterRegClass(InsReg);
if (MI->getOperand(2).isUndef())
// If the source register being inserted is undef, then this becomes a
// KILL.
BuildMI(*MBB, MI, MI->getDebugLoc(),
TII.get(TargetInstrInfo::KILL), DstSubReg);
else {
bool Emitted = TII.copyRegToReg(*MBB, MI, DstSubReg, InsReg, TRC0, TRC1);
(void)Emitted;
assert(Emitted && "Subreg and Dst must be of compatible register class");
}
MachineBasicBlock::iterator CopyMI = MI;
--CopyMI;
// INSERT_SUBREG is a two-address instruction so it implicitly kills SrcReg.
if (!MI->getOperand(1).isUndef())
CopyMI->addOperand(MachineOperand::CreateReg(DstReg, false, true, true));
// Transfer the kill/dead flags, if needed.
if (MI->getOperand(0).isDead()) {
TransferDeadFlag(MI, DstSubReg, TRI);
} else {
// Make sure the full DstReg is live after this replacement.
CopyMI->addOperand(MachineOperand::CreateReg(DstReg, true, true));
}
// Make sure the inserted register gets killed
if (MI->getOperand(2).isKill() && !MI->getOperand(2).isUndef())
TransferKillFlag(MI, InsReg, TRI);
}
DEBUG({
MachineBasicBlock::iterator dMI = MI;
errs() << "subreg: " << *(--dMI) << "\n";
});
MBB->erase(MI);
return true;
}
/// runOnMachineFunction - Reduce subregister inserts and extracts to register
/// copies.
///
bool LowerSubregsInstructionPass::runOnMachineFunction(MachineFunction &MF) {
DEBUG(errs() << "Machine Function\n"
<< "********** LOWERING SUBREG INSTRS **********\n"
<< "********** Function: "
<< MF.getFunction()->getName() << '\n');
bool MadeChange = false;
for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
mbbi != mbbe; ++mbbi) {
for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
mi != me;) {
MachineInstr *MI = mi++;
if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
MadeChange |= LowerExtract(MI);
} else if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
MadeChange |= LowerInsert(MI);
} else if (MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
MadeChange |= LowerSubregToReg(MI);
}
}
}
return MadeChange;
}
<|endoftext|> |
<commit_before>/*
* This file is part of Poedit (https://poedit.net)
*
* Copyright (C) 2000-2017 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.
*
*/
#include <wx/utils.h>
#include <wx/log.h>
#include <wx/process.h>
#include <wx/txtstrm.h>
#include <wx/string.h>
#include <wx/intl.h>
#include <wx/stdpaths.h>
#include <wx/translation.h>
#include <wx/filename.h>
#include <boost/throw_exception.hpp>
#include "gexecute.h"
#include "errors.h"
// GCC's libstdc++ didn't have functional std::regex implementation until 4.9
#if (defined(__GNUC__) && !defined(__clang__) && !wxCHECK_GCC_VERSION(4,9))
#include <boost/regex.hpp>
using boost::wregex;
using boost::wsmatch;
using boost::regex_match;
#else
#include <regex>
using std::wregex;
using std::wsmatch;
using std::regex_match;
#endif
namespace
{
#ifdef __WXOSX__
wxString GetGettextPluginPath()
{
return wxStandardPaths::Get().GetPluginsDir() + "/GettextTools.bundle";
}
#endif // __WXOSX__
#if defined(__WXOSX__) || defined(__WXMSW__)
inline wxString GetAuxBinariesDir()
{
return GetGettextPackagePath() + "/bin";
}
wxString GetPathToAuxBinary(const wxString& program)
{
wxFileName path;
path.SetPath(GetAuxBinariesDir());
path.SetName(program);
#ifdef __WXMSW__
path.SetExt("exe");
#endif
if ( path.IsFileExecutable() )
{
return wxString::Format(_T("\"%s\""), path.GetFullPath().c_str());
}
else
{
wxLogTrace("poedit.execute",
"%s doesn't exist, falling back to %s",
path.GetFullPath().c_str(),
program.c_str());
return program;
}
}
#endif // __WXOSX__ || __WXMSW__
bool ReadOutput(wxInputStream& s, wxArrayString& out)
{
// the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state
s.Reset();
wxTextInputStream tis(s, " ", wxConvUTF8);
while (true)
{
wxString line = tis.ReadLine();
if ( !line.empty() )
out.push_back(line);
if (s.Eof())
break;
if ( !s )
return false;
}
return true;
}
long DoExecuteGettext(const wxString& cmdline_, wxArrayString& gstderr)
{
wxExecuteEnv env;
wxString cmdline(cmdline_);
#if defined(__WXOSX__) || defined(__WXMSW__)
wxString binary = cmdline.BeforeFirst(_T(' '));
cmdline = GetPathToAuxBinary(binary) + cmdline.Mid(binary.length());
wxGetEnvMap(&env.env);
env.env["GETTEXTIOENCODING"] = "UTF-8";
wxString lang = wxTranslations::Get()->GetBestTranslation("gettext-tools");
if ( !lang.empty() )
env.env["LANG"] = lang;
#endif // __WXOSX__ || __WXMSW__
#ifdef __WXOSX__
// Hack alert! On Windows, relocation works, but building with it is too
// messy/broken on macOS, so just use some custom hacks instead:
auto sharedir = GetGettextPackagePath() + "/share";
env.env["POEDIT_LOCALEDIR"] = sharedir + "/locale";
env.env["GETTEXTDATADIR"] = sharedir + "/gettext";
#endif
wxLogTrace("poedit.execute", "executing: %s", cmdline.c_str());
wxScopedPtr<wxProcess> process(new wxProcess);
process->Redirect();
long retcode = wxExecute(cmdline, wxEXEC_BLOCK | wxEXEC_NODISABLE | wxEXEC_NOEVENTS, process.get(), &env);
wxInputStream *std_err = process->GetErrorStream();
if ( std_err && !ReadOutput(*std_err, gstderr) )
retcode = -1;
if ( retcode == -1 )
{
BOOST_THROW_EXCEPTION(Exception(wxString::Format(_("Cannot execute program: %s"), cmdline.c_str())));
}
return retcode;
}
} // anonymous namespace
bool ExecuteGettext(const wxString& cmdline)
{
wxArrayString gstderr;
long retcode = DoExecuteGettext(cmdline, gstderr);
for ( size_t i = 0; i < gstderr.size(); i++ )
{
if ( gstderr[i].empty() )
continue;
wxLogError("%s", gstderr[i].c_str());
}
return retcode == 0;
}
bool ExecuteGettextAndParseOutput(const wxString& cmdline, GettextErrors& errors)
{
wxArrayString gstderr;
long retcode = DoExecuteGettext(cmdline, gstderr);
static const wregex RE_ERROR(L".*\\.po:([0-9]+)(:[0-9]+)?: (.*)");
for (const auto& ewx: gstderr)
{
const auto e = ewx.ToStdWstring();
wxLogTrace("poedit", " stderr: %s", e.c_str());
if ( e.empty() )
continue;
GettextError rec;
wsmatch match;
if (regex_match(e, match, RE_ERROR))
{
rec.line = std::stoi(match.str(1));
rec.text = match.str(3);
errors.push_back(rec);
wxLogTrace("poedit.execute",
_T(" => parsed error = \"%s\" at %d"),
rec.text.c_str(), rec.line);
}
else
{
wxLogTrace("poedit.execute", " (unrecognized line!)");
// FIXME: handle the rest of output gracefully too
}
}
return retcode == 0;
}
wxString QuoteCmdlineArg(const wxString& s)
{
wxString s2(s);
#ifdef __UNIX__
s2.Replace("\"", "\\\"");
#endif
return "\"" + s2 + "\"";
}
#if defined(__WXOSX__) || defined(__WXMSW__)
wxString GetGettextPackagePath()
{
#if defined(__WXOSX__)
return GetGettextPluginPath() + "/Contents/MacOS";
#elif defined(__WXMSW__)
return wxStandardPaths::Get().GetDataDir() + wxFILE_SEP_PATH + "GettextTools";
#endif
}
#endif // __WXOSX__ || __WXMSW__
<commit_msg>Group multiline gettext errors into one<commit_after>/*
* This file is part of Poedit (https://poedit.net)
*
* Copyright (C) 2000-2017 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.
*
*/
#include <wx/utils.h>
#include <wx/log.h>
#include <wx/process.h>
#include <wx/txtstrm.h>
#include <wx/string.h>
#include <wx/intl.h>
#include <wx/stdpaths.h>
#include <wx/translation.h>
#include <wx/filename.h>
#include <boost/throw_exception.hpp>
#include "gexecute.h"
#include "errors.h"
// GCC's libstdc++ didn't have functional std::regex implementation until 4.9
#if (defined(__GNUC__) && !defined(__clang__) && !wxCHECK_GCC_VERSION(4,9))
#include <boost/regex.hpp>
using boost::wregex;
using boost::wsmatch;
using boost::regex_match;
#else
#include <regex>
using std::wregex;
using std::wsmatch;
using std::regex_match;
#endif
namespace
{
#ifdef __WXOSX__
wxString GetGettextPluginPath()
{
return wxStandardPaths::Get().GetPluginsDir() + "/GettextTools.bundle";
}
#endif // __WXOSX__
#if defined(__WXOSX__) || defined(__WXMSW__)
inline wxString GetAuxBinariesDir()
{
return GetGettextPackagePath() + "/bin";
}
wxString GetPathToAuxBinary(const wxString& program)
{
wxFileName path;
path.SetPath(GetAuxBinariesDir());
path.SetName(program);
#ifdef __WXMSW__
path.SetExt("exe");
#endif
if ( path.IsFileExecutable() )
{
return wxString::Format(_T("\"%s\""), path.GetFullPath().c_str());
}
else
{
wxLogTrace("poedit.execute",
"%s doesn't exist, falling back to %s",
path.GetFullPath().c_str(),
program.c_str());
return program;
}
}
#endif // __WXOSX__ || __WXMSW__
bool ReadOutput(wxInputStream& s, wxArrayString& out)
{
// the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state
s.Reset();
wxTextInputStream tis(s, " ", wxConvUTF8);
while (true)
{
wxString line = tis.ReadLine();
if ( !line.empty() )
out.push_back(line);
if (s.Eof())
break;
if ( !s )
return false;
}
return true;
}
long DoExecuteGettext(const wxString& cmdline_, wxArrayString& gstderr)
{
wxExecuteEnv env;
wxString cmdline(cmdline_);
#if defined(__WXOSX__) || defined(__WXMSW__)
wxString binary = cmdline.BeforeFirst(_T(' '));
cmdline = GetPathToAuxBinary(binary) + cmdline.Mid(binary.length());
wxGetEnvMap(&env.env);
env.env["GETTEXTIOENCODING"] = "UTF-8";
wxString lang = wxTranslations::Get()->GetBestTranslation("gettext-tools");
if ( !lang.empty() )
env.env["LANG"] = lang;
#endif // __WXOSX__ || __WXMSW__
#ifdef __WXOSX__
// Hack alert! On Windows, relocation works, but building with it is too
// messy/broken on macOS, so just use some custom hacks instead:
auto sharedir = GetGettextPackagePath() + "/share";
env.env["POEDIT_LOCALEDIR"] = sharedir + "/locale";
env.env["GETTEXTDATADIR"] = sharedir + "/gettext";
#endif
wxLogTrace("poedit.execute", "executing: %s", cmdline.c_str());
wxScopedPtr<wxProcess> process(new wxProcess);
process->Redirect();
long retcode = wxExecute(cmdline, wxEXEC_BLOCK | wxEXEC_NODISABLE | wxEXEC_NOEVENTS, process.get(), &env);
wxInputStream *std_err = process->GetErrorStream();
if ( std_err && !ReadOutput(*std_err, gstderr) )
retcode = -1;
if ( retcode == -1 )
{
BOOST_THROW_EXCEPTION(Exception(wxString::Format(_("Cannot execute program: %s"), cmdline.c_str())));
}
return retcode;
}
} // anonymous namespace
bool ExecuteGettext(const wxString& cmdline)
{
wxArrayString gstderr;
long retcode = DoExecuteGettext(cmdline, gstderr);
wxString pending;
for (auto& ln: gstderr)
{
if (ln.empty())
continue;
// special handling of multiline errors
if (ln[0] == ' ' || ln[0] == '\t')
{
pending += "\n\t" + ln.Strip(wxString::both);
}
else
{
if (!pending.empty())
wxLogError("%s", pending);
pending = ln;
}
}
if (!pending.empty())
wxLogError("%s", pending);
return retcode == 0;
}
bool ExecuteGettextAndParseOutput(const wxString& cmdline, GettextErrors& errors)
{
wxArrayString gstderr;
long retcode = DoExecuteGettext(cmdline, gstderr);
static const wregex RE_ERROR(L".*\\.po:([0-9]+)(:[0-9]+)?: (.*)");
for (const auto& ewx: gstderr)
{
const auto e = ewx.ToStdWstring();
wxLogTrace("poedit", " stderr: %s", e.c_str());
if ( e.empty() )
continue;
GettextError rec;
wsmatch match;
if (regex_match(e, match, RE_ERROR))
{
rec.line = std::stoi(match.str(1));
rec.text = match.str(3);
errors.push_back(rec);
wxLogTrace("poedit.execute",
_T(" => parsed error = \"%s\" at %d"),
rec.text.c_str(), rec.line);
}
else
{
wxLogTrace("poedit.execute", " (unrecognized line!)");
// FIXME: handle the rest of output gracefully too
}
}
return retcode == 0;
}
wxString QuoteCmdlineArg(const wxString& s)
{
wxString s2(s);
#ifdef __UNIX__
s2.Replace("\"", "\\\"");
#endif
return "\"" + s2 + "\"";
}
#if defined(__WXOSX__) || defined(__WXMSW__)
wxString GetGettextPackagePath()
{
#if defined(__WXOSX__)
return GetGettextPluginPath() + "/Contents/MacOS";
#elif defined(__WXMSW__)
return wxStandardPaths::Get().GetDataDir() + wxFILE_SEP_PATH + "GettextTools";
#endif
}
#endif // __WXOSX__ || __WXMSW__
<|endoftext|> |
<commit_before>
#include <iostream>
#include <cassert>
#include <fstream>
#include <string>
#include <algorithm>
#include <random>
#include <cstring>
#include <chrono>
#include <memory>
#include <cmath>
#include <argp.h>
#include <unsupported/Eigen/SparseExtra>
#include <Eigen/Sparse>
#include <getopt.h>
#include <signal.h>
#include "session.h"
#include "mvnormal.h"
#include "utils.h"
#include "omp_util.h"
#include "linop.h"
#include "gen_random.h"
#include "Data.h"
#include "ILatentPrior.h"
#include "MacauOnePrior.hpp"
using namespace std;
using namespace Eigen;
namespace smurff {
enum OPT_ENUM {
ROW_PRIOR = 1024, COL_PRIOR, ROW_FEATURES, COL_FEATURES, FNAME_ROW_MODEL, FNAME_COL_MODEL, FNAME_TEST, FNAME_TRAIN,
BURNIN, NSAMPLES, NUM_LATENT, PRECISION, ADAPTIVE, LAMBDA_BETA, TOL, DIRECT,
RESTORE_PREFIX, RESTORE_SUFFIX, SAVE_PREFIX, SAVE_SUFFIX, SAVE_FREQ, THRESHOLD, VERBOSE, QUIET,
INIT_MODEL, CENTER, STATUS_FILE
};
static int parse_opts(int key, char *optarg, struct argp_state *state)
{
Config &c = *(Config *)(state->input);
auto set_noise_model = [&c](std::string name, std::string optarg)
{
NoiseConfig nc;
nc.name = name;
if (name == "adaptive")
{
char *token, *str = strdup(optarg.c_str());
if(str && (token = strsep(&str, ","))) nc.sn_init = strtod(token, NULL);
if(str && (token = strsep(&str, ","))) nc.sn_max = strtod(token, NULL);
}
else if (name == "fixed")
{
nc.precision = strtod(optarg.c_str(), NULL);
}
// set global noise model
if (c.train.getNoiseConfig().name == "noiseless")
c.train.setNoiseConfig(nc);
//set for row/col feautres
for(auto &m: c.row_features)
if (m.getNoiseConfig().name == "noiseless")
m.setNoiseConfig(nc);
for(auto &m: c.col_features)
if (m.getNoiseConfig().name == "noiseless")
m.setNoiseConfig(nc);
};
switch (key)
{
case ROW_PRIOR: c.row_prior = optarg; break;
case COL_PRIOR: c.col_prior = optarg; break;
case ROW_FEATURES: c.row_features.push_back(read_matrix(optarg)); break;
case COL_FEATURES: c.col_features.push_back(read_matrix(optarg)); break;
case CENTER: c.center_mode = optarg; break;
case FNAME_TRAIN: c.train = read_sparse(optarg); break;
case LAMBDA_BETA: c.lambda_beta = strtod(optarg, NULL); break;
case BURNIN: c.burnin = strtol(optarg, NULL, 10); break;
case TOL: c.tol = atof(optarg); break;
case DIRECT: c.direct = true; break;
case FNAME_TEST: c.test = read_sparse(optarg); break;
case NUM_LATENT: c.num_latent = strtol(optarg, NULL, 10); break;
case NSAMPLES: c.nsamples = strtol(optarg, NULL, 10); break;
case RESTORE_PREFIX: c.restore_prefix = std::string(optarg); break;
case RESTORE_SUFFIX: c.restore_suffix = std::string(optarg); break;
case SAVE_PREFIX: c.save_prefix = std::string(optarg); break;
case SAVE_SUFFIX: c.save_suffix = std::string(optarg); break;
case SAVE_FREQ: c.save_freq = strtol(optarg, NULL, 10); break;
case PRECISION: set_noise_model("fixed", optarg); break;
case ADAPTIVE: set_noise_model("adaptive", optarg); break;
case THRESHOLD: c.threshold = strtod(optarg, 0); c.classify = true; break;
case INIT_MODEL: c.init_model = optarg; break;
case VERBOSE: c.verbose = optarg ? strtol(optarg, NULL, 0) : 1; break;
case QUIET: c.verbose = 0; break;
case STATUS_FILE: c.csv_status = optarg; break;
default: return ARGP_ERR_UNKNOWN;
}
return 0;
}
void CmdSession::setFromArgs(int argc, char** argv) {
/* Program documentation. */
char doc[] = "SMURFF: Scalable Matrix Factorization Framework -- http://github.com/ExaScience/smurff";
struct argp_option options[] = {
{0,0,0,0,"Priors and side Info:",1},
{"row-prior", ROW_PRIOR , "PRIOR", 0, "One of <normal|spikeandslab|macau|macauone>"},
{"col-prior", COL_PRIOR , "PRIOR", 0, "One of <normal|spikeandslab|macau|macauone>"},
{"row-features", ROW_FEATURES , "FILE", 0, "side info for rows"},
{"col-features", COL_FEATURES , "FILE", 0, "side info for cols"},
{"row-model", FNAME_ROW_MODEL , "FILE", 0, "initialization matrix for row model"},
{"col-model", FNAME_COL_MODEL , "FILE", 0, "initialization matrix for col model"},
{"center", CENTER , "MODE", 0, "center <global|rows|cols|none>"},
{0,0,0,0,"Test and train matrices:",2},
{"test", FNAME_TEST , "FILE", 0, "test data (for computing RMSE)"},
{"train", FNAME_TRAIN , "FILE", 0, "train data file"},
{0,0,0,0,"General parameters:",3},
{"burnin", BURNIN , "NUM", 0, "200 number of samples to discard"},
{"nsamples", NSAMPLES , "NUM", 0, "800 number of samples to collect"},
{"num-latent", NUM_LATENT , "NUM", 0, "96 number of latent dimensions"},
{"restore-prefix", RESTORE_PREFIX , "PATH", 0, "prefix for file to initialize stae"},
{"restore-suffix", RESTORE_SUFFIX , "EXT", 0, "suffix for initialization files (.csv or .ddm)"},
{"init-model", INIT_MODEL , "NAME", 0, "One of <random|zero>"},
{"save-prefix", SAVE_PREFIX , "PATH", 0, "prefix for result files"},
{"save-suffix", SAVE_SUFFIX , "EXT", 0, "suffix for result files (.csv or .ddm)"},
{"save-freq", SAVE_FREQ , "NUM", 0, "save every n iterations (0 == never)"},
{"threshold", THRESHOLD , "NUM", 0, "threshold for binary classification"},
{"verbose", VERBOSE , "NUM", OPTION_ARG_OPTIONAL, "verbose output (default = 1)"},
{"quiet", QUIET , 0, 0, "no output"},
{"status", STATUS_FILE, "FILE", 0, "output progress to csv file"},
{0,0,0,0,"Noise model:",4},
{"precision", PRECISION , "NUM", 0, "5.0 precision of observations"},
{"adaptive", ADAPTIVE , "NUM,NUM", 0, "1.0,10.0 adavtive precision of observations"},
{0,0,0,0,"For the macau prior:",5},
{"lambda-beta", LAMBDA_BETA , "NUM", 0, "10.0 initial value of lambda beta"},
{"tol", TOL , "NUM", 0, "1e-6 tolerance for CG"},
{"direct", DIRECT , 0, 0, "false Use Cholesky decomposition i.o. CG Solver"},
{0,0,0,0,"General Options:",0},
{0}
};
Config c;
struct argp argp = { options, parse_opts, 0, doc };
argp_parse (&argp, argc, argv, 0, 0, &c);
setFromConfig(c);
}
} // end namespace smurff
<commit_msg>Update docstring<commit_after>
#include <iostream>
#include <cassert>
#include <fstream>
#include <string>
#include <algorithm>
#include <random>
#include <cstring>
#include <chrono>
#include <memory>
#include <cmath>
#include <argp.h>
#include <unsupported/Eigen/SparseExtra>
#include <Eigen/Sparse>
#include <getopt.h>
#include <signal.h>
#include "session.h"
#include "mvnormal.h"
#include "utils.h"
#include "omp_util.h"
#include "linop.h"
#include "gen_random.h"
#include "Data.h"
#include "ILatentPrior.h"
#include "MacauOnePrior.hpp"
using namespace std;
using namespace Eigen;
namespace smurff {
enum OPT_ENUM {
ROW_PRIOR = 1024, COL_PRIOR, ROW_FEATURES, COL_FEATURES, FNAME_ROW_MODEL, FNAME_COL_MODEL, FNAME_TEST, FNAME_TRAIN,
BURNIN, NSAMPLES, NUM_LATENT, PRECISION, ADAPTIVE, LAMBDA_BETA, TOL, DIRECT,
RESTORE_PREFIX, RESTORE_SUFFIX, SAVE_PREFIX, SAVE_SUFFIX, SAVE_FREQ, THRESHOLD, VERBOSE, QUIET,
INIT_MODEL, CENTER, STATUS_FILE
};
static int parse_opts(int key, char *optarg, struct argp_state *state)
{
Config &c = *(Config *)(state->input);
auto set_noise_model = [&c](std::string name, std::string optarg)
{
NoiseConfig nc;
nc.name = name;
if (name == "adaptive")
{
char *token, *str = strdup(optarg.c_str());
if(str && (token = strsep(&str, ","))) nc.sn_init = strtod(token, NULL);
if(str && (token = strsep(&str, ","))) nc.sn_max = strtod(token, NULL);
}
else if (name == "fixed")
{
nc.precision = strtod(optarg.c_str(), NULL);
}
// set global noise model
if (c.train.getNoiseConfig().name == "noiseless")
c.train.setNoiseConfig(nc);
//set for row/col feautres
for(auto &m: c.row_features)
if (m.getNoiseConfig().name == "noiseless")
m.setNoiseConfig(nc);
for(auto &m: c.col_features)
if (m.getNoiseConfig().name == "noiseless")
m.setNoiseConfig(nc);
};
switch (key)
{
case ROW_PRIOR: c.row_prior = optarg; break;
case COL_PRIOR: c.col_prior = optarg; break;
case ROW_FEATURES: c.row_features.push_back(read_matrix(optarg)); break;
case COL_FEATURES: c.col_features.push_back(read_matrix(optarg)); break;
case CENTER: c.center_mode = optarg; break;
case FNAME_TRAIN: c.train = read_sparse(optarg); break;
case LAMBDA_BETA: c.lambda_beta = strtod(optarg, NULL); break;
case BURNIN: c.burnin = strtol(optarg, NULL, 10); break;
case TOL: c.tol = atof(optarg); break;
case DIRECT: c.direct = true; break;
case FNAME_TEST: c.test = read_sparse(optarg); break;
case NUM_LATENT: c.num_latent = strtol(optarg, NULL, 10); break;
case NSAMPLES: c.nsamples = strtol(optarg, NULL, 10); break;
case RESTORE_PREFIX: c.restore_prefix = std::string(optarg); break;
case RESTORE_SUFFIX: c.restore_suffix = std::string(optarg); break;
case SAVE_PREFIX: c.save_prefix = std::string(optarg); break;
case SAVE_SUFFIX: c.save_suffix = std::string(optarg); break;
case SAVE_FREQ: c.save_freq = strtol(optarg, NULL, 10); break;
case PRECISION: set_noise_model("fixed", optarg); break;
case ADAPTIVE: set_noise_model("adaptive", optarg); break;
case THRESHOLD: c.threshold = strtod(optarg, 0); c.classify = true; break;
case INIT_MODEL: c.init_model = optarg; break;
case VERBOSE: c.verbose = optarg ? strtol(optarg, NULL, 0) : 1; break;
case QUIET: c.verbose = 0; break;
case STATUS_FILE: c.csv_status = optarg; break;
default: return ARGP_ERR_UNKNOWN;
}
return 0;
}
void CmdSession::setFromArgs(int argc, char** argv) {
/* Program documentation. */
char doc[] = "SMURFF: Scalable Matrix Factorization Framework\n\thttp://github.com/ExaScience/smurff";
struct argp_option options[] = {
{0,0,0,0,"Priors and side Info:",1},
{"row-prior", ROW_PRIOR , "PRIOR", 0, "One of <normal|spikeandslab|macau|macauone>"},
{"col-prior", COL_PRIOR , "PRIOR", 0, "One of <normal|spikeandslab|macau|macauone>"},
{"row-features", ROW_FEATURES , "FILE", 0, "side info for rows"},
{"col-features", COL_FEATURES , "FILE", 0, "side info for cols"},
{"row-model", FNAME_ROW_MODEL , "FILE", 0, "initialization matrix for row model"},
{"col-model", FNAME_COL_MODEL , "FILE", 0, "initialization matrix for col model"},
{"center", CENTER , "MODE", 0, "center <global|rows|cols|none>"},
{0,0,0,0,"Test and train matrices:",2},
{"test", FNAME_TEST , "FILE", 0, "test data (for computing RMSE)"},
{"train", FNAME_TRAIN , "FILE", 0, "train data file"},
{0,0,0,0,"General parameters:",3},
{"burnin", BURNIN , "NUM", 0, "200 number of samples to discard"},
{"nsamples", NSAMPLES , "NUM", 0, "800 number of samples to collect"},
{"num-latent", NUM_LATENT , "NUM", 0, "96 number of latent dimensions"},
{"restore-prefix", RESTORE_PREFIX , "PATH", 0, "prefix for file to initialize stae"},
{"restore-suffix", RESTORE_SUFFIX , "EXT", 0, "suffix for initialization files (.csv or .ddm)"},
{"init-model", INIT_MODEL , "NAME", 0, "One of <random|zero>"},
{"save-prefix", SAVE_PREFIX , "PATH", 0, "prefix for result files"},
{"save-suffix", SAVE_SUFFIX , "EXT", 0, "suffix for result files (.csv or .ddm)"},
{"save-freq", SAVE_FREQ , "NUM", 0, "save every n iterations (0 == never)"},
{"threshold", THRESHOLD , "NUM", 0, "threshold for binary classification"},
{"verbose", VERBOSE , "NUM", OPTION_ARG_OPTIONAL, "verbose output (default = 1)"},
{"quiet", QUIET , 0, 0, "no output"},
{"status", STATUS_FILE, "FILE", 0, "output progress to csv file"},
{0,0,0,0,"Noise model:",4},
{"precision", PRECISION , "NUM", 0, "5.0 precision of observations"},
{"adaptive", ADAPTIVE , "NUM,NUM", 0, "1.0,10.0 adavtive precision of observations"},
{0,0,0,0,"For the macau prior:",5},
{"lambda-beta", LAMBDA_BETA , "NUM", 0, "10.0 initial value of lambda beta"},
{"tol", TOL , "NUM", 0, "1e-6 tolerance for CG"},
{"direct", DIRECT , 0, 0, "false Use Cholesky decomposition i.o. CG Solver"},
{0,0,0,0,"General Options:",0},
{0}
};
Config c;
struct argp argp = { options, parse_opts, 0, doc };
argp_parse (&argp, argc, argv, 0, 0, &c);
setFromConfig(c);
}
} // end namespace smurff
<|endoftext|> |
<commit_before>/*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
smtlib_frontend.cpp
Abstract:
Frontend for reading Smtlib input files
Author:
Nikolaj Bjorner (nbjorner) 2006-11-3.
Revision History:
Leonardo de Moura: new SMT 2.0 front-end, removed support for .smtc files and smtcmd_solver object.
--*/
#include<iostream>
#include<time.h>
#include<signal.h>
#include"smtlib_solver.h"
#include"timeout.h"
#include"smt2parser.h"
#include"dl_cmds.h"
#include"dbg_cmds.h"
#include"polynomial_cmds.h"
#include"subpaving_cmds.h"
#include"smt_strategic_solver.h"
extern bool g_display_statistics;
extern void display_config();
static clock_t g_start_time;
static smtlib::solver* g_solver = 0;
static cmd_context * g_cmd_context = 0;
static void display_statistics() {
clock_t end_time = clock();
if ((g_solver || g_cmd_context) && g_display_statistics) {
std::cout.flush();
std::cerr.flush();
if (g_solver) {
g_solver->display_statistics();
memory::display_max_usage(std::cout);
std::cout << "time: " << ((static_cast<double>(end_time) - static_cast<double>(g_start_time)) / CLOCKS_PER_SEC) << " secs\n";
}
else if (g_cmd_context) {
g_cmd_context->set_regular_stream("stdout");
g_cmd_context->display_statistics(true, ((static_cast<double>(end_time) - static_cast<double>(g_start_time)) / CLOCKS_PER_SEC));
}
}
}
static void on_timeout() {
display_statistics();
exit(0);
}
static void on_ctrl_c(int) {
signal (SIGINT, SIG_DFL);
display_statistics();
raise(SIGINT);
}
unsigned read_smtlib_file(char const * benchmark_file) {
g_start_time = clock();
register_on_timeout_proc(on_timeout);
signal(SIGINT, on_ctrl_c);
smtlib::solver solver;
g_solver = &solver;
bool ok = true;
ok = solver.solve_smt(benchmark_file);
if (!ok) {
if (benchmark_file) {
std::cerr << "ERROR: solving '" << benchmark_file << "'.\n";
}
else {
std::cerr << "ERROR: solving input stream.\n";
}
}
display_statistics();
register_on_timeout_proc(0);
g_solver = 0;
return solver.get_error_code();
}
unsigned read_smtlib2_commands(char const * file_name) {
g_start_time = clock();
register_on_timeout_proc(on_timeout);
signal(SIGINT, on_ctrl_c);
cmd_context ctx;
ctx.set_solver_factory(mk_smt_strategic_solver_factory());
install_dl_cmds(ctx);
install_dbg_cmds(ctx);
install_polynomial_cmds(ctx);
install_subpaving_cmds(ctx);
g_cmd_context = &ctx;
signal(SIGINT, on_ctrl_c);
bool result = true;
if (file_name) {
std::ifstream in(file_name);
if (in.bad() || in.fail()) {
std::cerr << "(error \"failed to open file '" << file_name << "'\")" << std::endl;
exit(ERR_OPEN_FILE);
}
result = parse_smt2_commands(ctx, in);
}
else {
result = parse_smt2_commands(ctx, std::cin, true);
}
display_statistics();
g_cmd_context = 0;
return result ? 0 : 1;
}
<commit_msg>addressing race condition on interrupts<commit_after>/*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
smtlib_frontend.cpp
Abstract:
Frontend for reading Smtlib input files
Author:
Nikolaj Bjorner (nbjorner) 2006-11-3.
Revision History:
Leonardo de Moura: new SMT 2.0 front-end, removed support for .smtc files and smtcmd_solver object.
--*/
#include<iostream>
#include<time.h>
#include<signal.h>
#include"smtlib_solver.h"
#include"timeout.h"
#include"smt2parser.h"
#include"dl_cmds.h"
#include"dbg_cmds.h"
#include"polynomial_cmds.h"
#include"subpaving_cmds.h"
#include"smt_strategic_solver.h"
extern bool g_display_statistics;
extern void display_config();
static clock_t g_start_time;
static smtlib::solver* g_solver = 0;
static cmd_context * g_cmd_context = 0;
static void display_statistics() {
clock_t end_time = clock();
if ((g_solver || g_cmd_context) && g_display_statistics) {
std::cout.flush();
std::cerr.flush();
if (g_solver) {
g_solver->display_statistics();
memory::display_max_usage(std::cout);
std::cout << "time: " << ((static_cast<double>(end_time) - static_cast<double>(g_start_time)) / CLOCKS_PER_SEC) << " secs\n";
}
else if (g_cmd_context) {
g_cmd_context->set_regular_stream("stdout");
g_cmd_context->display_statistics(true, ((static_cast<double>(end_time) - static_cast<double>(g_start_time)) / CLOCKS_PER_SEC));
}
}
}
static void on_timeout() {
#pragma omp critical (g_display_stats)
{
display_statistics();
exit(0);
}
}
static void on_ctrl_c(int) {
signal (SIGINT, SIG_DFL);
#pragma omp critical (g_display_stats)
{
display_statistics();
}
raise(SIGINT);
}
unsigned read_smtlib_file(char const * benchmark_file) {
g_start_time = clock();
register_on_timeout_proc(on_timeout);
signal(SIGINT, on_ctrl_c);
smtlib::solver solver;
g_solver = &solver;
bool ok = true;
ok = solver.solve_smt(benchmark_file);
if (!ok) {
if (benchmark_file) {
std::cerr << "ERROR: solving '" << benchmark_file << "'.\n";
}
else {
std::cerr << "ERROR: solving input stream.\n";
}
}
#pragma omp critical (g_display_stats)
{
display_statistics();
register_on_timeout_proc(0);
g_solver = 0;
}
return solver.get_error_code();
}
unsigned read_smtlib2_commands(char const * file_name) {
g_start_time = clock();
register_on_timeout_proc(on_timeout);
signal(SIGINT, on_ctrl_c);
cmd_context ctx;
ctx.set_solver_factory(mk_smt_strategic_solver_factory());
install_dl_cmds(ctx);
install_dbg_cmds(ctx);
install_polynomial_cmds(ctx);
install_subpaving_cmds(ctx);
g_cmd_context = &ctx;
signal(SIGINT, on_ctrl_c);
bool result = true;
if (file_name) {
std::ifstream in(file_name);
if (in.bad() || in.fail()) {
std::cerr << "(error \"failed to open file '" << file_name << "'\")" << std::endl;
exit(ERR_OPEN_FILE);
}
result = parse_smt2_commands(ctx, in);
}
else {
result = parse_smt2_commands(ctx, std::cin, true);
}
#pragma omp critical (g_display_stats)
{
display_statistics();
g_cmd_context = 0;
}
return result ? 0 : 1;
}
<|endoftext|> |
<commit_before>//===-- PluginLoader.cpp - Implement -load command line option ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the -load <plugin> command line option handler.
//
//===----------------------------------------------------------------------===//
#define DONT_GET_PLUGIN_LOADER_OPTION
#include "llvm/Support/PluginLoader.h"
#include "llvm/System/DynamicLibrary.h"
#include <iostream>
#include <vector>
using namespace llvm;
static std::vector<std::string>* plugins;
void PluginLoader::operator=(const std::string &Filename) {
std::string ErrorMessage;
if (!plugins)
plugins = new std::vector<std::string>();
try {
sys::DynamicLibrary::LoadLibraryPermanently(Filename.c_str());
plugins->push_back(Filename);
} catch (const std::string& errmsg) {
if (errmsg.empty()) {
ErrorMessage = "Unknown";
} else {
ErrorMessage = errmsg;
}
}
if (!ErrorMessage.empty())
std::cerr << "Error opening '" << Filename << "': " << ErrorMessage
<< "\n -load request ignored.\n";
}
unsigned PluginLoader::getNumPlugins()
{
if(plugins)
return plugins->size();
else
return 0;
}
std::string& PluginLoader::getPlugin(unsigned num)
{
assert(plugins && num < plugins->size() && "Asking for an out of bounds plugin");
return (*plugins)[num];
}
<commit_msg>LoadLibraryPermanently no longer throws an exception, so this code doesn't have to catch it. Other minor cleanups.<commit_after>//===-- PluginLoader.cpp - Implement -load command line option ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the -load <plugin> command line option handler.
//
//===----------------------------------------------------------------------===//
#define DONT_GET_PLUGIN_LOADER_OPTION
#include "llvm/Support/PluginLoader.h"
#include "llvm/System/DynamicLibrary.h"
#include <iostream>
#include <vector>
using namespace llvm;
static std::vector<std::string> *Plugins;
void PluginLoader::operator=(const std::string &Filename) {
if (!Plugins)
Plugins = new std::vector<std::string>();
std::string Error;
if (sys::DynamicLibrary::LoadLibraryPermanently(Filename.c_str(), &Error)) {
std::cerr << "Error opening '" << Filename << "': " << Error
<< "\n -load request ignored.\n";
} else {
Plugins->push_back(Filename);
}
}
unsigned PluginLoader::getNumPlugins() {
return Plugins ? Plugins->size() : 0;
}
std::string &PluginLoader::getPlugin(unsigned num) {
assert(Plugins && num < Plugins->size() && "Asking for an out of bounds plugin");
return (*Plugins)[num];
}
<|endoftext|> |
<commit_before>//===-- TargetAsmInfo.cpp - Asm Info ---------------------------------------==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines target asm properties related what form asm statements
// should take.
//
//===----------------------------------------------------------------------===//
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Function.h"
#include "llvm/Module.h"
#include "llvm/Type.h"
#include "llvm/Target/TargetAsmInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/ErrorHandling.h"
#include <cctype>
#include <cstring>
using namespace llvm;
TargetAsmInfo::TargetAsmInfo(const TargetMachine &tm)
: TM(tm)
{
BSSSection = "\t.bss";
BSSSection_ = 0;
ReadOnlySection = 0;
TLSDataSection = 0;
TLSBSSSection = 0;
ZeroFillDirective = 0;
NonexecutableStackDirective = 0;
NeedsSet = false;
MaxInstLength = 4;
PCSymbol = "$";
SeparatorChar = ';';
CommentColumn = 60;
CommentString = "#";
FirstOperandColumn = 0;
MaxOperandLength = 0;
GlobalPrefix = "";
PrivateGlobalPrefix = ".";
LinkerPrivateGlobalPrefix = "";
JumpTableSpecialLabelPrefix = 0;
GlobalVarAddrPrefix = "";
GlobalVarAddrSuffix = "";
FunctionAddrPrefix = "";
FunctionAddrSuffix = "";
PersonalityPrefix = "";
PersonalitySuffix = "";
NeedsIndirectEncoding = false;
InlineAsmStart = "#APP";
InlineAsmEnd = "#NO_APP";
AssemblerDialect = 0;
AllowQuotesInName = false;
ZeroDirective = "\t.zero\t";
ZeroDirectiveSuffix = 0;
AsciiDirective = "\t.ascii\t";
AscizDirective = "\t.asciz\t";
Data8bitsDirective = "\t.byte\t";
Data16bitsDirective = "\t.short\t";
Data32bitsDirective = "\t.long\t";
Data64bitsDirective = "\t.quad\t";
AlignDirective = "\t.align\t";
AlignmentIsInBytes = true;
TextAlignFillValue = 0;
SwitchToSectionDirective = "\t.section\t";
TextSectionStartSuffix = "";
DataSectionStartSuffix = "";
SectionEndDirectiveSuffix = 0;
ConstantPoolSection = "\t.section .rodata";
JumpTableDataSection = "\t.section .rodata";
JumpTableDirective = 0;
CStringSection = 0;
CStringSection_ = 0;
// FIXME: Flags are ELFish - replace with normal section stuff.
StaticCtorsSection = "\t.section .ctors,\"aw\",@progbits";
StaticDtorsSection = "\t.section .dtors,\"aw\",@progbits";
GlobalDirective = "\t.globl\t";
SetDirective = 0;
LCOMMDirective = 0;
COMMDirective = "\t.comm\t";
COMMDirectiveTakesAlignment = true;
HasDotTypeDotSizeDirective = true;
HasSingleParameterDotFile = true;
UsedDirective = 0;
WeakRefDirective = 0;
WeakDefDirective = 0;
// FIXME: These are ELFish - move to ELFTAI.
HiddenDirective = "\t.hidden\t";
ProtectedDirective = "\t.protected\t";
AbsoluteDebugSectionOffsets = false;
AbsoluteEHSectionOffsets = false;
HasLEB128 = false;
HasDotLocAndDotFile = false;
SupportsDebugInformation = false;
SupportsExceptionHandling = false;
DwarfRequiresFrameSection = true;
DwarfUsesInlineInfoSection = false;
Is_EHSymbolPrivate = true;
GlobalEHDirective = 0;
SupportsWeakOmittedEHFrame = true;
DwarfSectionOffsetDirective = 0;
DwarfAbbrevSection = ".debug_abbrev";
DwarfInfoSection = ".debug_info";
DwarfLineSection = ".debug_line";
DwarfFrameSection = ".debug_frame";
DwarfPubNamesSection = ".debug_pubnames";
DwarfPubTypesSection = ".debug_pubtypes";
DwarfDebugInlineSection = ".debug_inlined";
DwarfStrSection = ".debug_str";
DwarfLocSection = ".debug_loc";
DwarfARangesSection = ".debug_aranges";
DwarfRangesSection = ".debug_ranges";
DwarfMacroInfoSection = ".debug_macinfo";
DwarfEHFrameSection = ".eh_frame";
DwarfExceptionSection = ".gcc_except_table";
AsmTransCBE = 0;
TextSection = getUnnamedSection("\t.text", SectionFlags::Code);
DataSection = getUnnamedSection("\t.data", SectionFlags::Writeable);
}
TargetAsmInfo::~TargetAsmInfo() {
}
/// Measure the specified inline asm to determine an approximation of its
/// length.
/// Comments (which run till the next SeparatorChar or newline) do not
/// count as an instruction.
/// Any other non-whitespace text is considered an instruction, with
/// multiple instructions separated by SeparatorChar or newlines.
/// Variable-length instructions are not handled here; this function
/// may be overloaded in the target code to do that.
unsigned TargetAsmInfo::getInlineAsmLength(const char *Str) const {
// Count the number of instructions in the asm.
bool atInsnStart = true;
unsigned Length = 0;
for (; *Str; ++Str) {
if (*Str == '\n' || *Str == SeparatorChar)
atInsnStart = true;
if (atInsnStart && !isspace(*Str)) {
Length += MaxInstLength;
atInsnStart = false;
}
if (atInsnStart && strncmp(Str, CommentString, strlen(CommentString))==0)
atInsnStart = false;
}
return Length;
}
unsigned TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason,
bool Global) const {
return dwarf::DW_EH_PE_absptr;
}
static bool isSuitableForBSS(const GlobalVariable *GV) {
if (!GV->hasInitializer())
return true;
// Leave constant zeros in readonly constant sections, so they can be shared
Constant *C = GV->getInitializer();
return (C->isNullValue() && !GV->isConstant() && !NoZerosInBSS);
}
static bool isConstantString(const Constant *C) {
// First check: is we have constant array of i8 terminated with zero
const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
// Check, if initializer is a null-terminated string
if (CVA && CVA->isCString())
return true;
// Another possibility: [1 x i8] zeroinitializer
if (isa<ConstantAggregateZero>(C)) {
if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType())) {
return (Ty->getElementType() == Type::Int8Ty &&
Ty->getNumElements() == 1);
}
}
return false;
}
SectionKind::Kind
TargetAsmInfo::SectionKindForGlobal(const GlobalValue *GV) const {
// Early exit - functions should be always in text sections.
if (isa<Function>(GV))
return SectionKind::Text;
const GlobalVariable* GVar = dyn_cast<GlobalVariable>(GV);
bool isThreadLocal = GVar->isThreadLocal();
assert(GVar && "Invalid global value for section selection");
if (isSuitableForBSS(GVar)) {
// Variable can be easily put to BSS section.
return isThreadLocal ? SectionKind::ThreadBSS : SectionKind::BSS;
} else if (GVar->isConstant() && !isThreadLocal) {
// Now we know, that variable has initializer and it is constant. We need to
// check its initializer to decide, which section to output it into. Also
// note, there is no thread-local r/o section.
Constant *C = GVar->getInitializer();
if (C->getRelocationInfo() != 0) {
// Decide whether it is still possible to put symbol into r/o section.
if (TM.getRelocationModel() != Reloc::Static)
return SectionKind::Data;
else
return SectionKind::ROData;
} else {
// Check, if initializer is a null-terminated string
if (isConstantString(C))
return SectionKind::RODataMergeStr;
else
return SectionKind::RODataMergeConst;
}
}
// Variable either is not constant or thread-local - output to data section.
return isThreadLocal ? SectionKind::ThreadData : SectionKind::Data;
}
unsigned
TargetAsmInfo::SectionFlagsForGlobal(const GlobalValue *GV,
const char* Name) const {
unsigned Flags = SectionFlags::None;
// Decode flags from global itself.
if (GV) {
SectionKind::Kind Kind = SectionKindForGlobal(GV);
switch (Kind) {
case SectionKind::Text:
Flags |= SectionFlags::Code;
break;
case SectionKind::ThreadData:
case SectionKind::ThreadBSS:
Flags |= SectionFlags::TLS;
// FALLS THROUGH
case SectionKind::Data:
case SectionKind::DataRel:
case SectionKind::DataRelLocal:
case SectionKind::DataRelRO:
case SectionKind::DataRelROLocal:
case SectionKind::BSS:
Flags |= SectionFlags::Writeable;
break;
case SectionKind::ROData:
case SectionKind::RODataMergeStr:
case SectionKind::RODataMergeConst:
// No additional flags here
break;
default:
llvm_unreachable("Unexpected section kind!");
}
if (GV->isWeakForLinker())
Flags |= SectionFlags::Linkonce;
}
// Add flags from sections, if any.
if (Name && *Name) {
Flags |= SectionFlags::Named;
// Some lame default implementation based on some magic section names.
if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
Flags |= SectionFlags::BSS;
else if (strcmp(Name, ".tdata") == 0 ||
strncmp(Name, ".tdata.", 7) == 0 ||
strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
Flags |= SectionFlags::TLS;
else if (strcmp(Name, ".tbss") == 0 ||
strncmp(Name, ".tbss.", 6) == 0 ||
strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
Flags |= SectionFlags::BSS | SectionFlags::TLS;
}
return Flags;
}
const Section *TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const {
// Select section name
if (GV->hasSection()) {
// Honour section already set, if any.
unsigned Flags = SectionFlagsForGlobal(GV, GV->getSection().c_str());
return getNamedSection(GV->getSection().c_str(), Flags);
}
// If this global is linkonce/weak and the target handles this by emitting it
// into a 'uniqued' section name, create and return the section now.
if (GV->isWeakForLinker()) {
if (const char *Prefix =
getSectionPrefixForUniqueGlobal(SectionKindForGlobal(GV))) {
// FIXME: Use mangler interface (PR4584).
std::string Name = Prefix+GV->getNameStr();
unsigned Flags = SectionFlagsForGlobal(GV, Name.c_str());
return getNamedSection(Name.c_str(), Flags);
}
}
// Use default section depending on the 'type' of global
return SelectSectionForGlobal(GV);
}
// Lame default implementation. Calculate the section name for global.
const Section*
TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const {
SectionKind::Kind Kind = SectionKindForGlobal(GV);
if (Kind == SectionKind::Text)
return getTextSection();
if (isBSS(Kind))
if (const Section *S = getBSSSection_())
return S;
if (SectionKind::isReadOnly(Kind))
if (const Section *S = getReadOnlySection())
return S;
return getDataSection();
}
/// getSectionForMergableConstant - Given a mergable constant with the
/// specified size and relocation information, return a section that it
/// should be placed in.
const Section *
TargetAsmInfo::getSectionForMergableConstant(uint64_t Size,
unsigned ReloInfo) const {
// FIXME: Support data.rel stuff someday
// Lame default implementation. Calculate the section name for machine const.
return getDataSection();
}
const char *
TargetAsmInfo::getSectionPrefixForUniqueGlobal(SectionKind::Kind Kind) const {
switch (Kind) {
default: llvm_unreachable("Unknown section kind");
case SectionKind::Text: return ".gnu.linkonce.t.";
case SectionKind::Data: return ".gnu.linkonce.d.";
case SectionKind::DataRel: return ".gnu.linkonce.d.rel.";
case SectionKind::DataRelLocal: return ".gnu.linkonce.d.rel.local.";
case SectionKind::DataRelRO: return ".gnu.linkonce.d.rel.ro.";
case SectionKind::DataRelROLocal: return ".gnu.linkonce.d.rel.ro.local.";
case SectionKind::BSS: return ".gnu.linkonce.b.";
case SectionKind::ROData:
case SectionKind::RODataMergeConst:
case SectionKind::RODataMergeStr: return ".gnu.linkonce.r.";
case SectionKind::ThreadData: return ".gnu.linkonce.td.";
case SectionKind::ThreadBSS: return ".gnu.linkonce.tb.";
}
}
const Section *TargetAsmInfo::getNamedSection(const char *Name, unsigned Flags,
bool Override) const {
Section &S = Sections[Name];
// This is newly-created section, set it up properly.
if (S.Flags == SectionFlags::Invalid || Override) {
S.Flags = Flags | SectionFlags::Named;
S.Name = Name;
}
return &S;
}
const Section*
TargetAsmInfo::getUnnamedSection(const char *Directive, unsigned Flags,
bool Override) const {
Section& S = Sections[Directive];
// This is newly-created section, set it up properly.
if (S.Flags == SectionFlags::Invalid || Override) {
S.Flags = Flags & ~SectionFlags::Named;
S.Name = Directive;
}
return &S;
}
const std::string&
TargetAsmInfo::getSectionFlags(unsigned Flags) const {
SectionFlags::FlagsStringsMapType::iterator I = FlagsStrings.find(Flags);
// We didn't print these flags yet, print and save them to map. This reduces
// amount of heap trashing due to std::string construction / concatenation.
if (I == FlagsStrings.end())
I = FlagsStrings.insert(std::make_pair(Flags,
printSectionFlags(Flags))).first;
return I->second;
}
unsigned TargetAsmInfo::getULEB128Size(unsigned Value) {
unsigned Size = 0;
do {
Value >>= 7;
Size += sizeof(int8_t);
} while (Value);
return Size;
}
unsigned TargetAsmInfo::getSLEB128Size(int Value) {
unsigned Size = 0;
int Sign = Value >> (8 * sizeof(Value) - 1);
bool IsMore;
do {
unsigned Byte = Value & 0x7f;
Value >>= 7;
IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
Size += sizeof(int8_t);
} while (IsMore);
return Size;
}
<commit_msg>There is no need to pass the name into lib/Target/TargetAsmInfo.cpp when we have a global with no section explicitly specified.<commit_after>//===-- TargetAsmInfo.cpp - Asm Info ---------------------------------------==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines target asm properties related what form asm statements
// should take.
//
//===----------------------------------------------------------------------===//
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Function.h"
#include "llvm/Module.h"
#include "llvm/Type.h"
#include "llvm/Target/TargetAsmInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/ErrorHandling.h"
#include <cctype>
#include <cstring>
using namespace llvm;
TargetAsmInfo::TargetAsmInfo(const TargetMachine &tm)
: TM(tm)
{
BSSSection = "\t.bss";
BSSSection_ = 0;
ReadOnlySection = 0;
TLSDataSection = 0;
TLSBSSSection = 0;
ZeroFillDirective = 0;
NonexecutableStackDirective = 0;
NeedsSet = false;
MaxInstLength = 4;
PCSymbol = "$";
SeparatorChar = ';';
CommentColumn = 60;
CommentString = "#";
FirstOperandColumn = 0;
MaxOperandLength = 0;
GlobalPrefix = "";
PrivateGlobalPrefix = ".";
LinkerPrivateGlobalPrefix = "";
JumpTableSpecialLabelPrefix = 0;
GlobalVarAddrPrefix = "";
GlobalVarAddrSuffix = "";
FunctionAddrPrefix = "";
FunctionAddrSuffix = "";
PersonalityPrefix = "";
PersonalitySuffix = "";
NeedsIndirectEncoding = false;
InlineAsmStart = "#APP";
InlineAsmEnd = "#NO_APP";
AssemblerDialect = 0;
AllowQuotesInName = false;
ZeroDirective = "\t.zero\t";
ZeroDirectiveSuffix = 0;
AsciiDirective = "\t.ascii\t";
AscizDirective = "\t.asciz\t";
Data8bitsDirective = "\t.byte\t";
Data16bitsDirective = "\t.short\t";
Data32bitsDirective = "\t.long\t";
Data64bitsDirective = "\t.quad\t";
AlignDirective = "\t.align\t";
AlignmentIsInBytes = true;
TextAlignFillValue = 0;
SwitchToSectionDirective = "\t.section\t";
TextSectionStartSuffix = "";
DataSectionStartSuffix = "";
SectionEndDirectiveSuffix = 0;
ConstantPoolSection = "\t.section .rodata";
JumpTableDataSection = "\t.section .rodata";
JumpTableDirective = 0;
CStringSection = 0;
CStringSection_ = 0;
// FIXME: Flags are ELFish - replace with normal section stuff.
StaticCtorsSection = "\t.section .ctors,\"aw\",@progbits";
StaticDtorsSection = "\t.section .dtors,\"aw\",@progbits";
GlobalDirective = "\t.globl\t";
SetDirective = 0;
LCOMMDirective = 0;
COMMDirective = "\t.comm\t";
COMMDirectiveTakesAlignment = true;
HasDotTypeDotSizeDirective = true;
HasSingleParameterDotFile = true;
UsedDirective = 0;
WeakRefDirective = 0;
WeakDefDirective = 0;
// FIXME: These are ELFish - move to ELFTAI.
HiddenDirective = "\t.hidden\t";
ProtectedDirective = "\t.protected\t";
AbsoluteDebugSectionOffsets = false;
AbsoluteEHSectionOffsets = false;
HasLEB128 = false;
HasDotLocAndDotFile = false;
SupportsDebugInformation = false;
SupportsExceptionHandling = false;
DwarfRequiresFrameSection = true;
DwarfUsesInlineInfoSection = false;
Is_EHSymbolPrivate = true;
GlobalEHDirective = 0;
SupportsWeakOmittedEHFrame = true;
DwarfSectionOffsetDirective = 0;
DwarfAbbrevSection = ".debug_abbrev";
DwarfInfoSection = ".debug_info";
DwarfLineSection = ".debug_line";
DwarfFrameSection = ".debug_frame";
DwarfPubNamesSection = ".debug_pubnames";
DwarfPubTypesSection = ".debug_pubtypes";
DwarfDebugInlineSection = ".debug_inlined";
DwarfStrSection = ".debug_str";
DwarfLocSection = ".debug_loc";
DwarfARangesSection = ".debug_aranges";
DwarfRangesSection = ".debug_ranges";
DwarfMacroInfoSection = ".debug_macinfo";
DwarfEHFrameSection = ".eh_frame";
DwarfExceptionSection = ".gcc_except_table";
AsmTransCBE = 0;
TextSection = getUnnamedSection("\t.text", SectionFlags::Code);
DataSection = getUnnamedSection("\t.data", SectionFlags::Writeable);
}
TargetAsmInfo::~TargetAsmInfo() {
}
/// Measure the specified inline asm to determine an approximation of its
/// length.
/// Comments (which run till the next SeparatorChar or newline) do not
/// count as an instruction.
/// Any other non-whitespace text is considered an instruction, with
/// multiple instructions separated by SeparatorChar or newlines.
/// Variable-length instructions are not handled here; this function
/// may be overloaded in the target code to do that.
unsigned TargetAsmInfo::getInlineAsmLength(const char *Str) const {
// Count the number of instructions in the asm.
bool atInsnStart = true;
unsigned Length = 0;
for (; *Str; ++Str) {
if (*Str == '\n' || *Str == SeparatorChar)
atInsnStart = true;
if (atInsnStart && !isspace(*Str)) {
Length += MaxInstLength;
atInsnStart = false;
}
if (atInsnStart && strncmp(Str, CommentString, strlen(CommentString))==0)
atInsnStart = false;
}
return Length;
}
unsigned TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason,
bool Global) const {
return dwarf::DW_EH_PE_absptr;
}
static bool isSuitableForBSS(const GlobalVariable *GV) {
if (!GV->hasInitializer())
return true;
// Leave constant zeros in readonly constant sections, so they can be shared
Constant *C = GV->getInitializer();
return (C->isNullValue() && !GV->isConstant() && !NoZerosInBSS);
}
static bool isConstantString(const Constant *C) {
// First check: is we have constant array of i8 terminated with zero
const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
// Check, if initializer is a null-terminated string
if (CVA && CVA->isCString())
return true;
// Another possibility: [1 x i8] zeroinitializer
if (isa<ConstantAggregateZero>(C)) {
if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType())) {
return (Ty->getElementType() == Type::Int8Ty &&
Ty->getNumElements() == 1);
}
}
return false;
}
SectionKind::Kind
TargetAsmInfo::SectionKindForGlobal(const GlobalValue *GV) const {
// Early exit - functions should be always in text sections.
if (isa<Function>(GV))
return SectionKind::Text;
const GlobalVariable* GVar = dyn_cast<GlobalVariable>(GV);
bool isThreadLocal = GVar->isThreadLocal();
assert(GVar && "Invalid global value for section selection");
if (isSuitableForBSS(GVar)) {
// Variable can be easily put to BSS section.
return isThreadLocal ? SectionKind::ThreadBSS : SectionKind::BSS;
} else if (GVar->isConstant() && !isThreadLocal) {
// Now we know, that variable has initializer and it is constant. We need to
// check its initializer to decide, which section to output it into. Also
// note, there is no thread-local r/o section.
Constant *C = GVar->getInitializer();
if (C->getRelocationInfo() != 0) {
// Decide whether it is still possible to put symbol into r/o section.
if (TM.getRelocationModel() != Reloc::Static)
return SectionKind::Data;
else
return SectionKind::ROData;
} else {
// Check, if initializer is a null-terminated string
if (isConstantString(C))
return SectionKind::RODataMergeStr;
else
return SectionKind::RODataMergeConst;
}
}
// Variable either is not constant or thread-local - output to data section.
return isThreadLocal ? SectionKind::ThreadData : SectionKind::Data;
}
unsigned
TargetAsmInfo::SectionFlagsForGlobal(const GlobalValue *GV,
const char* Name) const {
unsigned Flags = SectionFlags::None;
// Decode flags from global itself.
if (GV) {
SectionKind::Kind Kind = SectionKindForGlobal(GV);
switch (Kind) {
case SectionKind::Text:
Flags |= SectionFlags::Code;
break;
case SectionKind::ThreadData:
case SectionKind::ThreadBSS:
Flags |= SectionFlags::TLS;
// FALLS THROUGH
case SectionKind::Data:
case SectionKind::DataRel:
case SectionKind::DataRelLocal:
case SectionKind::DataRelRO:
case SectionKind::DataRelROLocal:
case SectionKind::BSS:
Flags |= SectionFlags::Writeable;
break;
case SectionKind::ROData:
case SectionKind::RODataMergeStr:
case SectionKind::RODataMergeConst:
// No additional flags here
break;
default:
llvm_unreachable("Unexpected section kind!");
}
if (GV->isWeakForLinker())
Flags |= SectionFlags::Linkonce;
}
// Add flags from sections, if any.
if (Name && *Name) {
Flags |= SectionFlags::Named;
// Some lame default implementation based on some magic section names.
if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
Flags |= SectionFlags::BSS;
else if (strcmp(Name, ".tdata") == 0 ||
strncmp(Name, ".tdata.", 7) == 0 ||
strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
Flags |= SectionFlags::TLS;
else if (strcmp(Name, ".tbss") == 0 ||
strncmp(Name, ".tbss.", 6) == 0 ||
strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
Flags |= SectionFlags::BSS | SectionFlags::TLS;
}
return Flags;
}
const Section *TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const {
// Select section name
if (GV->hasSection()) {
// Honour section already set, if any.
unsigned Flags = SectionFlagsForGlobal(GV, GV->getSection().c_str());
return getNamedSection(GV->getSection().c_str(), Flags);
}
// If this global is linkonce/weak and the target handles this by emitting it
// into a 'uniqued' section name, create and return the section now.
if (GV->isWeakForLinker()) {
if (const char *Prefix =
getSectionPrefixForUniqueGlobal(SectionKindForGlobal(GV))) {
// FIXME: Use mangler interface (PR4584).
std::string Name = Prefix+GV->getNameStr();
unsigned Flags = SectionFlagsForGlobal(GV);
return getNamedSection(Name.c_str(), Flags);
}
}
// Use default section depending on the 'type' of global
return SelectSectionForGlobal(GV);
}
// Lame default implementation. Calculate the section name for global.
const Section*
TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const {
SectionKind::Kind Kind = SectionKindForGlobal(GV);
if (Kind == SectionKind::Text)
return getTextSection();
if (isBSS(Kind))
if (const Section *S = getBSSSection_())
return S;
if (SectionKind::isReadOnly(Kind))
if (const Section *S = getReadOnlySection())
return S;
return getDataSection();
}
/// getSectionForMergableConstant - Given a mergable constant with the
/// specified size and relocation information, return a section that it
/// should be placed in.
const Section *
TargetAsmInfo::getSectionForMergableConstant(uint64_t Size,
unsigned ReloInfo) const {
// FIXME: Support data.rel stuff someday
// Lame default implementation. Calculate the section name for machine const.
return getDataSection();
}
const char *
TargetAsmInfo::getSectionPrefixForUniqueGlobal(SectionKind::Kind Kind) const {
switch (Kind) {
default: llvm_unreachable("Unknown section kind");
case SectionKind::Text: return ".gnu.linkonce.t.";
case SectionKind::Data: return ".gnu.linkonce.d.";
case SectionKind::DataRel: return ".gnu.linkonce.d.rel.";
case SectionKind::DataRelLocal: return ".gnu.linkonce.d.rel.local.";
case SectionKind::DataRelRO: return ".gnu.linkonce.d.rel.ro.";
case SectionKind::DataRelROLocal: return ".gnu.linkonce.d.rel.ro.local.";
case SectionKind::BSS: return ".gnu.linkonce.b.";
case SectionKind::ROData:
case SectionKind::RODataMergeConst:
case SectionKind::RODataMergeStr: return ".gnu.linkonce.r.";
case SectionKind::ThreadData: return ".gnu.linkonce.td.";
case SectionKind::ThreadBSS: return ".gnu.linkonce.tb.";
}
}
const Section *TargetAsmInfo::getNamedSection(const char *Name, unsigned Flags,
bool Override) const {
Section &S = Sections[Name];
// This is newly-created section, set it up properly.
if (S.Flags == SectionFlags::Invalid || Override) {
S.Flags = Flags | SectionFlags::Named;
S.Name = Name;
}
return &S;
}
const Section*
TargetAsmInfo::getUnnamedSection(const char *Directive, unsigned Flags,
bool Override) const {
Section& S = Sections[Directive];
// This is newly-created section, set it up properly.
if (S.Flags == SectionFlags::Invalid || Override) {
S.Flags = Flags & ~SectionFlags::Named;
S.Name = Directive;
}
return &S;
}
const std::string&
TargetAsmInfo::getSectionFlags(unsigned Flags) const {
SectionFlags::FlagsStringsMapType::iterator I = FlagsStrings.find(Flags);
// We didn't print these flags yet, print and save them to map. This reduces
// amount of heap trashing due to std::string construction / concatenation.
if (I == FlagsStrings.end())
I = FlagsStrings.insert(std::make_pair(Flags,
printSectionFlags(Flags))).first;
return I->second;
}
unsigned TargetAsmInfo::getULEB128Size(unsigned Value) {
unsigned Size = 0;
do {
Value >>= 7;
Size += sizeof(int8_t);
} while (Value);
return Size;
}
unsigned TargetAsmInfo::getSLEB128Size(int Value) {
unsigned Size = 0;
int Sign = Value >> (8 * sizeof(Value) - 1);
bool IsMore;
do {
unsigned Byte = Value & 0x7f;
Value >>= 7;
IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
Size += sizeof(int8_t);
} while (IsMore);
return Size;
}
<|endoftext|> |
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
*
* Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/graphics.hpp"
#include "guichan/exception.hpp"
#include "guichan/font.hpp"
#include "guichan/image.hpp"
namespace gcn
{
Graphics::Graphics()
{
mFont = NULL;
}
bool Graphics::pushClipArea(Rectangle area)
{
if (mClipStack.empty())
{
ClipRectangle carea;
carea.x = area.x;
carea.y = area.y;
carea.width = area.width;
carea.height = area.height;
mClipStack.push(carea);
return true;
}
ClipRectangle top = mClipStack.top();
ClipRectangle carea;
carea = area;
carea.xOffset = top.xOffset + carea.x;
carea.yOffset = top.yOffset + carea.y;
carea.x += top.xOffset;
carea.y += top.yOffset;
// Clamp the pushed clip rectangle.
if (carea.x < top.x)
{
carea.x = top.x;
}
if (carea.y < top.y)
{
carea.y = top.y;
}
if (carea.width > top.width)
{
carea.width = top.width;
}
if (carea.height > top.height)
{
carea.height = top.height;
}
bool result = carea.intersect(top);
mClipStack.push(carea);
return result;
}
void Graphics::popClipArea()
{
if (mClipStack.empty())
{
throw GCN_EXCEPTION("Tried to pop clip area from empty stack.");
}
mClipStack.pop();
}
const ClipRectangle& Graphics::getCurrentClipArea()
{
if (mClipStack.empty())
{
throw GCN_EXCEPTION("The clip area stack is empty.");
}
return mClipStack.top();
}
void Graphics::drawImage(const Image* image, int dstX, int dstY)
{
drawImage(image, 0, 0, dstX, dstY, image->getWidth(), image->getHeight());
}
void Graphics::setFont(Font* font)
{
mFont = font;
}
void Graphics::drawText(const std::string& text, int x, int y,
Alignment alignment)
{
if (mFont == NULL)
{
throw GCN_EXCEPTION("No font set.");
}
switch (alignment)
{
case LEFT:
mFont->drawString(this, text, x, y);
break;
case CENTER:
mFont->drawString(this, text, x - mFont->getWidth(text) / 2, y);
break;
case RIGHT:
mFont->drawString(this, text, x - mFont->getWidth(text), y);
break;
default:
throw GCN_EXCEPTION("Unknown alignment.");
}
}
}
<commit_msg>A fix has been applied to correctly clamp a pushed clip area to the top clip area. <commit_after>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
*
* Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/graphics.hpp"
#include "guichan/exception.hpp"
#include "guichan/font.hpp"
#include "guichan/image.hpp"
namespace gcn
{
Graphics::Graphics()
{
mFont = NULL;
}
bool Graphics::pushClipArea(Rectangle area)
{
if (mClipStack.empty())
{
ClipRectangle carea;
carea.x = area.x;
carea.y = area.y;
carea.width = area.width;
carea.height = area.height;
mClipStack.push(carea);
return true;
}
ClipRectangle top = mClipStack.top();
ClipRectangle carea;
carea = area;
carea.xOffset = top.xOffset + carea.x;
carea.yOffset = top.yOffset + carea.y;
carea.x += top.xOffset;
carea.y += top.yOffset;
// Clamp the pushed clip rectangle.
if (carea.x < top.x)
{
carea.width += carea.x - top.x;
carea.x = top.x;
}
if (carea.y < top.y)
{
carea.height += carea.y - top.y;
carea.y = top.y;
}
if (carea.width > top.width)
{
carea.width = top.width;
}
if (carea.height > top.height)
{
carea.height = top.height;
}
bool result = carea.intersect(top);
mClipStack.push(carea);
return result;
}
void Graphics::popClipArea()
{
if (mClipStack.empty())
{
throw GCN_EXCEPTION("Tried to pop clip area from empty stack.");
}
mClipStack.pop();
}
const ClipRectangle& Graphics::getCurrentClipArea()
{
if (mClipStack.empty())
{
throw GCN_EXCEPTION("The clip area stack is empty.");
}
return mClipStack.top();
}
void Graphics::drawImage(const Image* image, int dstX, int dstY)
{
drawImage(image, 0, 0, dstX, dstY, image->getWidth(), image->getHeight());
}
void Graphics::setFont(Font* font)
{
mFont = font;
}
void Graphics::drawText(const std::string& text, int x, int y,
Alignment alignment)
{
if (mFont == NULL)
{
throw GCN_EXCEPTION("No font set.");
}
switch (alignment)
{
case LEFT:
mFont->drawString(this, text, x, y);
break;
case CENTER:
mFont->drawString(this, text, x - mFont->getWidth(text) / 2, y);
break;
case RIGHT:
mFont->drawString(this, text, x - mFont->getWidth(text), y);
break;
default:
throw GCN_EXCEPTION("Unknown alignment.");
}
}
}
<|endoftext|> |
<commit_before>#include <QApplication>
#include <QFontDatabase>
#include <QtGlobal>
#include <QFile>
#include <QCommandLineParser>
#include "neovimconnector.h"
#include "mainwindow.h"
/**
* A log handler for Qt messages, all messages are dumped into the file
* passed via the NVIM_QT_LOG variable. Some information is only available
* in debug builds (e.g. qDebug is only called in debug builds).
*
* In UNIX Qt prints messages to the console output, but in Windows this is
* the only way to get Qt's debug/warning messages.
*/
void logger(QtMsgType type, const QMessageLogContext& ctx, const QString& msg)
{
QFile logFile(qgetenv("NVIM_QT_LOG"));
if (logFile.open(QIODevice::Append | QIODevice::Text)) {
QTextStream stream(&logFile);
stream << msg << "\n";
}
}
/**
* Neovim Qt GUI
*
* Usage:
* nvim-qt --server <SOCKET>
* nvim-qt [...]
*
* When --server is not provided, a Neovim instance will be spawned. All arguments
* are passed to the Neovim process.
*/
int main(int argc, char **argv)
{
QApplication app(argc, argv);
app.setApplicationDisplayName("Neovim");
app.setWindowIcon(QIcon(":/neovim.png"));
if (!qgetenv("NVIM_QT_LOG").isEmpty()) {
qInstallMessageHandler(logger);
}
QCommandLineParser parser;
parser.addOption(QCommandLineOption("embed",
QCoreApplication::translate("main", "Communicate with Neovim over stdin/out")));
parser.addOption(QCommandLineOption("server",
QCoreApplication::translate("main", "Connect to existing Neovim instance"),
QCoreApplication::translate("main", "addr")));
parser.addOption(QCommandLineOption("geometry",
QCoreApplication::translate("main", "Initial window geometry"),
QCoreApplication::translate("main", "geometry")));
parser.addOption(QCommandLineOption("maximized",
QCoreApplication::translate("main", "Maximize the window on startup")));
parser.addOption(QCommandLineOption("fullscreen",
QCoreApplication::translate("main", "Open the window in fullscreen on startup")));
parser.addPositionalArgument("...", "Additional arguments are fowarded to Neovim", "[-- ...]");
parser.addHelpOption();
int sep = app.arguments().indexOf("--");
QStringList neovimArgs;
if (sep != -1) {
QStringList args = app.arguments().mid(0, sep);
neovimArgs += app.arguments().mid(sep+1);
parser.process(app.arguments());
} else {
parser.process(app.arguments());
}
if (parser.isSet("help")) {
parser.showHelp();
}
NeovimQt::NeovimConnector *c;
if (parser.isSet("embed")) {
c = NeovimQt::NeovimConnector::fromStdinOut();
} else {
if (parser.isSet("server")) {
QString server = parser.value("server");
c = NeovimQt::NeovimConnector::connectToNeovim(server);
} else {
c = NeovimQt::NeovimConnector::spawn(neovimArgs);
}
}
#ifdef NEOVIMQT_GUI_WIDGET
NeovimQt::Shell *win = new NeovimQt::Shell(c);
win->show();
if (parser.isSet("fullscreen")) {
win->showFullScreen();
} else if (parser.isSet("maximized")) {
win->showMaximized();
} else {
win->show();
}
#else
NeovimQt::MainWindow *win = new NeovimQt::MainWindow(c);
if (parser.isSet("fullscreen")) {
win->delayedShow(NeovimQt::MainWindow::DelayedShow::FullScreen);
} else if (parser.isSet("maximized")) {
win->delayedShow(NeovimQt::MainWindow::DelayedShow::Maximized);
} else {
win->delayedShow();
}
#endif
return app.exec();
}
<commit_msg>Cleanup main.cpp<commit_after>#include <QApplication>
#include <QFontDatabase>
#include <QtGlobal>
#include <QFile>
#include <QCommandLineParser>
#include "neovimconnector.h"
#include "mainwindow.h"
/// A log handler for Qt messages, all messages are dumped into the file
/// passed via the NVIM_QT_LOG variable. Some information is only available
/// in debug builds (e.g. qDebug is only called in debug builds).
///
/// In UNIX Qt prints messages to the console output, but in Windows this is
/// the only way to get Qt's debug/warning messages.
void logger(QtMsgType type, const QMessageLogContext& ctx, const QString& msg)
{
QFile logFile(qgetenv("NVIM_QT_LOG"));
if (logFile.open(QIODevice::Append | QIODevice::Text)) {
QTextStream stream(&logFile);
stream << msg << "\n";
}
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
app.setApplicationDisplayName("Neovim");
app.setWindowIcon(QIcon(":/neovim.png"));
if (!qgetenv("NVIM_QT_LOG").isEmpty()) {
qInstallMessageHandler(logger);
}
QCommandLineParser parser;
parser.addOption(QCommandLineOption("embed",
QCoreApplication::translate("main", "Communicate with Neovim over stdin/out")));
parser.addOption(QCommandLineOption("server",
QCoreApplication::translate("main", "Connect to existing Neovim instance"),
QCoreApplication::translate("main", "addr")));
parser.addOption(QCommandLineOption("geometry",
QCoreApplication::translate("main", "Initial window geometry"),
QCoreApplication::translate("main", "geometry")));
parser.addOption(QCommandLineOption("maximized",
QCoreApplication::translate("main", "Maximize the window on startup")));
parser.addOption(QCommandLineOption("fullscreen",
QCoreApplication::translate("main", "Open the window in fullscreen on startup")));
parser.addPositionalArgument("...", "Additional arguments are fowarded to Neovim", "[-- ...]");
parser.addHelpOption();
int sep = app.arguments().indexOf("--");
QStringList neovimArgs;
if (sep != -1) {
QStringList args = app.arguments().mid(0, sep);
neovimArgs += app.arguments().mid(sep+1);
parser.process(app.arguments());
} else {
parser.process(app.arguments());
}
if (parser.isSet("help")) {
parser.showHelp();
}
NeovimQt::NeovimConnector *c;
if (parser.isSet("embed")) {
c = NeovimQt::NeovimConnector::fromStdinOut();
} else {
if (parser.isSet("server")) {
QString server = parser.value("server");
c = NeovimQt::NeovimConnector::connectToNeovim(server);
} else {
c = NeovimQt::NeovimConnector::spawn(neovimArgs);
}
}
#ifdef NEOVIMQT_GUI_WIDGET
NeovimQt::Shell *win = new NeovimQt::Shell(c);
win->show();
if (parser.isSet("fullscreen")) {
win->showFullScreen();
} else if (parser.isSet("maximized")) {
win->showMaximized();
} else {
win->show();
}
#else
NeovimQt::MainWindow *win = new NeovimQt::MainWindow(c);
if (parser.isSet("fullscreen")) {
win->delayedShow(NeovimQt::MainWindow::DelayedShow::FullScreen);
} else if (parser.isSet("maximized")) {
win->delayedShow(NeovimQt::MainWindow::DelayedShow::Maximized);
} else {
win->delayedShow();
}
#endif
return app.exec();
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2008, Avian Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
There is NO WARRANTY for this software. See license.txt for
details. */
#include "machine.h"
using namespace vm;
namespace {
const uintptr_t PointerShift = log(BytesPerWord);
class Set {
public:
class Entry {
public:
object value;
uint32_t number;
int next;
};
static unsigned footprint(unsigned capacity) {
return sizeof(Set)
+ pad(sizeof(int) * capacity)
+ pad(sizeof(Set::Entry) * capacity);
}
Set(unsigned capacity):
size(0),
capacity(capacity),
index(reinterpret_cast<int*>
(reinterpret_cast<uint8_t*>(this)
+ sizeof(Set))),
entries(reinterpret_cast<Entry*>
(reinterpret_cast<uint8_t*>(index)
+ pad(sizeof(int) * capacity)))
{ }
unsigned size;
unsigned capacity;
int* index;
Entry* entries;
};
class Stack {
public:
class Entry {
public:
object value;
int offset;
};
static const unsigned Capacity = 4096;
Stack(Stack* next): next(next), entryCount(0) { }
Stack* next;
unsigned entryCount;
Entry entries[Capacity];
};
class Context {
public:
Context(Thread* thread, FILE* out):
thread(thread), out(out), objects(0), stack(0), nextNumber(1)
{ }
~Context() {
if (objects) {
thread->m->heap->free(objects, Set::footprint(objects->capacity));
}
while (stack) {
Stack* dead = stack;
stack = dead->next;
thread->m->heap->free(stack, sizeof(Stack));
}
}
Thread* thread;
FILE* out;
Set* objects;
Stack* stack;
uint32_t nextNumber;
};
void
push(Context* c, object p, int offset)
{
if (c->stack == 0 or c->stack->entryCount == Stack::Capacity) {
c->stack = new (c->thread->m->heap->allocate(sizeof(Stack)))
Stack(c->stack);
}
Stack::Entry* e = c->stack->entries + (c->stack->entryCount++);
e->value = p;
e->offset = offset;
}
bool
pop(Context* c, object* p, int* offset)
{
if (c->stack) {
if (c->stack->entryCount == 0) {
if (c->stack->next) {
Stack* dead = c->stack;
c->stack = dead->next;
c->thread->m->heap->free(dead, sizeof(Stack));
} else {
return false;
}
}
Stack::Entry* e = c->stack->entries + (--c->stack->entryCount);
*p = e->value;
*offset = e->offset;
return true;
} else {
return false;
}
}
unsigned
hash(object p, unsigned capacity)
{
return (reinterpret_cast<uintptr_t>(p) >> PointerShift)
& (capacity - 1);
}
Set::Entry*
find(Context* c, object p)
{
if (c->objects == 0) return false;
for (int i = c->objects->index[hash(p, c->objects->capacity)]; i >= 0;) {
Set::Entry* e = c->objects->entries + i;
if (e->value == p) {
return e;
}
i = e->next;
}
return false;
}
Set::Entry*
add(Context* c UNUSED, Set* set, object p)
{
assert(c->thread, set->size < set->capacity);
unsigned index = hash(p, set->capacity);
int offset = set->size++;
Set::Entry* e = set->entries + offset;
e->value = p;
e->next = set->index[index];
set->index[index] = offset;
return e;
}
Set::Entry*
add(Context* c, object p)
{
if (c->objects == 0 or c->objects->size == c->objects->capacity) {
unsigned capacity;
if (c->objects) {
capacity = c->objects->capacity * 2;
} else {
capacity = 4096; // must be power of two
}
Set* set = new (c->thread->m->heap->allocate(Set::footprint(capacity)))
Set(capacity);
memset(set->index, 0xFF, sizeof(int) * capacity);
if (c->objects) {
for (unsigned i = 0; i < c->objects->capacity; ++i) {
for (int j = c->objects->index[i]; j >= 0;) {
Set::Entry* e = c->objects->entries + j;
add(c, set, e->value);
j = e->next;
}
}
c->thread->m->heap->free
(c->objects, Set::footprint(c->objects->capacity));
}
c->objects = set;
}
return add(c, c->objects, p);
}
enum {
Root,
ClassName,
Push,
LastChild,
Pop,
Size
};
inline object
get(object o, unsigned offsetInWords)
{
return static_cast<object>
(mask(cast<void*>(o, offsetInWords * BytesPerWord)));
}
void
write1(Context* c, uint8_t v)
{
fwrite(&v, 1, 1, c->out);
}
void
write4(Context* c, uint32_t v)
{
uint8_t b[] = { v >> 24, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF };
fwrite(b, 4, 1, c->out);
}
void
writeString(Context* c, int8_t* p, unsigned size)
{
write4(c, size);
fwrite(p, size, 1, c->out);
}
unsigned
objectSize(Thread* t, object o)
{
unsigned n = baseSize(t, o, objectClass(t, o));
if (objectExtended(t, o)) {
++ n;
}
return n;
}
void
visit(Context* c, object p)
{
Thread* t = c->thread;
int nextChildOffset;
write1(c, Root);
visit: {
Set::Entry* e = find(c, p);
if (e) {
write4(c, e->number);
} else {
e = add(c, p);
e->number = c->nextNumber++;
write4(c, e->number);
write1(c, Size);
write4(c, objectSize(t, p));
if (objectClass(t, p) == arrayBody(t, t->m->types, Machine::ClassType)) {
object name = className(t, p);
if (name) {
write1(c, ClassName);
writeString(c, &byteArrayBody(t, name, 0),
byteArrayLength(t, name) - 1);
}
}
nextChildOffset = walkNext(t, p, -1);
if (nextChildOffset != -1) {
goto children;
}
}
}
goto pop;
children: {
int next = walkNext(t, p, nextChildOffset);
if (next >= 0) {
write1(c, Push);
push(c, p, next);
} else {
write1(c, LastChild);
}
p = get(p, nextChildOffset);
goto visit;
}
pop: {
if (pop(c, &p, &nextChildOffset)) {
write1(c, Pop);
goto children;
}
}
}
} // namespace
namespace vm {
void
dumpHeap(Thread* t, FILE* out)
{
Context context(t, out);
class Visitor : public Heap::Visitor {
public:
Visitor(Context* c): c(c) { }
virtual void visit(void* p) {
::visit(c, static_cast<object>(mask(*static_cast<void**>(p))));
}
Context* c;
} v(&context);
add(&context, 0)->number = 0;
visitRoots(t, &v);
}
} // namespace vm
<commit_msg>heap dump bugfixes<commit_after>/* Copyright (c) 2008, Avian Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
There is NO WARRANTY for this software. See license.txt for
details. */
#include "machine.h"
using namespace vm;
namespace {
const uintptr_t PointerShift = log(BytesPerWord);
class Set {
public:
class Entry {
public:
object value;
uint32_t number;
int next;
};
static unsigned footprint(unsigned capacity) {
return sizeof(Set)
+ pad(sizeof(int) * capacity)
+ pad(sizeof(Set::Entry) * capacity);
}
Set(unsigned capacity):
size(0),
capacity(capacity),
index(reinterpret_cast<int*>
(reinterpret_cast<uint8_t*>(this)
+ sizeof(Set))),
entries(reinterpret_cast<Entry*>
(reinterpret_cast<uint8_t*>(index)
+ pad(sizeof(int) * capacity)))
{ }
unsigned size;
unsigned capacity;
int* index;
Entry* entries;
};
class Stack {
public:
class Entry {
public:
object value;
int offset;
};
static const unsigned Capacity = 4096;
Stack(Stack* next): next(next), entryCount(0) { }
Stack* next;
unsigned entryCount;
Entry entries[Capacity];
};
class Context {
public:
Context(Thread* thread, FILE* out):
thread(thread), out(out), objects(0), stack(0), nextNumber(1)
{ }
~Context() {
if (objects) {
thread->m->heap->free(objects, Set::footprint(objects->capacity));
}
while (stack) {
Stack* dead = stack;
stack = dead->next;
thread->m->heap->free(stack, sizeof(Stack));
}
}
Thread* thread;
FILE* out;
Set* objects;
Stack* stack;
uint32_t nextNumber;
};
void
push(Context* c, object p, int offset)
{
if (c->stack == 0 or c->stack->entryCount == Stack::Capacity) {
c->stack = new (c->thread->m->heap->allocate(sizeof(Stack)))
Stack(c->stack);
}
Stack::Entry* e = c->stack->entries + (c->stack->entryCount++);
e->value = p;
e->offset = offset;
}
bool
pop(Context* c, object* p, int* offset)
{
if (c->stack) {
if (c->stack->entryCount == 0) {
if (c->stack->next) {
Stack* dead = c->stack;
c->stack = dead->next;
c->thread->m->heap->free(dead, sizeof(Stack));
} else {
return false;
}
}
Stack::Entry* e = c->stack->entries + (--c->stack->entryCount);
*p = e->value;
*offset = e->offset;
return true;
} else {
return false;
}
}
unsigned
hash(object p, unsigned capacity)
{
return (reinterpret_cast<uintptr_t>(p) >> PointerShift)
& (capacity - 1);
}
Set::Entry*
find(Context* c, object p)
{
if (c->objects == 0) return false;
for (int i = c->objects->index[hash(p, c->objects->capacity)]; i >= 0;) {
Set::Entry* e = c->objects->entries + i;
if (e->value == p) {
return e;
}
i = e->next;
}
return false;
}
Set::Entry*
add(Context* c UNUSED, Set* set, object p, uint32_t number)
{
assert(c->thread, set->size < set->capacity);
unsigned index = hash(p, set->capacity);
int offset = set->size++;
Set::Entry* e = set->entries + offset;
e->value = p;
e->number = number;
e->next = set->index[index];
set->index[index] = offset;
return e;
}
Set::Entry*
add(Context* c, object p)
{
if (c->objects == 0 or c->objects->size == c->objects->capacity) {
unsigned capacity;
if (c->objects) {
capacity = c->objects->capacity * 2;
} else {
capacity = 4096; // must be power of two
}
Set* set = new (c->thread->m->heap->allocate(Set::footprint(capacity)))
Set(capacity);
memset(set->index, 0xFF, sizeof(int) * capacity);
if (c->objects) {
for (unsigned i = 0; i < c->objects->capacity; ++i) {
for (int j = c->objects->index[i]; j >= 0;) {
Set::Entry* e = c->objects->entries + j;
add(c, set, e->value, e->number);
j = e->next;
}
}
c->thread->m->heap->free
(c->objects, Set::footprint(c->objects->capacity));
}
c->objects = set;
}
return add(c, c->objects, p, 0);
}
enum {
Root,
Size,
ClassName,
Push,
Pop
};
inline object
get(object o, unsigned offsetInWords)
{
return static_cast<object>
(mask(cast<void*>(o, offsetInWords * BytesPerWord)));
}
void
write1(Context* c, uint8_t v)
{
fwrite(&v, 1, 1, c->out);
}
void
write4(Context* c, uint32_t v)
{
uint8_t b[] = { v >> 24, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF };
fwrite(b, 4, 1, c->out);
}
void
writeString(Context* c, int8_t* p, unsigned size)
{
write4(c, size);
fwrite(p, size, 1, c->out);
}
unsigned
objectSize(Thread* t, object o)
{
unsigned n = baseSize(t, o, objectClass(t, o));
if (objectExtended(t, o)) {
++ n;
}
return n;
}
void
visit(Context* c, object p)
{
Thread* t = c->thread;
int nextChildOffset;
write1(c, Root);
visit: {
Set::Entry* e = find(c, p);
if (e) {
write4(c, e->number);
} else {
e = add(c, p);
e->number = c->nextNumber++;
write4(c, e->number);
write1(c, Size);
write4(c, objectSize(t, p));
if (objectClass(t, p) == arrayBody(t, t->m->types, Machine::ClassType)) {
object name = className(t, p);
if (name) {
write1(c, ClassName);
writeString(c, &byteArrayBody(t, name, 0),
byteArrayLength(t, name) - 1);
}
}
nextChildOffset = walkNext(t, p, -1);
if (nextChildOffset != -1) {
goto children;
}
}
}
goto pop;
children: {
write1(c, Push);
push(c, p, nextChildOffset);
p = get(p, nextChildOffset);
goto visit;
}
pop: {
if (pop(c, &p, &nextChildOffset)) {
write1(c, Pop);
nextChildOffset = walkNext(t, p, nextChildOffset);
if (nextChildOffset >= 0) {
goto children;
} else {
goto pop;
}
}
}
}
} // namespace
namespace vm {
void
dumpHeap(Thread* t, FILE* out)
{
Context context(t, out);
class Visitor : public Heap::Visitor {
public:
Visitor(Context* c): c(c) { }
virtual void visit(void* p) {
::visit(c, static_cast<object>(mask(*static_cast<void**>(p))));
}
Context* c;
} v(&context);
add(&context, 0)->number = 0;
visitRoots(t, &v);
}
} // namespace vm
<|endoftext|> |
<commit_before>
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_
#include <recording/dispatchrecorder.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
using namespace ::com::sun::star::uno;
namespace framework{
//*****************************************************************************************************************
// XInterface, XTypeProvider, XServiceInfo
//*****************************************************************************************************************
DEFINE_XINTERFACE_3(
DispatchRecorder,
OWeakObject,
DIRECT_INTERFACE(css::lang::XTypeProvider),
DIRECT_INTERFACE(css::lang::XServiceInfo),
DIRECT_INTERFACE(css::frame::XDispatchRecorder))
DEFINE_XTYPEPROVIDER_3(
DispatchRecorder,
css::lang::XTypeProvider,
css::lang::XServiceInfo,
css::frame::XDispatchRecorder)
DEFINE_XSERVICEINFO_MULTISERVICE(
DispatchRecorder,
::cppu::OWeakObject,
SERVICENAME_DISPATCHRECORDER,
IMPLEMENTATIONNAME_DISPATCHRECORDER)
DEFINE_INIT_SERVICE(
DispatchRecorder,
{
}
)
#include <typelib/typedescription.h>
//--------------------------------------------------------------------------------------------------
void flatten_struct_members(
::std::vector< Any > * vec, void const * data,
typelib_CompoundTypeDescription * pTD )
SAL_THROW( () )
{
if (pTD->pBaseTypeDescription)
{
flatten_struct_members( vec, data, pTD->pBaseTypeDescription );
}
for ( sal_Int32 nPos = 0; nPos < pTD->nMembers; ++nPos )
{
vec->push_back(
Any( (char const *)data + pTD->pMemberOffsets[ nPos ], pTD->ppTypeRefs[ nPos ] ) );
}
}
//==================================================================================================
Sequence< Any > make_seq_out_of_struct(
Any const & val )
SAL_THROW( (RuntimeException) )
{
Type const & type = val.getValueType();
TypeClass eTypeClass = type.getTypeClass();
if (TypeClass_STRUCT != eTypeClass && TypeClass_EXCEPTION != eTypeClass)
{
throw RuntimeException(
type.getTypeName() +
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("is no struct or exception!") ),
Reference< XInterface >() );
}
typelib_TypeDescription * pTD = 0;
TYPELIB_DANGER_GET( &pTD, type.getTypeLibType() );
OSL_ASSERT( pTD );
if (! pTD)
{
throw RuntimeException(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("cannot get type descr of type ") ) +
type.getTypeName(),
Reference< XInterface >() );
}
::std::vector< Any > vec;
vec.reserve( ((typelib_CompoundTypeDescription *)pTD)->nMembers ); // good guess
flatten_struct_members( &vec, val.getValue(), (typelib_CompoundTypeDescription *)pTD );
TYPELIB_DANGER_RELEASE( pTD );
return Sequence< Any >( &vec[ 0 ], vec.size() );
}
struct DispatchStatement
{
::rtl::OUString aCommand;
css::uno::Sequence < css::beans::PropertyValue > aArgs;
sal_Bool bIsComment;
DispatchStatement( const ::rtl::OUString& rCmd, const css::uno::Sequence< css::beans::PropertyValue >& rArgs, sal_Bool bComment )
: aCommand( rCmd )
, bIsComment( bComment )
{
aArgs = rArgs;
}
};
//***********************************************************************
DispatchRecorder::DispatchRecorder( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR )
: ThreadHelpBase ( &Application::GetSolarMutex() )
, ::cppu::OWeakObject( )
, m_xSMGR ( xSMGR )
, m_xConverter( m_xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.script.Converter")), css::uno::UNO_QUERY )
{
}
//************************************************************************
DispatchRecorder::~DispatchRecorder()
{
}
//*************************************************************************
// generate header
void SAL_CALL DispatchRecorder::startRecording( const css::uno::Reference< css::frame::XFrame >& xFrame ) throw( css::uno::RuntimeException )
{
/* SAFE{ */
/* } */
}
//*************************************************************************
void SAL_CALL DispatchRecorder::recordDispatch( const css::util::URL& aURL,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException )
{
//implts_recordMacro(aURL,lArguments,sal_False);
sal_Int32 nSize = m_aStatements.size();
if ( nSize && aURL.Complete.compareToAscii(".uno:InsertText") == COMPARE_EQUAL )
{
DispatchStatementList::reverse_iterator pLast = m_aStatements.rbegin();
if ( pLast->aCommand.compareToAscii(".uno:InsertText") == COMPARE_EQUAL )
{
::rtl::OUString aStr;
::rtl::OUString aNew;
pLast->aArgs[0].Value >>= aStr;
lArguments[0].Value >>= aNew;
aStr += aNew;
pLast->aArgs[0].Value <<= aStr;
return;
}
}
DispatchStatement aStatement( aURL.Complete, lArguments, sal_False );
m_aStatements.push_back( aStatement );
}
//*************************************************************************
void SAL_CALL DispatchRecorder::recordDispatchAsComment( const css::util::URL& aURL,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException )
{
//implts_recordMacro(aURL,lArguments,sal_True);
DispatchStatement aStatement( aURL.Complete, lArguments, sal_True );
m_aStatements.push_back( aStatement );
}
//*************************************************************************
void SAL_CALL DispatchRecorder::endRecording() throw( css::uno::RuntimeException )
{
/* SAFE{ */
WriteGuard aWriteLock(m_aLock);
m_aStatements.clear();
/* } */
}
//*************************************************************************
::rtl::OUString SAL_CALL DispatchRecorder::getRecordedMacro() throw( css::uno::RuntimeException )
{
/* SAFE{ */
WriteGuard aWriteLock(m_aLock);
::rtl::OUStringBuffer aScriptBuffer;
aScriptBuffer.ensureCapacity(10000);
m_nRecordingID = 1;
aScriptBuffer.appendAscii("rem ----------------------------------------------------------------------\n");
aScriptBuffer.appendAscii("rem define variables\n");
aScriptBuffer.appendAscii("dim document as object\n");
aScriptBuffer.appendAscii("dim dispatcher as object\n");
aScriptBuffer.appendAscii("dim parser as object\n");
aScriptBuffer.appendAscii("dim url as new com.sun.star.util.URL\n");
aScriptBuffer.appendAscii("rem ----------------------------------------------------------------------\n");
aScriptBuffer.appendAscii("rem get access to the document\n");
aScriptBuffer.appendAscii("document = ThisComponent.CurrentController.Frame\n");
aScriptBuffer.appendAscii("parser = createUnoService(\"com.sun.star.util.URLTransformer\")\n\n");
std::vector< DispatchStatement>::iterator p;
for ( p = m_aStatements.begin(); p != m_aStatements.end(); p++ )
implts_recordMacro( p->aCommand, p->aArgs, p->bIsComment, aScriptBuffer );
::rtl::OUString sScript = aScriptBuffer.makeStringAndClear();
return sScript;
/* } */
}
//*************************************************************************
void SAL_CALL DispatchRecorder::AppendToBuffer( css::uno::Any aValue, ::rtl::OUStringBuffer& aArgumentBuffer )
{
// if value == bool
if (aValue.getValueType() == getBooleanCppuType())
{
sal_Bool bVal;
aValue >>= bVal;
if (bVal)
aArgumentBuffer.appendAscii("true");
else
aArgumentBuffer.appendAscii("false");
}
else
// if value == sal_Int8
if (aValue.getValueType() == getCppuType((sal_Int8*)0))
{
sal_Int8 nVal;
aValue >>= nVal;
aArgumentBuffer.append((sal_Int32)nVal);
}
else
// if value == sal_Int16
if (aValue.getValueType() == getCppuType((sal_Int16*)0))
{
sal_Int16 nVal;
aValue >>= nVal;
aArgumentBuffer.append((sal_Int32)nVal);
}
else
// if value == sal_Int32
if (aValue.getValueType() == getCppuType((sal_Int32*)0))
{
sal_Int32 nVal;
aValue >>= nVal;
aArgumentBuffer.append((sal_Int32)nVal);
}
else
// if value == sal_UniCode
if (aValue.getValueType() == getCppuCharType())
{
sal_Unicode nVal = *((sal_Unicode*)aValue.getValue());
aArgumentBuffer.appendAscii("\"");
aArgumentBuffer.append((sal_Unicode)nVal);
aArgumentBuffer.appendAscii("\"");
}
else
// if value == float
if (aValue.getValueType() == getCppuType((float*)0))
{
float fVal;
aValue >>= fVal;
aArgumentBuffer.append(fVal);
}
else
// if value == double
if (aValue.getValueType() == getCppuType((double*)0))
{
double fVal;
aValue >>= fVal;
aArgumentBuffer.append(fVal);
}
else
// if value == string
if (aValue.getValueType() == getCppuType((::rtl::OUString*)0))
{
::rtl::OUString sVal;
aValue >>= sVal;
aArgumentBuffer.appendAscii("\"");
aArgumentBuffer.append (sVal);
aArgumentBuffer.appendAscii("\"");
}
else if (aValue.getValueTypeClass() == css::uno::TypeClass_ENUM )
{
sal_Int32 nVal = *(sal_Int32*)aValue.getValue();
aArgumentBuffer.append((sal_Int32)nVal);
}
else if (aValue.getValueTypeClass() == css::uno::TypeClass_STRUCT )
{
Sequence< Any > aSeq = make_seq_out_of_struct( aValue );
aArgumentBuffer.appendAscii("Array(");
for ( sal_Int32 nAny=0; nAny<aSeq.getLength(); nAny++ )
{
AppendToBuffer( aSeq[nAny], aArgumentBuffer );
if ( nAny+1 < aSeq.getLength() )
// not last argument
aArgumentBuffer.appendAscii(",");
}
aArgumentBuffer.appendAscii(")");
}
else if (aValue.getValueTypeClass() == css::uno::TypeClass_SEQUENCE )
{
css::uno::Sequence < css::uno::Any > aSeq;
css::uno::Any aNew;
try { aNew = m_xConverter->convertTo( aValue, ::getCppuType((const css::uno::Sequence < css::uno::Any >*)0) ); }
catch (css::uno::Exception&) {}
aNew >>= aSeq;
aArgumentBuffer.appendAscii("Array(");
for ( sal_Int32 nAny=0; nAny<aSeq.getLength(); nAny++ )
{
AppendToBuffer( aSeq[nAny], aArgumentBuffer );
if ( nAny+1 < aSeq.getLength() )
// not last argument
aArgumentBuffer.appendAscii(",");
}
aArgumentBuffer.appendAscii(")");
}
else {
LOG_WARNING("","Type not scriptable!")
}
}
void SAL_CALL DispatchRecorder::implts_recordMacro( const ::rtl::OUString& aURL,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments,
sal_Bool bAsComment, ::rtl::OUStringBuffer& aScriptBuffer )
{
::rtl::OUStringBuffer aArgumentBuffer(1000);
::rtl::OUString sArrayName;
aScriptBuffer.appendAscii("rem ----------------------------------------------------------------------\n");
aScriptBuffer.appendAscii("rem dispatch\n");
sal_Int32 nLength = lArguments.getLength();
sal_Int32 nValidArgs = 0;
for( sal_Int32 i=0; i<nLength; ++i )
{
if(lArguments[i].Value.hasValue())
{
// this value is used to name the arrays of aArgumentBuffer
if(sArrayName.getLength()<1)
{
sArrayName = ::rtl::OUString::createFromAscii("args");
sArrayName += ::rtl::OUString::valueOf((sal_Int32)m_nRecordingID);
}
++nValidArgs;
// add arg().Name
if(bAsComment)
aArgumentBuffer.appendAscii("rem ");
aArgumentBuffer.append (sArrayName);
aArgumentBuffer.appendAscii("(");
aArgumentBuffer.append (i);
aArgumentBuffer.appendAscii(").Name = \"");
aArgumentBuffer.append (lArguments[i].Name);
aArgumentBuffer.appendAscii("\"\n");
// add arg().Value
if(bAsComment)
aArgumentBuffer.appendAscii("rem ");
aArgumentBuffer.append (sArrayName);
aArgumentBuffer.appendAscii("(");
aArgumentBuffer.append (i);
aArgumentBuffer.appendAscii(").Value = ");
AppendToBuffer( lArguments[i].Value, aArgumentBuffer);
aArgumentBuffer.appendAscii("\n");
}
}
// if aArgumentBuffer exist - pack it into the aScriptBuffer
if(nValidArgs>0)
{
if(bAsComment)
aArgumentBuffer.appendAscii("rem ");
aScriptBuffer.appendAscii("dim ");
aScriptBuffer.append (sArrayName);
aScriptBuffer.appendAscii("(");
aScriptBuffer.append ((sal_Int32)(nValidArgs-1)); // 0 based!
aScriptBuffer.appendAscii(") as new com.sun.star.beans.PropertyValue\n");
aScriptBuffer.append (aArgumentBuffer.makeStringAndClear());
aScriptBuffer.appendAscii("\n");
}
// add code for parsing urls
if(bAsComment)
aArgumentBuffer.appendAscii("rem ");
aScriptBuffer.appendAscii("url.Complete = \"");
aScriptBuffer.append (aURL);
aScriptBuffer.appendAscii("\"\n");
if(bAsComment)
aArgumentBuffer.appendAscii("rem ");
aScriptBuffer.appendAscii("parser.parseStrict(url)\n");
// add code for dispatches
if(bAsComment)
aArgumentBuffer.appendAscii("rem ");
aScriptBuffer.appendAscii("disp = document.queryDispatch(url,\"\",0)\n");
if(bAsComment)
aArgumentBuffer.appendAscii("rem ");
if(nValidArgs<1)
aScriptBuffer.appendAscii("disp.dispatch(url,noargs())\n");
else
{
aScriptBuffer.appendAscii("disp.dispatch(url,");
aScriptBuffer.append( sArrayName.getStr() );
aScriptBuffer.appendAscii("())\n");
}
aScriptBuffer.appendAscii("\n");
/* SAFE { */
m_nRecordingID++;
/* } */
}
} // namespace framework
<commit_msg>#99907#: record enums<commit_after>
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_
#include <recording/dispatchrecorder.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
using namespace ::com::sun::star::uno;
namespace framework{
//*****************************************************************************************************************
// XInterface, XTypeProvider, XServiceInfo
//*****************************************************************************************************************
DEFINE_XINTERFACE_3(
DispatchRecorder,
OWeakObject,
DIRECT_INTERFACE(css::lang::XTypeProvider),
DIRECT_INTERFACE(css::lang::XServiceInfo),
DIRECT_INTERFACE(css::frame::XDispatchRecorder))
DEFINE_XTYPEPROVIDER_3(
DispatchRecorder,
css::lang::XTypeProvider,
css::lang::XServiceInfo,
css::frame::XDispatchRecorder)
DEFINE_XSERVICEINFO_MULTISERVICE(
DispatchRecorder,
::cppu::OWeakObject,
SERVICENAME_DISPATCHRECORDER,
IMPLEMENTATIONNAME_DISPATCHRECORDER)
DEFINE_INIT_SERVICE(
DispatchRecorder,
{
}
)
#include <typelib/typedescription.h>
//--------------------------------------------------------------------------------------------------
void flatten_struct_members(
::std::vector< Any > * vec, void const * data,
typelib_CompoundTypeDescription * pTD )
SAL_THROW( () )
{
if (pTD->pBaseTypeDescription)
{
flatten_struct_members( vec, data, pTD->pBaseTypeDescription );
}
for ( sal_Int32 nPos = 0; nPos < pTD->nMembers; ++nPos )
{
vec->push_back(
Any( (char const *)data + pTD->pMemberOffsets[ nPos ], pTD->ppTypeRefs[ nPos ] ) );
}
}
//==================================================================================================
Sequence< Any > make_seq_out_of_struct(
Any const & val )
SAL_THROW( (RuntimeException) )
{
Type const & type = val.getValueType();
TypeClass eTypeClass = type.getTypeClass();
if (TypeClass_STRUCT != eTypeClass && TypeClass_EXCEPTION != eTypeClass)
{
throw RuntimeException(
type.getTypeName() +
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("is no struct or exception!") ),
Reference< XInterface >() );
}
typelib_TypeDescription * pTD = 0;
TYPELIB_DANGER_GET( &pTD, type.getTypeLibType() );
OSL_ASSERT( pTD );
if (! pTD)
{
throw RuntimeException(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("cannot get type descr of type ") ) +
type.getTypeName(),
Reference< XInterface >() );
}
::std::vector< Any > vec;
vec.reserve( ((typelib_CompoundTypeDescription *)pTD)->nMembers ); // good guess
flatten_struct_members( &vec, val.getValue(), (typelib_CompoundTypeDescription *)pTD );
TYPELIB_DANGER_RELEASE( pTD );
return Sequence< Any >( &vec[ 0 ], vec.size() );
}
struct DispatchStatement
{
::rtl::OUString aCommand;
css::uno::Sequence < css::beans::PropertyValue > aArgs;
sal_Bool bIsComment;
DispatchStatement( const ::rtl::OUString& rCmd, const css::uno::Sequence< css::beans::PropertyValue >& rArgs, sal_Bool bComment )
: aCommand( rCmd )
, bIsComment( bComment )
{
aArgs = rArgs;
}
};
//***********************************************************************
DispatchRecorder::DispatchRecorder( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR )
: ThreadHelpBase ( &Application::GetSolarMutex() )
, ::cppu::OWeakObject( )
, m_xSMGR ( xSMGR )
, m_xConverter( m_xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.script.Converter")), css::uno::UNO_QUERY )
{
}
//************************************************************************
DispatchRecorder::~DispatchRecorder()
{
}
//*************************************************************************
// generate header
void SAL_CALL DispatchRecorder::startRecording( const css::uno::Reference< css::frame::XFrame >& xFrame ) throw( css::uno::RuntimeException )
{
/* SAFE{ */
/* } */
}
//*************************************************************************
void SAL_CALL DispatchRecorder::recordDispatch( const css::util::URL& aURL,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException )
{
//implts_recordMacro(aURL,lArguments,sal_False);
sal_Int32 nSize = m_aStatements.size();
if ( nSize && aURL.Complete.compareToAscii(".uno:InsertText") == COMPARE_EQUAL )
{
DispatchStatementList::reverse_iterator pLast = m_aStatements.rbegin();
if ( pLast->aCommand.compareToAscii(".uno:InsertText") == COMPARE_EQUAL )
{
::rtl::OUString aStr;
::rtl::OUString aNew;
pLast->aArgs[0].Value >>= aStr;
lArguments[0].Value >>= aNew;
aStr += aNew;
pLast->aArgs[0].Value <<= aStr;
return;
}
}
DispatchStatement aStatement( aURL.Complete, lArguments, sal_False );
m_aStatements.push_back( aStatement );
}
//*************************************************************************
void SAL_CALL DispatchRecorder::recordDispatchAsComment( const css::util::URL& aURL,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException )
{
//implts_recordMacro(aURL,lArguments,sal_True);
DispatchStatement aStatement( aURL.Complete, lArguments, sal_True );
m_aStatements.push_back( aStatement );
}
//*************************************************************************
void SAL_CALL DispatchRecorder::endRecording() throw( css::uno::RuntimeException )
{
/* SAFE{ */
WriteGuard aWriteLock(m_aLock);
m_aStatements.clear();
/* } */
}
//*************************************************************************
::rtl::OUString SAL_CALL DispatchRecorder::getRecordedMacro() throw( css::uno::RuntimeException )
{
/* SAFE{ */
WriteGuard aWriteLock(m_aLock);
::rtl::OUStringBuffer aScriptBuffer;
aScriptBuffer.ensureCapacity(10000);
m_nRecordingID = 1;
aScriptBuffer.appendAscii("rem ----------------------------------------------------------------------\n");
aScriptBuffer.appendAscii("rem define variables\n");
aScriptBuffer.appendAscii("dim document as object\n");
aScriptBuffer.appendAscii("dim dispatcher as object\n");
aScriptBuffer.appendAscii("dim parser as object\n");
aScriptBuffer.appendAscii("dim url as new com.sun.star.util.URL\n");
aScriptBuffer.appendAscii("rem ----------------------------------------------------------------------\n");
aScriptBuffer.appendAscii("rem get access to the document\n");
aScriptBuffer.appendAscii("document = ThisComponent.CurrentController.Frame\n");
aScriptBuffer.appendAscii("parser = createUnoService(\"com.sun.star.util.URLTransformer\")\n\n");
std::vector< DispatchStatement>::iterator p;
for ( p = m_aStatements.begin(); p != m_aStatements.end(); p++ )
implts_recordMacro( p->aCommand, p->aArgs, p->bIsComment, aScriptBuffer );
::rtl::OUString sScript = aScriptBuffer.makeStringAndClear();
return sScript;
/* } */
}
//*************************************************************************
void SAL_CALL DispatchRecorder::AppendToBuffer( css::uno::Any aValue, ::rtl::OUStringBuffer& aArgumentBuffer )
{
// if value == bool
if (aValue.getValueTypeClass() == css::uno::TypeClass_STRUCT )
{
// structs are recorded as arrays, convert to "Sequence of any"
Sequence< Any > aSeq = make_seq_out_of_struct( aValue );
aArgumentBuffer.appendAscii("Array(");
for ( sal_Int32 nAny=0; nAny<aSeq.getLength(); nAny++ )
{
AppendToBuffer( aSeq[nAny], aArgumentBuffer );
if ( nAny+1 < aSeq.getLength() )
// not last argument
aArgumentBuffer.appendAscii(",");
}
aArgumentBuffer.appendAscii(")");
}
else if (aValue.getValueTypeClass() == css::uno::TypeClass_SEQUENCE )
{
// convert to "Sequence of any"
css::uno::Sequence < css::uno::Any > aSeq;
css::uno::Any aNew;
try { aNew = m_xConverter->convertTo( aValue, ::getCppuType((const css::uno::Sequence < css::uno::Any >*)0) ); }
catch (css::uno::Exception&) {}
aNew >>= aSeq;
aArgumentBuffer.appendAscii("Array(");
for ( sal_Int32 nAny=0; nAny<aSeq.getLength(); nAny++ )
{
AppendToBuffer( aSeq[nAny], aArgumentBuffer );
if ( nAny+1 < aSeq.getLength() )
// not last argument
aArgumentBuffer.appendAscii(",");
}
aArgumentBuffer.appendAscii(")");
}
else if (aValue.getValueTypeClass() == css::uno::TypeClass_STRING )
{
// strings need \"
::rtl::OUString sVal;
aValue >>= sVal;
// open string
aArgumentBuffer.appendAscii("\"");
// encode \" inside the string to \"\"
sal_Int32 nIndex = 0;
do
{
::rtl::OUString aToken = sVal.getToken( 0, '"', nIndex );
aArgumentBuffer.append( aToken );
if ( nIndex>=0 )
aArgumentBuffer.appendAscii("\"\"");
}
while ( nIndex >= 0 );
// close string
aArgumentBuffer.appendAscii("\"");
}
else if (aValue.getValueType() == getCppuCharType())
{
// character variables are recorded as strings, back conversion must be handled in client code
sal_Unicode nVal = *((sal_Unicode*)aValue.getValue());
aArgumentBuffer.appendAscii("\"");
if ( (sal_Unicode(nVal) == '\"') )
// encode \" to \"\"
aArgumentBuffer.append((sal_Unicode)nVal);
aArgumentBuffer.append((sal_Unicode)nVal);
aArgumentBuffer.appendAscii("\"");
}
else
{
css::uno::Any aNew;
try
{
aNew = m_xConverter->convertToSimpleType( aValue, css::uno::TypeClass_STRING );
}
catch (css::script::CannotConvertException&) { LOG_WARNING("","Type not scriptable!") }
catch (css::uno::Exception&) {}
::rtl::OUString sVal;
aNew >>= sVal;
if (aValue.getValueTypeClass() == css::uno::TypeClass_ENUM )
{
::rtl::OUString aName = aValue.getValueType().getTypeName();
aArgumentBuffer.append( aName );
aArgumentBuffer.appendAscii(".");
}
aArgumentBuffer.append(sVal);
}
/*
else if (aValue.getValueType() == getBooleanCppuType())
{
sal_Bool bVal;
aValue >>= bVal;
if (bVal)
aArgumentBuffer.appendAscii("true");
else
aArgumentBuffer.appendAscii("false");
}
else if (aValue.getValueType() == getCppuType((sal_Int8*)0))
{
sal_Int8 nVal;
aValue >>= nVal;
aArgumentBuffer.append((sal_Int32)nVal);
}
else if (aValue.getValueType() == getCppuType((sal_Int16*)0))
{
sal_Int16 nVal;
aValue >>= nVal;
aArgumentBuffer.append((sal_Int32)nVal);
}
else if (aValue.getValueType() == getCppuType((sal_Int32*)0))
{
sal_Int32 nVal;
aValue >>= nVal;
aArgumentBuffer.append((sal_Int32)nVal);
}
else if (aValue.getValueType() == getCppuType((float*)0))
{
float fVal;
aValue >>= fVal;
aArgumentBuffer.append(fVal);
}
else if (aValue.getValueType() == getCppuType((double*)0))
{
double fVal;
aValue >>= fVal;
aArgumentBuffer.append(fVal);
}
else
{
LOG_WARNING("","Type not scriptable!")
}
*/
}
void SAL_CALL DispatchRecorder::implts_recordMacro( const ::rtl::OUString& aURL,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments,
sal_Bool bAsComment, ::rtl::OUStringBuffer& aScriptBuffer )
{
::rtl::OUStringBuffer aArgumentBuffer(1000);
::rtl::OUString sArrayName;
aScriptBuffer.appendAscii("rem ----------------------------------------------------------------------\n");
aScriptBuffer.appendAscii("rem dispatch\n");
sal_Int32 nLength = lArguments.getLength();
sal_Int32 nValidArgs = 0;
for( sal_Int32 i=0; i<nLength; ++i )
{
if(lArguments[i].Value.hasValue())
{
// this value is used to name the arrays of aArgumentBuffer
if(sArrayName.getLength()<1)
{
sArrayName = ::rtl::OUString::createFromAscii("args");
sArrayName += ::rtl::OUString::valueOf((sal_Int32)m_nRecordingID);
}
++nValidArgs;
// add arg().Name
if(bAsComment)
aArgumentBuffer.appendAscii("rem ");
aArgumentBuffer.append (sArrayName);
aArgumentBuffer.appendAscii("(");
aArgumentBuffer.append (i);
aArgumentBuffer.appendAscii(").Name = \"");
aArgumentBuffer.append (lArguments[i].Name);
aArgumentBuffer.appendAscii("\"\n");
// add arg().Value
if(bAsComment)
aArgumentBuffer.appendAscii("rem ");
aArgumentBuffer.append (sArrayName);
aArgumentBuffer.appendAscii("(");
aArgumentBuffer.append (i);
aArgumentBuffer.appendAscii(").Value = ");
AppendToBuffer( lArguments[i].Value, aArgumentBuffer);
aArgumentBuffer.appendAscii("\n");
}
}
// if aArgumentBuffer exist - pack it into the aScriptBuffer
if(nValidArgs>0)
{
if(bAsComment)
aArgumentBuffer.appendAscii("rem ");
aScriptBuffer.appendAscii("dim ");
aScriptBuffer.append (sArrayName);
aScriptBuffer.appendAscii("(");
aScriptBuffer.append ((sal_Int32)(nValidArgs-1)); // 0 based!
aScriptBuffer.appendAscii(") as new com.sun.star.beans.PropertyValue\n");
aScriptBuffer.append (aArgumentBuffer.makeStringAndClear());
aScriptBuffer.appendAscii("\n");
}
// add code for parsing urls
if(bAsComment)
aArgumentBuffer.appendAscii("rem ");
aScriptBuffer.appendAscii("url.Complete = \"");
aScriptBuffer.append (aURL);
aScriptBuffer.appendAscii("\"\n");
if(bAsComment)
aArgumentBuffer.appendAscii("rem ");
aScriptBuffer.appendAscii("parser.parseStrict(url)\n");
// add code for dispatches
if(bAsComment)
aArgumentBuffer.appendAscii("rem ");
aScriptBuffer.appendAscii("disp = document.queryDispatch(url,\"\",0)\n");
if(bAsComment)
aArgumentBuffer.appendAscii("rem ");
if(nValidArgs<1)
aScriptBuffer.appendAscii("disp.dispatch(url,noargs())\n");
else
{
aScriptBuffer.appendAscii("disp.dispatch(url,");
aScriptBuffer.append( sArrayName.getStr() );
aScriptBuffer.appendAscii("())\n");
}
aScriptBuffer.appendAscii("\n");
/* SAFE { */
m_nRecordingID++;
/* } */
}
} // namespace framework
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "net/base/mock_host_resolver.h"
class AppApiTest : public ExtensionApiTest {
};
// Simulates a page calling window.open on an URL, and waits for the navigation.
static void WindowOpenHelper(Browser* browser,
RenderViewHost* opener_host,
const GURL& url,
bool newtab_process_should_equal_opener) {
ASSERT_TRUE(ui_test_utils::ExecuteJavaScript(
opener_host, L"", L"window.open('" + UTF8ToWide(url.spec()) + L"');"));
// The above window.open call is not user-initiated, it will create
// a popup window instead of a new tab in current window.
// Now the active tab in last active window should be the new tab.
Browser* last_active_browser = BrowserList::GetLastActive();
EXPECT_TRUE(last_active_browser);
TabContents* newtab = last_active_browser->GetSelectedTabContents();
EXPECT_TRUE(newtab);
if (!newtab->controller().GetLastCommittedEntry() ||
newtab->controller().GetLastCommittedEntry()->url() != url)
ui_test_utils::WaitForNavigation(&newtab->controller());
EXPECT_EQ(url, newtab->controller().GetLastCommittedEntry()->url());
if (newtab_process_should_equal_opener)
EXPECT_EQ(opener_host->process(), newtab->render_view_host()->process());
else
EXPECT_NE(opener_host->process(), newtab->render_view_host()->process());
}
// Simulates a page navigating itself to an URL, and waits for the navigation.
static void NavigateTabHelper(TabContents* contents, const GURL& url) {
bool result = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(), L"",
L"window.addEventListener('unload', function() {"
L" window.domAutomationController.send(true);"
L"}, false);"
L"window.location = '" + UTF8ToWide(url.spec()) + L"';",
&result));
ASSERT_TRUE(result);
if (!contents->controller().GetLastCommittedEntry() ||
contents->controller().GetLastCommittedEntry()->url() != url)
ui_test_utils::WaitForNavigation(&contents->controller());
EXPECT_EQ(url, contents->controller().GetLastCommittedEntry()->url());
}
#if defined(OS_WIN)
// AppProcess sometimes hangs on Windows
// http://crbug.com/88316
#define MAYBE_AppProcess DISABLED_AppProcess
#else
#define MAYBE_AppProcess AppProcess
#endif
IN_PROC_BROWSER_TEST_F(AppApiTest, MAYBE_AppProcess) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisablePopupBlocking);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app_process")));
// Open two tabs in the app, one outside it.
GURL base_url = test_server()->GetURL(
"files/extensions/api_test/app_process/");
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL::Replacements replace_host;
std::string host_str("localhost"); // must stay in scope with replace_host
replace_host.SetHostStr(host_str);
base_url = base_url.ReplaceComponents(replace_host);
// Test both opening a URL in a new tab, and opening a tab and then navigating
// it. Either way, app tabs should be considered extension processes, but
// they have no elevated privileges and thus should not have WebUI bindings.
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("path1/empty.html"), NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
EXPECT_TRUE(browser()->GetTabContentsAt(1)->render_view_host()->process()->
is_extension_process());
EXPECT_FALSE(browser()->GetTabContentsAt(1)->web_ui());
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path2/empty.html"));
EXPECT_TRUE(browser()->GetTabContentsAt(2)->render_view_host()->process()->
is_extension_process());
EXPECT_FALSE(browser()->GetTabContentsAt(2)->web_ui());
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path3/empty.html"));
EXPECT_FALSE(browser()->GetTabContentsAt(3)->render_view_host()->process()->
is_extension_process());
EXPECT_FALSE(browser()->GetTabContentsAt(3)->web_ui());
// We should have opened 3 new extension tabs. Including the original blank
// tab, we now have 4 tabs. Because the app_process app has the background
// permission, all of its instances are in the same process. Thus two tabs
// should be part of the extension app and grouped in the same process.
ASSERT_EQ(4, browser()->tab_count());
RenderViewHost* host = browser()->GetTabContentsAt(1)->render_view_host();
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
EXPECT_NE(host->process(),
browser()->GetTabContentsAt(3)->render_view_host()->process());
// Now let's do the same using window.open. The same should happen.
ASSERT_EQ(1u, BrowserList::GetBrowserCount(browser()->profile()));
WindowOpenHelper(browser(), host,
base_url.Resolve("path1/empty.html"), true);
WindowOpenHelper(browser(), host,
base_url.Resolve("path2/empty.html"), true);
// This should open in a new process (i.e., false for the last argument).
WindowOpenHelper(browser(), host,
base_url.Resolve("path3/empty.html"), false);
// Now let's have these pages navigate, into or out of the extension web
// extent. They should switch processes.
const GURL& app_url(base_url.Resolve("path1/empty.html"));
const GURL& non_app_url(base_url.Resolve("path3/empty.html"));
NavigateTabHelper(browser()->GetTabContentsAt(2), non_app_url);
NavigateTabHelper(browser()->GetTabContentsAt(3), app_url);
EXPECT_NE(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(3)->render_view_host()->process());
// If one of the popup tabs navigates back to the app, window.opener should
// be valid.
NavigateTabHelper(browser()->GetTabContentsAt(6), app_url);
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(6)->render_view_host()->process());
bool windowOpenerValid = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetTabContentsAt(6)->render_view_host(), L"",
L"window.domAutomationController.send(window.opener != null)",
&windowOpenerValid));
ASSERT_TRUE(windowOpenerValid);
}
// Test that hosted apps without the background permission use a process per app
// instance model, such that separate instances are in separate processes.
IN_PROC_BROWSER_TEST_F(AppApiTest, AppProcessInstances) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisablePopupBlocking);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("app_process_instances")));
// Open two tabs in the app, one outside it.
GURL base_url = test_server()->GetURL(
"files/extensions/api_test/app_process_instances/");
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL::Replacements replace_host;
std::string host_str("localhost"); // must stay in scope with replace_host
replace_host.SetHostStr(host_str);
base_url = base_url.ReplaceComponents(replace_host);
// Test both opening a URL in a new tab, and opening a tab and then navigating
// it. Either way, app tabs should be considered extension processes, but
// they have no elevated privileges and thus should not have WebUI bindings.
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("path1/empty.html"), NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
EXPECT_TRUE(browser()->GetTabContentsAt(1)->render_view_host()->process()->
is_extension_process());
EXPECT_FALSE(browser()->GetTabContentsAt(1)->web_ui());
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path2/empty.html"));
EXPECT_TRUE(browser()->GetTabContentsAt(2)->render_view_host()->process()->
is_extension_process());
EXPECT_FALSE(browser()->GetTabContentsAt(2)->web_ui());
// We should have opened 2 new extension tabs. Including the original blank
// tab, we now have 3 tabs. The two app tabs should not be in the same
// process, since they do not have the background permission. (Thus, we want
// to separate them to improve responsiveness.)
ASSERT_EQ(3, browser()->tab_count());
RenderViewHost* host1 = browser()->GetTabContentsAt(1)->render_view_host();
RenderViewHost* host2 = browser()->GetTabContentsAt(2)->render_view_host();
EXPECT_NE(host1->process(), host2->process());
// Opening tabs with window.open should keep the page in the opener's process.
ASSERT_EQ(1u, BrowserList::GetBrowserCount(browser()->profile()));
WindowOpenHelper(browser(), host1,
base_url.Resolve("path1/empty.html"), true);
WindowOpenHelper(browser(), host2,
base_url.Resolve("path2/empty.html"), true);
}
// Tests that app process switching works properly in the following scenario:
// 1. navigate to a page1 in the app
// 2. page1 redirects to a page2 outside the app extent (ie, "/server-redirect")
// 3. page2 redirects back to a page in the app
// The final navigation should end up in the app process.
// See http://crbug.com/61757
IN_PROC_BROWSER_TEST_F(AppApiTest, AppProcessRedirectBack) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisablePopupBlocking);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app_process")));
// Open two tabs in the app.
GURL base_url = test_server()->GetURL(
"files/extensions/api_test/app_process/");
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL::Replacements replace_host;
std::string host_str("localhost"); // must stay in scope with replace_host
replace_host.SetHostStr(host_str);
base_url = base_url.ReplaceComponents(replace_host);
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path1/empty.html"));
browser()->NewTab();
// Wait until the second tab finishes its redirect train (2 hops).
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
browser(), base_url.Resolve("path1/redirect.html"), 2);
// 3 tabs, including the initial about:blank. The last 2 should be the same
// process.
ASSERT_EQ(3, browser()->tab_count());
EXPECT_EQ("/files/extensions/api_test/app_process/path1/empty.html",
browser()->GetTabContentsAt(2)->controller().
GetLastCommittedEntry()->url().path());
RenderViewHost* host = browser()->GetTabContentsAt(1)->render_view_host();
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
}
// Ensure that reloading a URL after installing or uninstalling it as an app
// correctly swaps the process. (http://crbug.com/80621)
IN_PROC_BROWSER_TEST_F(AppApiTest, ReloadIntoAppProcess) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisablePopupBlocking);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL::Replacements replace_host;
std::string host_str("localhost"); // must stay in scope with replace_host
replace_host.SetHostStr(host_str);
GURL base_url = test_server()->GetURL(
"files/extensions/api_test/app_process/");
base_url = base_url.ReplaceComponents(replace_host);
// Load an app URL before loading the app.
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path1/empty.html"));
TabContents* contents = browser()->GetTabContentsAt(0);
EXPECT_FALSE(contents->render_view_host()->process()->is_extension_process());
// Load app and reload page.
const Extension* app =
LoadExtension(test_data_dir_.AppendASCII("app_process"));
ASSERT_TRUE(app);
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path1/empty.html"));
EXPECT_TRUE(contents->render_view_host()->process()->is_extension_process());
// Disable app and reload page.
DisableExtension(app->id());
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path1/empty.html"));
EXPECT_FALSE(contents->render_view_host()->process()->is_extension_process());
// Enable app and reload via JavaScript.
EnableExtension(app->id());
ASSERT_TRUE(ui_test_utils::ExecuteJavaScript(contents->render_view_host(),
L"", L"location.reload();"));
ui_test_utils::WaitForNavigation(&contents->controller());
EXPECT_TRUE(contents->render_view_host()->process()->is_extension_process());
// Disable app and reload via JavaScript.
DisableExtension(app->id());
ASSERT_TRUE(ui_test_utils::ExecuteJavaScript(contents->render_view_host(),
L"", L"location.reload();"));
ui_test_utils::WaitForNavigation(&contents->controller());
EXPECT_FALSE(contents->render_view_host()->process()->is_extension_process());
}
<commit_msg>Marking AppApiTest.AppProcessInstances as flaky on windows<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "net/base/mock_host_resolver.h"
class AppApiTest : public ExtensionApiTest {
};
// Simulates a page calling window.open on an URL, and waits for the navigation.
static void WindowOpenHelper(Browser* browser,
RenderViewHost* opener_host,
const GURL& url,
bool newtab_process_should_equal_opener) {
ASSERT_TRUE(ui_test_utils::ExecuteJavaScript(
opener_host, L"", L"window.open('" + UTF8ToWide(url.spec()) + L"');"));
// The above window.open call is not user-initiated, it will create
// a popup window instead of a new tab in current window.
// Now the active tab in last active window should be the new tab.
Browser* last_active_browser = BrowserList::GetLastActive();
EXPECT_TRUE(last_active_browser);
TabContents* newtab = last_active_browser->GetSelectedTabContents();
EXPECT_TRUE(newtab);
if (!newtab->controller().GetLastCommittedEntry() ||
newtab->controller().GetLastCommittedEntry()->url() != url)
ui_test_utils::WaitForNavigation(&newtab->controller());
EXPECT_EQ(url, newtab->controller().GetLastCommittedEntry()->url());
if (newtab_process_should_equal_opener)
EXPECT_EQ(opener_host->process(), newtab->render_view_host()->process());
else
EXPECT_NE(opener_host->process(), newtab->render_view_host()->process());
}
// Simulates a page navigating itself to an URL, and waits for the navigation.
static void NavigateTabHelper(TabContents* contents, const GURL& url) {
bool result = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(), L"",
L"window.addEventListener('unload', function() {"
L" window.domAutomationController.send(true);"
L"}, false);"
L"window.location = '" + UTF8ToWide(url.spec()) + L"';",
&result));
ASSERT_TRUE(result);
if (!contents->controller().GetLastCommittedEntry() ||
contents->controller().GetLastCommittedEntry()->url() != url)
ui_test_utils::WaitForNavigation(&contents->controller());
EXPECT_EQ(url, contents->controller().GetLastCommittedEntry()->url());
}
#if defined(OS_WIN)
// AppProcess sometimes hangs on Windows
// http://crbug.com/88316
#define MAYBE_AppProcess DISABLED_AppProcess
#else
#define MAYBE_AppProcess AppProcess
#endif
IN_PROC_BROWSER_TEST_F(AppApiTest, MAYBE_AppProcess) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisablePopupBlocking);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app_process")));
// Open two tabs in the app, one outside it.
GURL base_url = test_server()->GetURL(
"files/extensions/api_test/app_process/");
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL::Replacements replace_host;
std::string host_str("localhost"); // must stay in scope with replace_host
replace_host.SetHostStr(host_str);
base_url = base_url.ReplaceComponents(replace_host);
// Test both opening a URL in a new tab, and opening a tab and then navigating
// it. Either way, app tabs should be considered extension processes, but
// they have no elevated privileges and thus should not have WebUI bindings.
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("path1/empty.html"), NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
EXPECT_TRUE(browser()->GetTabContentsAt(1)->render_view_host()->process()->
is_extension_process());
EXPECT_FALSE(browser()->GetTabContentsAt(1)->web_ui());
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path2/empty.html"));
EXPECT_TRUE(browser()->GetTabContentsAt(2)->render_view_host()->process()->
is_extension_process());
EXPECT_FALSE(browser()->GetTabContentsAt(2)->web_ui());
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path3/empty.html"));
EXPECT_FALSE(browser()->GetTabContentsAt(3)->render_view_host()->process()->
is_extension_process());
EXPECT_FALSE(browser()->GetTabContentsAt(3)->web_ui());
// We should have opened 3 new extension tabs. Including the original blank
// tab, we now have 4 tabs. Because the app_process app has the background
// permission, all of its instances are in the same process. Thus two tabs
// should be part of the extension app and grouped in the same process.
ASSERT_EQ(4, browser()->tab_count());
RenderViewHost* host = browser()->GetTabContentsAt(1)->render_view_host();
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
EXPECT_NE(host->process(),
browser()->GetTabContentsAt(3)->render_view_host()->process());
// Now let's do the same using window.open. The same should happen.
ASSERT_EQ(1u, BrowserList::GetBrowserCount(browser()->profile()));
WindowOpenHelper(browser(), host,
base_url.Resolve("path1/empty.html"), true);
WindowOpenHelper(browser(), host,
base_url.Resolve("path2/empty.html"), true);
// This should open in a new process (i.e., false for the last argument).
WindowOpenHelper(browser(), host,
base_url.Resolve("path3/empty.html"), false);
// Now let's have these pages navigate, into or out of the extension web
// extent. They should switch processes.
const GURL& app_url(base_url.Resolve("path1/empty.html"));
const GURL& non_app_url(base_url.Resolve("path3/empty.html"));
NavigateTabHelper(browser()->GetTabContentsAt(2), non_app_url);
NavigateTabHelper(browser()->GetTabContentsAt(3), app_url);
EXPECT_NE(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(3)->render_view_host()->process());
// If one of the popup tabs navigates back to the app, window.opener should
// be valid.
NavigateTabHelper(browser()->GetTabContentsAt(6), app_url);
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(6)->render_view_host()->process());
bool windowOpenerValid = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetTabContentsAt(6)->render_view_host(), L"",
L"window.domAutomationController.send(window.opener != null)",
&windowOpenerValid));
ASSERT_TRUE(windowOpenerValid);
}
#if defined(OS_WIN)
// Seems to timeout sometimes on Windows: http://crbug.com/89766
#define MAYBE_AppProcessInstances FLAKY_AppProcessInstances
#else
#define MAYBE_AppProcessInstances AppProcessInstances
#endif
// Test that hosted apps without the background permission use a process per app
// instance model, such that separate instances are in separate processes.
IN_PROC_BROWSER_TEST_F(AppApiTest, MAYBE_AppProcessInstances) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisablePopupBlocking);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("app_process_instances")));
// Open two tabs in the app, one outside it.
GURL base_url = test_server()->GetURL(
"files/extensions/api_test/app_process_instances/");
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL::Replacements replace_host;
std::string host_str("localhost"); // must stay in scope with replace_host
replace_host.SetHostStr(host_str);
base_url = base_url.ReplaceComponents(replace_host);
// Test both opening a URL in a new tab, and opening a tab and then navigating
// it. Either way, app tabs should be considered extension processes, but
// they have no elevated privileges and thus should not have WebUI bindings.
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("path1/empty.html"), NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
EXPECT_TRUE(browser()->GetTabContentsAt(1)->render_view_host()->process()->
is_extension_process());
EXPECT_FALSE(browser()->GetTabContentsAt(1)->web_ui());
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path2/empty.html"));
EXPECT_TRUE(browser()->GetTabContentsAt(2)->render_view_host()->process()->
is_extension_process());
EXPECT_FALSE(browser()->GetTabContentsAt(2)->web_ui());
// We should have opened 2 new extension tabs. Including the original blank
// tab, we now have 3 tabs. The two app tabs should not be in the same
// process, since they do not have the background permission. (Thus, we want
// to separate them to improve responsiveness.)
ASSERT_EQ(3, browser()->tab_count());
RenderViewHost* host1 = browser()->GetTabContentsAt(1)->render_view_host();
RenderViewHost* host2 = browser()->GetTabContentsAt(2)->render_view_host();
EXPECT_NE(host1->process(), host2->process());
// Opening tabs with window.open should keep the page in the opener's process.
ASSERT_EQ(1u, BrowserList::GetBrowserCount(browser()->profile()));
WindowOpenHelper(browser(), host1,
base_url.Resolve("path1/empty.html"), true);
WindowOpenHelper(browser(), host2,
base_url.Resolve("path2/empty.html"), true);
}
// Tests that app process switching works properly in the following scenario:
// 1. navigate to a page1 in the app
// 2. page1 redirects to a page2 outside the app extent (ie, "/server-redirect")
// 3. page2 redirects back to a page in the app
// The final navigation should end up in the app process.
// See http://crbug.com/61757
IN_PROC_BROWSER_TEST_F(AppApiTest, AppProcessRedirectBack) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisablePopupBlocking);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app_process")));
// Open two tabs in the app.
GURL base_url = test_server()->GetURL(
"files/extensions/api_test/app_process/");
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL::Replacements replace_host;
std::string host_str("localhost"); // must stay in scope with replace_host
replace_host.SetHostStr(host_str);
base_url = base_url.ReplaceComponents(replace_host);
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path1/empty.html"));
browser()->NewTab();
// Wait until the second tab finishes its redirect train (2 hops).
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
browser(), base_url.Resolve("path1/redirect.html"), 2);
// 3 tabs, including the initial about:blank. The last 2 should be the same
// process.
ASSERT_EQ(3, browser()->tab_count());
EXPECT_EQ("/files/extensions/api_test/app_process/path1/empty.html",
browser()->GetTabContentsAt(2)->controller().
GetLastCommittedEntry()->url().path());
RenderViewHost* host = browser()->GetTabContentsAt(1)->render_view_host();
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
}
// Ensure that reloading a URL after installing or uninstalling it as an app
// correctly swaps the process. (http://crbug.com/80621)
IN_PROC_BROWSER_TEST_F(AppApiTest, ReloadIntoAppProcess) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisablePopupBlocking);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL::Replacements replace_host;
std::string host_str("localhost"); // must stay in scope with replace_host
replace_host.SetHostStr(host_str);
GURL base_url = test_server()->GetURL(
"files/extensions/api_test/app_process/");
base_url = base_url.ReplaceComponents(replace_host);
// Load an app URL before loading the app.
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path1/empty.html"));
TabContents* contents = browser()->GetTabContentsAt(0);
EXPECT_FALSE(contents->render_view_host()->process()->is_extension_process());
// Load app and reload page.
const Extension* app =
LoadExtension(test_data_dir_.AppendASCII("app_process"));
ASSERT_TRUE(app);
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path1/empty.html"));
EXPECT_TRUE(contents->render_view_host()->process()->is_extension_process());
// Disable app and reload page.
DisableExtension(app->id());
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path1/empty.html"));
EXPECT_FALSE(contents->render_view_host()->process()->is_extension_process());
// Enable app and reload via JavaScript.
EnableExtension(app->id());
ASSERT_TRUE(ui_test_utils::ExecuteJavaScript(contents->render_view_host(),
L"", L"location.reload();"));
ui_test_utils::WaitForNavigation(&contents->controller());
EXPECT_TRUE(contents->render_view_host()->process()->is_extension_process());
// Disable app and reload via JavaScript.
DisableExtension(app->id());
ASSERT_TRUE(ui_test_utils::ExecuteJavaScript(contents->render_view_host(),
L"", L"location.reload();"));
ui_test_utils::WaitForNavigation(&contents->controller());
EXPECT_FALSE(contents->render_view_host()->process()->is_extension_process());
}
<|endoftext|> |
<commit_before>//===--- ProtocolConformance.cpp - AST Protocol Conformance -----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the protocol conformance data structures.
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/Fallthrough.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/Decl.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Module.h"
#include "swift/AST/Substitution.h"
#include "swift/AST/Types.h"
#include "swift/AST/TypeWalker.h"
using namespace swift;
void *ProtocolConformance::operator new(size_t bytes, ASTContext &context,
AllocationArena arena,
unsigned alignment) {
return context.Allocate(bytes, alignment, arena);
}
#define CONFORMANCE_SUBCLASS_DISPATCH(Method, Args) \
switch (getKind()) { \
case ProtocolConformanceKind::Normal: \
static_assert(&ProtocolConformance::Method != \
&NormalProtocolConformance::Method, \
"Must override NormalProtocolConformance::" #Method); \
return cast<NormalProtocolConformance>(this)->Method Args; \
case ProtocolConformanceKind::Specialized: \
static_assert(&ProtocolConformance::Method != \
&SpecializedProtocolConformance::Method, \
"Must override SpecializedProtocolConformance::" #Method); \
return cast<SpecializedProtocolConformance>(this)->Method Args; \
case ProtocolConformanceKind::Inherited: \
static_assert(&ProtocolConformance::Method != \
&InheritedProtocolConformance::Method, \
"Must override InheritedProtocolConformance::" #Method); \
return cast<InheritedProtocolConformance>(this)->Method Args; \
}
/// Get the protocol being conformed to.
ProtocolDecl *ProtocolConformance::getProtocol() const {
CONFORMANCE_SUBCLASS_DISPATCH(getProtocol, ())
}
DeclContext *ProtocolConformance::getDeclContext() const {
CONFORMANCE_SUBCLASS_DISPATCH(getDeclContext, ())
}
/// Retrieve the state of this conformance.
ProtocolConformanceState ProtocolConformance::getState() const {
CONFORMANCE_SUBCLASS_DISPATCH(getState, ())
}
const Substitution &
ProtocolConformance::getTypeWitness(AssociatedTypeDecl *assocType,
LazyResolver *resolver) const {
CONFORMANCE_SUBCLASS_DISPATCH(getTypeWitness, (assocType, resolver))
}
ConcreteDeclRef ProtocolConformance::getWitness(ValueDecl *requirement,
LazyResolver *resolver) const {
CONFORMANCE_SUBCLASS_DISPATCH(getWitness, (requirement, resolver))
}
const InheritedConformanceMap &
ProtocolConformance::getInheritedConformances() const {
CONFORMANCE_SUBCLASS_DISPATCH(getInheritedConformances, ())
}
/// Determine whether the witness for the given requirement
/// is either the default definition or was otherwise deduced.
bool ProtocolConformance::usesDefaultDefinition(ValueDecl *requirement) const {
CONFORMANCE_SUBCLASS_DISPATCH(usesDefaultDefinition, (requirement))
}
/// FIXME: This should be an independent property of the conformance.
/// Assuming a BoundGenericType conformance is always for the
/// DeclaredTypeInContext is unsound if we ever add constrained extensions.
static GenericParamList *genericParamListForType(Type ty) {
while (ty) {
if (auto nt = ty->getAs<NominalType>())
ty = nt->getParent();
else
break;
}
if (!ty)
return nullptr;
if (auto bgt = ty->getAs<BoundGenericType>()) {
auto decl = bgt->getDecl();
assert(bgt->isEqual(decl->getDeclaredTypeInContext()) &&
"conformance for constrained generic type not implemented");
return decl->getGenericParams();
}
return nullptr;
}
/// Return the list of generic params that were substituted if this conformance
/// was specialized somewhere along the inheritence chain.
GenericParamList *ProtocolConformance::getSubstitutedGenericParams() const {
const ProtocolConformance *C = this;
bool FoundSpecializedConformance = false;
while (true) {
switch (C->getKind()) {
case ProtocolConformanceKind::Inherited:
// If we have an inherited protocol conformance, grab our inherited
// conformance and continue. Inheritence in it of itself does not yield
// additional type variables.
C = cast<InheritedProtocolConformance>(C)->getInheritedConformance();
continue;
case ProtocolConformanceKind::Specialized:
// If we have a specialized protocol conformance, since we do not support
// currently partial specialization, we know that it can not have any open
// type variables.
C = cast<SpecializedProtocolConformance>(C)->getGenericConformance();
FoundSpecializedConformance = true;
continue;
case ProtocolConformanceKind::Normal:
// If we have a normal protocol conformance and we have not seen a
// specialized protocol conformance yet, we know that the normal protocol
// conformance can only contain open types. Bail.
if (!FoundSpecializedConformance)
return nullptr;
// Otherwise, this must be the original conformance containing the
// specialized generic parameters. Attempt to create the param list.
return genericParamListForType(C->getType());
}
}
}
GenericParamList *ProtocolConformance::getGenericParams() const {
const ProtocolConformance *C = this;
while (true) {
switch (C->getKind()) {
case ProtocolConformanceKind::Inherited:
// If we have an inherited protocol conformance, grab our inherited
// conformance and continue.
C = cast<InheritedProtocolConformance>(C)->getInheritedConformance();
continue;
case ProtocolConformanceKind::Specialized:
// If we have a specialized protocol conformance, since we do not support
// currently partial specialization, we know that it can not have any open
// type variables.
return nullptr;
case ProtocolConformanceKind::Normal:
// If we have a normal protocol conformance, attempt to look up its open
// generic type variables.
return genericParamListForType(C->getType());
}
}
}
Type ProtocolConformance::getInterfaceType() const {
switch (getKind()) {
case ProtocolConformanceKind::Normal:
// FIXME: This should be the type stored in the protocol conformance.
// Assuming a generic conformance is always for the DeclaredTypeInContext
// is unsound if we ever add constrained extensions.
return getType()->getNominalOrBoundGenericNominal()
->getDeclaredInterfaceType();
case ProtocolConformanceKind::Inherited:
return cast<InheritedProtocolConformance>(this)->getInheritedConformance()
->getInterfaceType();
case ProtocolConformanceKind::Specialized:
// Assume a specialized conformance is fully applied.
return getType();
}
}
GenericSignature *ProtocolConformance::getGenericSignature() const {
// FIXME: Should be an independent property of the conformance.
// Assuming a BoundGenericType conformance is always for the
// DeclaredTypeInContext is unsound if we ever add constrained extensions.
return getType()->getNominalOrBoundGenericNominal()
->getGenericSignatureOfContext();
}
const Substitution &NormalProtocolConformance::getTypeWitness(
AssociatedTypeDecl *assocType,
LazyResolver *resolver) const {
auto known = TypeWitnesses.find(assocType);
if (known == TypeWitnesses.end()) {
assert(resolver && "Unable to resolve type witness");
resolver->resolveTypeWitness(this, assocType);
known = TypeWitnesses.find(assocType);
assert(known != TypeWitnesses.end() && "Didn't resolve witness?");
}
return known->second;
}
void NormalProtocolConformance::setTypeWitness(
AssociatedTypeDecl *assocType,
const Substitution &substitution) const {
assert(getProtocol() == cast<ProtocolDecl>(assocType->getDeclContext()) &&
"associated type in wrong protocol");
assert(TypeWitnesses.count(assocType) == 0 && "Type witness already known");
assert(!isComplete() && "Conformance already complete?");
TypeWitnesses[assocType] = substitution;
}
/// Retrieve the value witness corresponding to the given requirement.
ConcreteDeclRef NormalProtocolConformance::getWitness(
ValueDecl *requirement,
LazyResolver *resolver) const {
assert(!isa<AssociatedTypeDecl>(requirement) && "Request type witness");
auto known = Mapping.find(requirement);
if (known == Mapping.end()) {
assert(resolver && "Unable to resolve witness without resolver");
resolver->resolveWitness(this, requirement);
known = Mapping.find(requirement);
assert(known != Mapping.end() && "Resolver did not resolve requirement");
}
return known->second;
}
void NormalProtocolConformance::setWitness(ValueDecl *requirement,
ConcreteDeclRef witness) const {
assert(!isa<AssociatedTypeDecl>(requirement) && "Request type witness");
assert(getProtocol() == cast<ProtocolDecl>(requirement->getDeclContext()) &&
"requirement in wrong protocol");
assert(Mapping.count(requirement) == 0 && "Witness already known");
assert(!isComplete() && "Conformance already complete?");
Mapping[requirement] = witness;
}
const Substitution &SpecializedProtocolConformance::getTypeWitness(
AssociatedTypeDecl *assocType,
LazyResolver *resolver) const {
// If we've already created this type witness, return it.
auto known = TypeWitnesses.find(assocType);
if (known != TypeWitnesses.end()) {
return known->second;
}
// Otherwise, perform substitutions to create this witness now.
TypeSubstitutionMap substitutionMap = GenericConformance->getGenericParams()
->getSubstitutionMap(GenericSubstitutions);
auto &genericWitness
= GenericConformance->getTypeWitness(assocType, resolver);
auto conformingDC = getDeclContext();
auto conformingModule = conformingDC->getParentModule();
auto specializedType
= genericWitness.getReplacement().subst(conformingModule,
substitutionMap,
/*ignoreMissing=*/false,
resolver);
// If the type witness was unchanged, just copy it directly.
if (specializedType.getPointer() == genericWitness.getReplacement().getPointer()) {
TypeWitnesses[assocType] = genericWitness;
return TypeWitnesses[assocType];
}
// Gather the conformances for the type witness. These should never fail.
SmallVector<ProtocolConformance *, 4> conformances;
auto archetype = genericWitness.getArchetype();
for (auto proto : archetype->getConformsTo()) {
auto conforms = conformingModule->lookupConformance(specializedType, proto,
resolver);
assert((conforms.getInt() == ConformanceKind::Conforms ||
specializedType->is<TypeVariableType>() ||
specializedType->is<DependentMemberType>()) &&
"Improperly checked substitution");
conformances.push_back(conforms.getPointer());
}
// Form the substitution.
auto &ctx = assocType->getASTContext();
TypeWitnesses[assocType] = Substitution{archetype, specializedType,
ctx.AllocateCopy(conformances)};
return TypeWitnesses[assocType];
}
ConcreteDeclRef
SpecializedProtocolConformance::getWitness(ValueDecl *requirement,
LazyResolver *resolver) const {
// FIXME: Apply substitutions here!
return GenericConformance->getWitness(requirement, resolver);
}
const NormalProtocolConformance *
ProtocolConformance::getRootNormalConformance() const {
const ProtocolConformance *C = this;
while (!isa<NormalProtocolConformance>(C)) {
switch (C->getKind()) {
case ProtocolConformanceKind::Normal:
llvm_unreachable("should have broken out of loop");
case ProtocolConformanceKind::Inherited:
C = cast<InheritedProtocolConformance>(C)
->getInheritedConformance();
break;
case ProtocolConformanceKind::Specialized:
C = cast<SpecializedProtocolConformance>(C)
->getGenericConformance();
break;
}
}
return cast<NormalProtocolConformance>(C);
}
ProtocolConformance *ProtocolConformance::subst(Module *module,
Type substType,
ArrayRef<Substitution> subs,
TypeSubstitutionMap &subMap,
ArchetypeConformanceMap &conformanceMap) {
if (getType()->isEqual(substType))
return this;
switch (getKind()) {
case ProtocolConformanceKind::Normal:
if (substType->isSpecialized()) {
assert(getType()->isSpecialized()
&& "substitution mapped non-specialized to specialized?!");
assert(getType()->getNominalOrBoundGenericNominal()
== substType->getNominalOrBoundGenericNominal()
&& "substitution mapped to different nominal?!");
return module->getASTContext()
.getSpecializedConformance(substType, this,
substType->gatherAllSubstitutions(module, nullptr));
}
assert(substType->isEqual(getType())
&& "substitution changed non-specialized type?!");
return this;
case ProtocolConformanceKind::Inherited: {
// Substitute the base.
ProtocolConformance *newBase
= cast<InheritedProtocolConformance>(this)->getInheritedConformance()
->subst(module, substType, subs, subMap, conformanceMap);
return module->getASTContext()
.getInheritedConformance(substType, newBase);
}
case ProtocolConformanceKind::Specialized: {
// Substitute the substitutions in the specialized conformance.
auto spec = cast<SpecializedProtocolConformance>(this);
SmallVector<Substitution, 8> newSubs;
newSubs.reserve(spec->getGenericSubstitutions().size());
for (auto &sub : spec->getGenericSubstitutions())
newSubs.push_back(sub.subst(module, subs, subMap, conformanceMap));
auto ctxNewSubs = module->getASTContext().AllocateCopy(newSubs);
return module->getASTContext()
.getSpecializedConformance(substType, spec->getGenericConformance(),
ctxNewSubs);
}
}
}
ProtocolConformance *
ProtocolConformance::getInheritedConformance(ProtocolDecl *protocol) const {
// Preserve specialization through this operation by peeling off the
// substitutions from a specialized conformance so we can apply them later.
const ProtocolConformance *unspecialized;
ArrayRef<Substitution> subs;
switch (getKind()) {
case ProtocolConformanceKind::Specialized: {
auto spec = cast<SpecializedProtocolConformance>(this);
unspecialized = spec->getGenericConformance();
subs = spec->getGenericSubstitutions();
break;
}
case ProtocolConformanceKind::Normal:
case ProtocolConformanceKind::Inherited:
unspecialized = this;
break;
}
ProtocolConformance *foundInherited;
// Search for the inherited conformance among our immediate parents.
auto &inherited = unspecialized->getInheritedConformances();
auto known = inherited.find(protocol);
if (known != inherited.end()) {
foundInherited = known->second;
goto found_inherited;
}
// If not there, the inherited conformance must be available through one of
// our parents.
for (auto &inheritedMapping : inherited)
if (inheritedMapping.first->inheritsFrom(protocol)) {
foundInherited = inheritedMapping.second->
getInheritedConformance(protocol);
goto found_inherited;
}
llvm_unreachable("Can't find the inherited conformance.");
found_inherited:
// Specialize the inherited conformance, if necessary.
if (!subs.empty()) {
return getType()->getASTContext()
.getSpecializedConformance(getType(), foundInherited, subs);
}
assert(getType()->isEqual(foundInherited->getType())
&& "inherited conformance does not match type");
return foundInherited;
}
<commit_msg>When determining the generic parameters used in a conformance, query the DeclContext.<commit_after>//===--- ProtocolConformance.cpp - AST Protocol Conformance -----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the protocol conformance data structures.
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/Fallthrough.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/Decl.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Module.h"
#include "swift/AST/Substitution.h"
#include "swift/AST/Types.h"
#include "swift/AST/TypeWalker.h"
using namespace swift;
void *ProtocolConformance::operator new(size_t bytes, ASTContext &context,
AllocationArena arena,
unsigned alignment) {
return context.Allocate(bytes, alignment, arena);
}
#define CONFORMANCE_SUBCLASS_DISPATCH(Method, Args) \
switch (getKind()) { \
case ProtocolConformanceKind::Normal: \
static_assert(&ProtocolConformance::Method != \
&NormalProtocolConformance::Method, \
"Must override NormalProtocolConformance::" #Method); \
return cast<NormalProtocolConformance>(this)->Method Args; \
case ProtocolConformanceKind::Specialized: \
static_assert(&ProtocolConformance::Method != \
&SpecializedProtocolConformance::Method, \
"Must override SpecializedProtocolConformance::" #Method); \
return cast<SpecializedProtocolConformance>(this)->Method Args; \
case ProtocolConformanceKind::Inherited: \
static_assert(&ProtocolConformance::Method != \
&InheritedProtocolConformance::Method, \
"Must override InheritedProtocolConformance::" #Method); \
return cast<InheritedProtocolConformance>(this)->Method Args; \
}
/// Get the protocol being conformed to.
ProtocolDecl *ProtocolConformance::getProtocol() const {
CONFORMANCE_SUBCLASS_DISPATCH(getProtocol, ())
}
DeclContext *ProtocolConformance::getDeclContext() const {
CONFORMANCE_SUBCLASS_DISPATCH(getDeclContext, ())
}
/// Retrieve the state of this conformance.
ProtocolConformanceState ProtocolConformance::getState() const {
CONFORMANCE_SUBCLASS_DISPATCH(getState, ())
}
const Substitution &
ProtocolConformance::getTypeWitness(AssociatedTypeDecl *assocType,
LazyResolver *resolver) const {
CONFORMANCE_SUBCLASS_DISPATCH(getTypeWitness, (assocType, resolver))
}
ConcreteDeclRef ProtocolConformance::getWitness(ValueDecl *requirement,
LazyResolver *resolver) const {
CONFORMANCE_SUBCLASS_DISPATCH(getWitness, (requirement, resolver))
}
const InheritedConformanceMap &
ProtocolConformance::getInheritedConformances() const {
CONFORMANCE_SUBCLASS_DISPATCH(getInheritedConformances, ())
}
/// Determine whether the witness for the given requirement
/// is either the default definition or was otherwise deduced.
bool ProtocolConformance::usesDefaultDefinition(ValueDecl *requirement) const {
CONFORMANCE_SUBCLASS_DISPATCH(usesDefaultDefinition, (requirement))
}
/// Return the list of generic params that were substituted if this conformance
/// was specialized somewhere along the inheritence chain.
GenericParamList *ProtocolConformance::getSubstitutedGenericParams() const {
const ProtocolConformance *C = this;
bool FoundSpecializedConformance = false;
while (true) {
switch (C->getKind()) {
case ProtocolConformanceKind::Inherited:
// If we have an inherited protocol conformance, grab our inherited
// conformance and continue. Inheritence in it of itself does not yield
// additional type variables.
C = cast<InheritedProtocolConformance>(C)->getInheritedConformance();
continue;
case ProtocolConformanceKind::Specialized:
// If we have a specialized protocol conformance, since we do not support
// currently partial specialization, we know that it can not have any open
// type variables.
C = cast<SpecializedProtocolConformance>(C)->getGenericConformance();
FoundSpecializedConformance = true;
continue;
case ProtocolConformanceKind::Normal:
// If we have a normal protocol conformance and we have not seen a
// specialized protocol conformance yet, we know that the normal protocol
// conformance can only contain open types. Bail.
if (!FoundSpecializedConformance)
return nullptr;
// Otherwise, this must be the original conformance containing the
// specialized generic parameters. Attempt to create the param list.
return cast<NormalProtocolConformance>(C)->getDeclContext()
->getGenericParamsOfContext();
}
}
}
GenericParamList *ProtocolConformance::getGenericParams() const {
const ProtocolConformance *C = this;
while (true) {
switch (C->getKind()) {
case ProtocolConformanceKind::Inherited:
// If we have an inherited protocol conformance, grab our inherited
// conformance and continue.
C = cast<InheritedProtocolConformance>(C)->getInheritedConformance();
continue;
case ProtocolConformanceKind::Specialized:
// If we have a specialized protocol conformance, since we do not support
// currently partial specialization, we know that it can not have any open
// type variables.
return nullptr;
case ProtocolConformanceKind::Normal:
// If we have a normal protocol conformance, attempt to look up its open
// generic type variables.
return cast<NormalProtocolConformance>(C)->getDeclContext()
->getGenericParamsOfContext();
}
}
}
Type ProtocolConformance::getInterfaceType() const {
switch (getKind()) {
case ProtocolConformanceKind::Normal:
// FIXME: This should be the type stored in the protocol conformance.
// Assuming a generic conformance is always for the DeclaredTypeInContext
// is unsound if we ever add constrained extensions.
return getType()->getNominalOrBoundGenericNominal()
->getDeclaredInterfaceType();
case ProtocolConformanceKind::Inherited:
return cast<InheritedProtocolConformance>(this)->getInheritedConformance()
->getInterfaceType();
case ProtocolConformanceKind::Specialized:
// Assume a specialized conformance is fully applied.
return getType();
}
}
GenericSignature *ProtocolConformance::getGenericSignature() const {
// FIXME: Should be an independent property of the conformance.
// Assuming a BoundGenericType conformance is always for the
// DeclaredTypeInContext is unsound if we ever add constrained extensions.
return getType()->getNominalOrBoundGenericNominal()
->getGenericSignatureOfContext();
}
const Substitution &NormalProtocolConformance::getTypeWitness(
AssociatedTypeDecl *assocType,
LazyResolver *resolver) const {
auto known = TypeWitnesses.find(assocType);
if (known == TypeWitnesses.end()) {
assert(resolver && "Unable to resolve type witness");
resolver->resolveTypeWitness(this, assocType);
known = TypeWitnesses.find(assocType);
assert(known != TypeWitnesses.end() && "Didn't resolve witness?");
}
return known->second;
}
void NormalProtocolConformance::setTypeWitness(
AssociatedTypeDecl *assocType,
const Substitution &substitution) const {
assert(getProtocol() == cast<ProtocolDecl>(assocType->getDeclContext()) &&
"associated type in wrong protocol");
assert(TypeWitnesses.count(assocType) == 0 && "Type witness already known");
assert(!isComplete() && "Conformance already complete?");
TypeWitnesses[assocType] = substitution;
}
/// Retrieve the value witness corresponding to the given requirement.
ConcreteDeclRef NormalProtocolConformance::getWitness(
ValueDecl *requirement,
LazyResolver *resolver) const {
assert(!isa<AssociatedTypeDecl>(requirement) && "Request type witness");
auto known = Mapping.find(requirement);
if (known == Mapping.end()) {
assert(resolver && "Unable to resolve witness without resolver");
resolver->resolveWitness(this, requirement);
known = Mapping.find(requirement);
assert(known != Mapping.end() && "Resolver did not resolve requirement");
}
return known->second;
}
void NormalProtocolConformance::setWitness(ValueDecl *requirement,
ConcreteDeclRef witness) const {
assert(!isa<AssociatedTypeDecl>(requirement) && "Request type witness");
assert(getProtocol() == cast<ProtocolDecl>(requirement->getDeclContext()) &&
"requirement in wrong protocol");
assert(Mapping.count(requirement) == 0 && "Witness already known");
assert(!isComplete() && "Conformance already complete?");
Mapping[requirement] = witness;
}
const Substitution &SpecializedProtocolConformance::getTypeWitness(
AssociatedTypeDecl *assocType,
LazyResolver *resolver) const {
// If we've already created this type witness, return it.
auto known = TypeWitnesses.find(assocType);
if (known != TypeWitnesses.end()) {
return known->second;
}
// Otherwise, perform substitutions to create this witness now.
TypeSubstitutionMap substitutionMap = GenericConformance->getGenericParams()
->getSubstitutionMap(GenericSubstitutions);
auto &genericWitness
= GenericConformance->getTypeWitness(assocType, resolver);
auto conformingDC = getDeclContext();
auto conformingModule = conformingDC->getParentModule();
auto specializedType
= genericWitness.getReplacement().subst(conformingModule,
substitutionMap,
/*ignoreMissing=*/false,
resolver);
// If the type witness was unchanged, just copy it directly.
if (specializedType.getPointer() == genericWitness.getReplacement().getPointer()) {
TypeWitnesses[assocType] = genericWitness;
return TypeWitnesses[assocType];
}
// Gather the conformances for the type witness. These should never fail.
SmallVector<ProtocolConformance *, 4> conformances;
auto archetype = genericWitness.getArchetype();
for (auto proto : archetype->getConformsTo()) {
auto conforms = conformingModule->lookupConformance(specializedType, proto,
resolver);
assert((conforms.getInt() == ConformanceKind::Conforms ||
specializedType->is<TypeVariableType>() ||
specializedType->is<DependentMemberType>()) &&
"Improperly checked substitution");
conformances.push_back(conforms.getPointer());
}
// Form the substitution.
auto &ctx = assocType->getASTContext();
TypeWitnesses[assocType] = Substitution{archetype, specializedType,
ctx.AllocateCopy(conformances)};
return TypeWitnesses[assocType];
}
ConcreteDeclRef
SpecializedProtocolConformance::getWitness(ValueDecl *requirement,
LazyResolver *resolver) const {
// FIXME: Apply substitutions here!
return GenericConformance->getWitness(requirement, resolver);
}
const NormalProtocolConformance *
ProtocolConformance::getRootNormalConformance() const {
const ProtocolConformance *C = this;
while (!isa<NormalProtocolConformance>(C)) {
switch (C->getKind()) {
case ProtocolConformanceKind::Normal:
llvm_unreachable("should have broken out of loop");
case ProtocolConformanceKind::Inherited:
C = cast<InheritedProtocolConformance>(C)
->getInheritedConformance();
break;
case ProtocolConformanceKind::Specialized:
C = cast<SpecializedProtocolConformance>(C)
->getGenericConformance();
break;
}
}
return cast<NormalProtocolConformance>(C);
}
ProtocolConformance *ProtocolConformance::subst(Module *module,
Type substType,
ArrayRef<Substitution> subs,
TypeSubstitutionMap &subMap,
ArchetypeConformanceMap &conformanceMap) {
if (getType()->isEqual(substType))
return this;
switch (getKind()) {
case ProtocolConformanceKind::Normal:
if (substType->isSpecialized()) {
assert(getType()->isSpecialized()
&& "substitution mapped non-specialized to specialized?!");
assert(getType()->getNominalOrBoundGenericNominal()
== substType->getNominalOrBoundGenericNominal()
&& "substitution mapped to different nominal?!");
return module->getASTContext()
.getSpecializedConformance(substType, this,
substType->gatherAllSubstitutions(module, nullptr));
}
assert(substType->isEqual(getType())
&& "substitution changed non-specialized type?!");
return this;
case ProtocolConformanceKind::Inherited: {
// Substitute the base.
ProtocolConformance *newBase
= cast<InheritedProtocolConformance>(this)->getInheritedConformance()
->subst(module, substType, subs, subMap, conformanceMap);
return module->getASTContext()
.getInheritedConformance(substType, newBase);
}
case ProtocolConformanceKind::Specialized: {
// Substitute the substitutions in the specialized conformance.
auto spec = cast<SpecializedProtocolConformance>(this);
SmallVector<Substitution, 8> newSubs;
newSubs.reserve(spec->getGenericSubstitutions().size());
for (auto &sub : spec->getGenericSubstitutions())
newSubs.push_back(sub.subst(module, subs, subMap, conformanceMap));
auto ctxNewSubs = module->getASTContext().AllocateCopy(newSubs);
return module->getASTContext()
.getSpecializedConformance(substType, spec->getGenericConformance(),
ctxNewSubs);
}
}
}
ProtocolConformance *
ProtocolConformance::getInheritedConformance(ProtocolDecl *protocol) const {
// Preserve specialization through this operation by peeling off the
// substitutions from a specialized conformance so we can apply them later.
const ProtocolConformance *unspecialized;
ArrayRef<Substitution> subs;
switch (getKind()) {
case ProtocolConformanceKind::Specialized: {
auto spec = cast<SpecializedProtocolConformance>(this);
unspecialized = spec->getGenericConformance();
subs = spec->getGenericSubstitutions();
break;
}
case ProtocolConformanceKind::Normal:
case ProtocolConformanceKind::Inherited:
unspecialized = this;
break;
}
ProtocolConformance *foundInherited;
// Search for the inherited conformance among our immediate parents.
auto &inherited = unspecialized->getInheritedConformances();
auto known = inherited.find(protocol);
if (known != inherited.end()) {
foundInherited = known->second;
goto found_inherited;
}
// If not there, the inherited conformance must be available through one of
// our parents.
for (auto &inheritedMapping : inherited)
if (inheritedMapping.first->inheritsFrom(protocol)) {
foundInherited = inheritedMapping.second->
getInheritedConformance(protocol);
goto found_inherited;
}
llvm_unreachable("Can't find the inherited conformance.");
found_inherited:
// Specialize the inherited conformance, if necessary.
if (!subs.empty()) {
return getType()->getASTContext()
.getSpecializedConformance(getType(), foundInherited, subs);
}
assert(getType()->isEqual(foundInherited->getType())
&& "inherited conformance does not match type");
return foundInherited;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013-2014 Flowgrammable.org
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS"
// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing
// permissions and limitations under the License.
#include <iostream>
#include <map>
#include <typeinfo>
#include <freeflow/sys/selector.hpp>
#include <freeflow/sys/socket.hpp>
#include <freeflow/sys/file.hpp>
#include <freeflow/sys/reactor.hpp>
#include <freeflow/nbi/controller.hpp>
#include "acceptor.hpp"
#include "connection.hpp"
#include "noflow.hpp"
#include "bridge.hpp"
using namespace std;
using namespace freeflow;
using namespace nocontrol;
// This handler is responsible for watching for the end of
// file from an open file.
//
// This is primarily intended for debugging purposes. Really, we should
// be trapping signals and shutting down that way instead.
struct Terminator : Resource_handler<Resource> {
Terminator(int fd)
: Resource_handler<Resource>(fd) { }
Terminator(Resource&& f)
: Resource_handler<Resource>(std::move(f)) { }
// If there is no more data to read, indicate that we want
// to terminate the reactor loop.
bool on_read(Reactor& r) {
char c[1024];
if (read(rc(), &c, 1024) <= 0) {
std::cout << "shutting down\n";
r.stop();
return false;
}
return true;
}
};
int
main(int argc, char* argv[]) {
// Create the controller for NBI applications.
Controller ctrl;
// Load default applications.
ctrl.load<Noflow>();
// Configure the switch address.
Address addr(Ipv4_addr::any, 9001);
Acceptor acc(ctrl, addr);
// Listen for ^D on stdin so we can shutdown easily.
Terminator term(0);
// Run the reactor loop.
//
// FIXME: Consider moving all of the reactor facilities into
// the NBI library.
Reactor r;
r.add_handler(&term);
r.add_handler(&acc);
r.run();
// FIXME: This should be part of the controller's destructor.
ctrl.unload<Bridge>();
return 0;
}
<commit_msg>Fixing shutdown bug.<commit_after>// Copyright (c) 2013-2014 Flowgrammable.org
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS"
// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing
// permissions and limitations under the License.
#include <iostream>
#include <map>
#include <typeinfo>
#include <freeflow/sys/selector.hpp>
#include <freeflow/sys/socket.hpp>
#include <freeflow/sys/file.hpp>
#include <freeflow/sys/reactor.hpp>
#include <freeflow/nbi/controller.hpp>
#include "acceptor.hpp"
#include "connection.hpp"
#include "noflow.hpp"
#include "bridge.hpp"
using namespace std;
using namespace freeflow;
using namespace nocontrol;
// This handler is responsible for watching for the end of
// file from an open file.
//
// This is primarily intended for debugging purposes. Really, we should
// be trapping signals and shutting down that way instead.
struct Terminator : Resource_handler<Resource> {
Terminator(int fd)
: Resource_handler<Resource>(fd) { }
Terminator(Resource&& f)
: Resource_handler<Resource>(std::move(f)) { }
// If there is no more data to read, indicate that we want
// to terminate the reactor loop.
bool on_read(Reactor& r) {
char c[1024];
if (read(rc(), &c, 1024) <= 0) {
std::cout << "shutting down\n";
r.stop();
return false;
}
return true;
}
};
int
main(int argc, char* argv[]) {
// Create the controller for NBI applications.
Controller ctrl;
// Load default applications.
ctrl.load<Noflow>();
// Configure the switch address.
Address addr(Ipv4_addr::any, 9001);
Acceptor acc(ctrl, addr);
// Listen for ^D on stdin so we can shutdown easily.
Terminator term(0);
// Run the reactor loop.
//
// FIXME: Consider moving all of the reactor facilities into
// the NBI library.
Reactor r;
r.add_handler(&term);
r.add_handler(&acc);
r.run();
// FIXME: This should be part of the controller's destructor.
ctrl.unload<Noflow>();
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Fix possible uninitialized variable if all frames in the .ico are smaller than the desired size.<commit_after><|endoftext|> |
<commit_before>#include <cppunit/extensions/HelperMacros.h>
#include "BVect.hpp"
class BVectTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(BVectTest);
CPPUNIT_TEST(testDominance);
CPPUNIT_TEST(testWeakDominance);
CPPUNIT_TEST(testStrictDominance);
CPPUNIT_TEST_SUITE_END();
private:
BVect* a;
BVect* b;
BVect* c;
BVect* d;
public:
void setUp() {
std::vector<double> x;
a = new BVect(1, 2, x);
b = new BVect(2, 1, x);
c = new BVect(3, 3, x);
d = new BVect(2, 2, x);
}
void tearDown() {
delete a;
delete b;
delete c;
delete d;
}
void testDominance() {
CPPUNIT_ASSERT(!a->dominates(*a));
CPPUNIT_ASSERT(!a->dominates(*b));
CPPUNIT_ASSERT(a->dominates(*c));
CPPUNIT_ASSERT(a->dominates(*d));
CPPUNIT_ASSERT(!b->dominates(*a));
CPPUNIT_ASSERT(!b->dominates(*b));
CPPUNIT_ASSERT(b->dominates(*c));
CPPUNIT_ASSERT(b->dominates(*d));
CPPUNIT_ASSERT(!c->dominates(*a));
CPPUNIT_ASSERT(!c->dominates(*b));
CPPUNIT_ASSERT(!c->dominates(*c));
CPPUNIT_ASSERT(!c->dominates(*d));
CPPUNIT_ASSERT(!d->dominates(*a));
CPPUNIT_ASSERT(!d->dominates(*b));
CPPUNIT_ASSERT(d->dominates(*c));
CPPUNIT_ASSERT(!d->dominates(*d));
}
void testWeakDominance() {
CPPUNIT_ASSERT(a->weaklyDominates(*a));
CPPUNIT_ASSERT(!a->weaklyDominates(*b));
CPPUNIT_ASSERT(a->weaklyDominates(*c));
CPPUNIT_ASSERT(a->weaklyDominates(*d));
CPPUNIT_ASSERT(!b->weaklyDominates(*a));
CPPUNIT_ASSERT(b->weaklyDominates(*b));
CPPUNIT_ASSERT(b->weaklyDominates(*c));
CPPUNIT_ASSERT(b->weaklyDominates(*d));
CPPUNIT_ASSERT(!c->weaklyDominates(*a));
CPPUNIT_ASSERT(!c->weaklyDominates(*b));
CPPUNIT_ASSERT(c->weaklyDominates(*c));
CPPUNIT_ASSERT(!c->weaklyDominates(*d));
CPPUNIT_ASSERT(!d->weaklyDominates(*a));
CPPUNIT_ASSERT(!d->weaklyDominates(*b));
CPPUNIT_ASSERT(d->weaklyDominates(*c));
CPPUNIT_ASSERT(d->weaklyDominates(*d));
}
void testStrictDominance() {
CPPUNIT_ASSERT(!a->strictlyDominates(*a));
CPPUNIT_ASSERT(!a->strictlyDominates(*b));
CPPUNIT_ASSERT(a->strictlyDominates(*c));
CPPUNIT_ASSERT(!a->strictlyDominates(*d));
CPPUNIT_ASSERT(!b->strictlyDominates(*a));
CPPUNIT_ASSERT(!b->strictlyDominates(*b));
CPPUNIT_ASSERT(b->strictlyDominates(*c));
CPPUNIT_ASSERT(!b->strictlyDominates(*d));
CPPUNIT_ASSERT(!c->strictlyDominates(*a));
CPPUNIT_ASSERT(!c->strictlyDominates(*b));
CPPUNIT_ASSERT(!c->strictlyDominates(*c));
CPPUNIT_ASSERT(!c->strictlyDominates(*d));
CPPUNIT_ASSERT(!d->strictlyDominates(*a));
CPPUNIT_ASSERT(!d->strictlyDominates(*b));
CPPUNIT_ASSERT(d->strictlyDominates(*c));
CPPUNIT_ASSERT(!d->strictlyDominates(*d));
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(BVectTest);
<commit_msg>BVect: Add test for area predicates<commit_after>#include <cppunit/extensions/HelperMacros.h>
#include "BVect.hpp"
class BVectTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(BVectTest);
CPPUNIT_TEST(testDominance);
CPPUNIT_TEST(testWeakDominance);
CPPUNIT_TEST(testStrictDominance);
CPPUNIT_TEST(testAreaPredicates);
CPPUNIT_TEST_SUITE_END();
private:
BVect* a;
BVect* b;
BVect* c;
BVect* d;
public:
void setUp() {
std::vector<double> x;
a = new BVect(1, 2, x);
b = new BVect(2, 1, x);
c = new BVect(3, 3, x);
d = new BVect(2, 2, x);
}
void tearDown() {
delete a;
delete b;
delete c;
delete d;
}
void testDominance() {
CPPUNIT_ASSERT(!a->dominates(*a));
CPPUNIT_ASSERT(!a->dominates(*b));
CPPUNIT_ASSERT(a->dominates(*c));
CPPUNIT_ASSERT(a->dominates(*d));
CPPUNIT_ASSERT(!b->dominates(*a));
CPPUNIT_ASSERT(!b->dominates(*b));
CPPUNIT_ASSERT(b->dominates(*c));
CPPUNIT_ASSERT(b->dominates(*d));
CPPUNIT_ASSERT(!c->dominates(*a));
CPPUNIT_ASSERT(!c->dominates(*b));
CPPUNIT_ASSERT(!c->dominates(*c));
CPPUNIT_ASSERT(!c->dominates(*d));
CPPUNIT_ASSERT(!d->dominates(*a));
CPPUNIT_ASSERT(!d->dominates(*b));
CPPUNIT_ASSERT(d->dominates(*c));
CPPUNIT_ASSERT(!d->dominates(*d));
}
void testWeakDominance() {
CPPUNIT_ASSERT(a->weaklyDominates(*a));
CPPUNIT_ASSERT(!a->weaklyDominates(*b));
CPPUNIT_ASSERT(a->weaklyDominates(*c));
CPPUNIT_ASSERT(a->weaklyDominates(*d));
CPPUNIT_ASSERT(!b->weaklyDominates(*a));
CPPUNIT_ASSERT(b->weaklyDominates(*b));
CPPUNIT_ASSERT(b->weaklyDominates(*c));
CPPUNIT_ASSERT(b->weaklyDominates(*d));
CPPUNIT_ASSERT(!c->weaklyDominates(*a));
CPPUNIT_ASSERT(!c->weaklyDominates(*b));
CPPUNIT_ASSERT(c->weaklyDominates(*c));
CPPUNIT_ASSERT(!c->weaklyDominates(*d));
CPPUNIT_ASSERT(!d->weaklyDominates(*a));
CPPUNIT_ASSERT(!d->weaklyDominates(*b));
CPPUNIT_ASSERT(d->weaklyDominates(*c));
CPPUNIT_ASSERT(d->weaklyDominates(*d));
}
void testStrictDominance() {
CPPUNIT_ASSERT(!a->strictlyDominates(*a));
CPPUNIT_ASSERT(!a->strictlyDominates(*b));
CPPUNIT_ASSERT(a->strictlyDominates(*c));
CPPUNIT_ASSERT(!a->strictlyDominates(*d));
CPPUNIT_ASSERT(!b->strictlyDominates(*a));
CPPUNIT_ASSERT(!b->strictlyDominates(*b));
CPPUNIT_ASSERT(b->strictlyDominates(*c));
CPPUNIT_ASSERT(!b->strictlyDominates(*d));
CPPUNIT_ASSERT(!c->strictlyDominates(*a));
CPPUNIT_ASSERT(!c->strictlyDominates(*b));
CPPUNIT_ASSERT(!c->strictlyDominates(*c));
CPPUNIT_ASSERT(!c->strictlyDominates(*d));
CPPUNIT_ASSERT(!d->strictlyDominates(*a));
CPPUNIT_ASSERT(!d->strictlyDominates(*b));
CPPUNIT_ASSERT(d->strictlyDominates(*c));
CPPUNIT_ASSERT(!d->strictlyDominates(*d));
}
void testAreaPredicates() {
CPPUNIT_ASSERT(a->isInA1AreaOf(*b));
CPPUNIT_ASSERT(!a->isInA1AreaOf(*c));
CPPUNIT_ASSERT(!a->isInA1AreaOf(*d));
CPPUNIT_ASSERT(!b->isInA1AreaOf(*a));
CPPUNIT_ASSERT(!b->isInA1AreaOf(*c));
CPPUNIT_ASSERT(!b->isInA1AreaOf(*d));
CPPUNIT_ASSERT(!c->isInA1AreaOf(*a));
CPPUNIT_ASSERT(!c->isInA1AreaOf(*b));
CPPUNIT_ASSERT(!c->isInA1AreaOf(*d));
CPPUNIT_ASSERT(!d->isInA1AreaOf(*a));
CPPUNIT_ASSERT(!d->isInA1AreaOf(*b));
CPPUNIT_ASSERT(!d->isInA1AreaOf(*c));
CPPUNIT_ASSERT(!a->isInA2AreaOf(*b));
CPPUNIT_ASSERT(!a->isInA2AreaOf(*c));
CPPUNIT_ASSERT(!a->isInA2AreaOf(*d));
CPPUNIT_ASSERT(b->isInA2AreaOf(*a));
CPPUNIT_ASSERT(!b->isInA2AreaOf(*c));
CPPUNIT_ASSERT(!b->isInA2AreaOf(*d));
CPPUNIT_ASSERT(!c->isInA2AreaOf(*a));
CPPUNIT_ASSERT(!c->isInA2AreaOf(*b));
CPPUNIT_ASSERT(!c->isInA2AreaOf(*d));
CPPUNIT_ASSERT(!d->isInA2AreaOf(*a));
CPPUNIT_ASSERT(!d->isInA2AreaOf(*b));
CPPUNIT_ASSERT(!d->isInA2AreaOf(*c));
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(BVectTest);
<|endoftext|> |
<commit_before>// @(#)root/test:$Id$
// Author: Rene Brun 19/01/97
////////////////////////////////////////////////////////////////////////
//
// A simple example with a ROOT tree
// =================================
//
// This program creates :
// - a ROOT file
// - a tree
// Additional arguments can be passed to the program to control the flow
// of execution. (see comments describing the arguments in the code).
// Event nevent comp split fill tracks IMT compression
// All arguments are optional. Default is:
// Event 400 1 1 1 400 0 1
//
// In this example, the tree consists of one single "super branch"
// The statement ***tree->Branch("event", &event, 64000,split);*** below
// will parse the structure described in Event.h and will make
// a new branch for each data member of the class if split is set to 1.
// - 9 branches corresponding to the basic types fType, fNtrack,fNseg,
// fNvertex,fFlag,fTemperature,fMeasures,fMatrix,fClosesDistance.
// - 3 branches corresponding to the members of the subobject EventHeader.
// - one branch for each data member of the class Track of TClonesArray.
// - one branch for the TRefArray of high Pt tracks
// - one branch for the TRefArray of muon tracks
// - one branch for the reference pointer to the last track
// - one branch for the object fH (histogram of class TH1F).
//
// if split = 0 only one single branch is created and the complete event
// is serialized in one single buffer.
// if split = -2 the event is split using the old TBranchObject mechanism
// if split = -1 the event is streamed using the old TBranchObject mechanism
// if split > 0 the event is split using the new TBranchElement mechanism.
//
// if comp = 0 no compression at all.
// if comp = 1 event is compressed.
// if comp = 2 same as 1. In addition branches with floats in the TClonesArray
// are also compressed.
// The 4th argument fill can be set to 0 if one wants to time
// the percentage of time spent in creating the event structure and
// not write the event in the file.
// The 5th argument will enable IMT mode (Implicit Multi-Threading), allowing
// ROOT to use multiple threads internally, if enabled.
// The 6th argument allows the user to specify the compression algorithm:
// - 1 - zlib.
// - 2 - LZMA.
// - 3 - "old ROOT algorithm" A variant of zlib; do not use, kept for
// backwards compatability.
// - 4 - LZ4.
// In this example, one loops over nevent events.
// The branch "event" is created at the first event.
// The branch address is set for all other events.
// For each event, the event header is filled and ntrack tracks
// are generated and added to the TClonesArray list.
// For each event the event histogram is saved as well as the list
// of all tracks.
//
// The two TRefArray contain only references to the original tracks owned by
// the TClonesArray fTracks.
//
// The number of events can be given as the first argument to the program.
// By default 400 events are generated.
// The compression option can be activated/deactivated via the second argument.
//
// ---Running/Linking instructions----
// This program consists of the following files and procedures.
// - Event.h event class description
// - Event.C event class implementation
// - MainEvent.C the main program to demo this class might be used (this file)
// - EventCint.C the CINT dictionary for the event and Track classes
// this file is automatically generated by rootcint (see Makefile),
// when the class definition in Event.h is modified.
//
// ---Analyzing the Event.root file with the interactive root
// example of a simple session
// Root > TFile f("Event.root")
// Root > T.Draw("fNtrack") //histogram the number of tracks per event
// Root > T.Draw("fPx") //histogram fPx for all tracks in all events
// Root > T.Draw("fXfirst:fYfirst","fNtrack>600")
// //scatter-plot for x versus y of first point of each track
// Root > T.Draw("fH.GetRMS()") //histogram of the RMS of the event histogram
//
// Look also in the same directory at the following macros:
// - eventa.C an example how to read the tree
// - eventb.C how to read events conditionally
//
////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include "Riostream.h"
#include "TROOT.h"
#include "TFile.h"
#include "TNetFile.h"
#include "TRandom.h"
#include "TTree.h"
#include "TTreePerfStats.h"
#include "TBranch.h"
#include "TClonesArray.h"
#include "TStopwatch.h"
#include "Event.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
Int_t nevent = 400; // by default create 400 events
Int_t comp = 1; // by default file is compressed
Int_t split = 1; // by default, split Event in sub branches
Int_t write = 1; // by default the tree is filled
Int_t hfill = 0; // by default histograms are not filled
Int_t read = 0;
Int_t arg4 = 1;
Int_t arg5 = 600; //default number of tracks per event
Int_t enable_imt = 0; // Whether to enable IMT mode.
Int_t compAlg = 1; // Allow user to specify underlying compression algorithm.
Int_t netf = 0;
Int_t punzip = 0;
if (argc > 1) nevent = atoi(argv[1]);
if (argc > 2) comp = atoi(argv[2]);
if (argc > 3) split = atoi(argv[3]);
if (argc > 4) arg4 = atoi(argv[4]);
if (argc > 5) arg5 = atoi(argv[5]);
if (argc > 6) enable_imt = atoi(argv[6]);
if (argc > 7) compAlg = atoi(argv[7]);
if (arg4 == 0) { write = 0; hfill = 0; read = 1;}
if (arg4 == 1) { write = 1; hfill = 0;}
if (arg4 == 2) { write = 0; hfill = 0;}
if (arg4 == 10) { write = 0; hfill = 1;}
if (arg4 == 11) { write = 1; hfill = 1;}
if (arg4 == 20) { write = 0; read = 1;} //read sequential
if (arg4 == 21) { write = 0; read = 1; punzip = 1;} //read sequential + parallel unzipping
if (arg4 == 25) { write = 0; read = 2;} //read random
if (arg4 >= 30) { netf = 1; } //use TNetFile
if (arg4 == 30) { write = 0; read = 1;} //netfile + read sequential
if (arg4 == 35) { write = 0; read = 2;} //netfile + read random
if (arg4 == 36) { write = 1; } //netfile + write sequential
Int_t branchStyle = 1; //new style by default
if (split < 0) {branchStyle = 0; split = -1-split;}
#ifdef R__USE_IMT
if (enable_imt) {
ROOT::EnableImplicitMT();
}
#else
if (enable_imt) {
std::cerr << "IMT mode requested, but this version of ROOT "
"is built without IMT support." << std::endl;
return 1;
}
#endif
TFile *hfile;
TTree *tree;
TTreePerfStats *ioperf = nullptr;
Event *event = 0;
// Fill event, header and tracks with some random numbers
// Create a timer object to benchmark this loop
TStopwatch timer;
timer.Start();
Long64_t nb = 0;
Int_t ev;
Int_t bufsize;
Double_t told = 0;
Double_t tnew = 0;
Int_t printev = 100;
if (arg5 < 100) printev = 1000;
if (arg5 < 10) printev = 10000;
// Read case
if (read) {
if (netf) {
hfile = new TNetFile("root://localhost/root/test/EventNet.root");
} else
hfile = new TFile("Event.root");
tree = (TTree*)hfile->Get("T");
TBranch *branch = tree->GetBranch("event");
branch->SetAddress(&event);
Int_t nentries = (Int_t)tree->GetEntries();
nevent = TMath::Min(nevent,nentries);
if (read == 1) { //read sequential
//by setting the read cache to -1 we set it to the AutoFlush value when writing
ioperf = new TTreePerfStats("Perf Stats", tree);
Int_t cachesize = -1;
if (punzip) tree->SetParallelUnzip();
tree->SetCacheSize(cachesize);
tree->SetCacheLearnEntries(1); //one entry is sufficient to learn
tree->SetCacheEntryRange(0,nevent);
for (ev = 0; ev < nevent; ev++) {
tree->LoadTree(ev); //this call is required when using the cache
if (ev%printev == 0) {
tnew = timer.RealTime();
printf("event:%d, rtime=%f s\n",ev,tnew-told);
told=tnew;
timer.Continue();
}
nb += tree->GetEntry(ev); //read complete event in memory
}
ioperf->Finish();
} else { //read random
Int_t evrandom;
for (ev = 0; ev < nevent; ev++) {
if (ev%printev == 0) std::cout<<"event="<<ev<<std::endl;
evrandom = Int_t(nevent*gRandom->Rndm());
nb += tree->GetEntry(evrandom); //read complete event in memory
}
}
} else {
// Write case
// Create a new ROOT binary machine independent file.
// Note that this file may contain any kind of ROOT objects, histograms,
// pictures, graphics objects, detector geometries, tracks, events, etc..
// This file is now becoming the current directory.
if (netf) {
hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file");
} else
hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file");
hfile->SetCompressionLevel(comp);
hfile->SetCompressionAlgorithm(compAlg);
// Create histogram to show write_time in function of time
Float_t curtime = -0.5;
Int_t ntime = nevent / printev;
TH1F *htime = new TH1F("htime", "Real-Time to write versus time", ntime, 0, ntime);
HistogramManager *hm = 0;
if (hfill) {
TDirectory *hdir = new TDirectory("histograms", "all histograms");
hm = new HistogramManager(hdir);
}
// Create a ROOT Tree and one superbranch
tree = new TTree("T","An example of a ROOT tree");
tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written
tree->SetCacheSize(10000000); // set a 10 MBytes cache (useless when writing local files)
bufsize = 64000;
if (split) bufsize /= 4;
event = new Event(); // By setting the value, we own the pointer and must delete it.
TTree::SetBranchStyle(branchStyle);
TBranch *branch = tree->Branch("event", &event, bufsize,split);
branch->SetAutoDelete(kFALSE);
if(split >= 0 && branchStyle) tree->BranchRef();
Float_t ptmin = 1;
for (ev = 0; ev < nevent; ev++) {
if (ev%printev == 0) {
tnew = timer.RealTime();
printf("event:%d, rtime=%f s\n",ev,tnew-told);
htime->Fill(curtime,tnew-told);
curtime += 1;
told=tnew;
timer.Continue();
}
event->Build(ev, arg5, ptmin);
if (write) nb += tree->Fill(); //fill the tree
if (hm) hm->Hfill(event); //fill histograms
}
if (write) {
hfile = tree->GetCurrentFile(); //just in case we switched to a new file
hfile->Write();
tree->Print();
}
}
// We own the event (since we set the branch address explicitly), we need to delete it.
delete event; event = 0;
// Stop timer and print results
timer.Stop();
Float_t mbytes = 0.000001*nb;
Double_t rtime = timer.RealTime();
Double_t ctime = timer.CpuTime();
printf("\n%d events and %lld bytes processed.\n",nevent,nb);
printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime);
if (read) {
tree->PrintCacheStats();
if (ioperf) {
ioperf->Print();
}
printf("You read %f Mbytes/Realtime seconds\n", mbytes / rtime);
printf("You read %f Mbytes/Cputime seconds\n", mbytes / ctime);
} else {
printf("compression level=%d, split=%d, arg4=%d, IMT=%d, compression algorithm=%d\n", comp, split, arg4,
enable_imt, compAlg);
printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime);
printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime);
//printf("file compression factor = %f\n",hfile.GetCompressionFactor());
}
hfile->Close();
return 0;
}
<commit_msg>Make use of TTreePlayer optional.<commit_after>// @(#)root/test:$Id$
// Author: Rene Brun 19/01/97
////////////////////////////////////////////////////////////////////////
//
// A simple example with a ROOT tree
// =================================
//
// This program creates :
// - a ROOT file
// - a tree
// Additional arguments can be passed to the program to control the flow
// of execution. (see comments describing the arguments in the code).
// Event nevent comp split fill tracks IMT compression
// All arguments are optional. Default is:
// Event 400 1 1 1 400 0 1
//
// In this example, the tree consists of one single "super branch"
// The statement ***tree->Branch("event", &event, 64000,split);*** below
// will parse the structure described in Event.h and will make
// a new branch for each data member of the class if split is set to 1.
// - 9 branches corresponding to the basic types fType, fNtrack,fNseg,
// fNvertex,fFlag,fTemperature,fMeasures,fMatrix,fClosesDistance.
// - 3 branches corresponding to the members of the subobject EventHeader.
// - one branch for each data member of the class Track of TClonesArray.
// - one branch for the TRefArray of high Pt tracks
// - one branch for the TRefArray of muon tracks
// - one branch for the reference pointer to the last track
// - one branch for the object fH (histogram of class TH1F).
//
// if split = 0 only one single branch is created and the complete event
// is serialized in one single buffer.
// if split = -2 the event is split using the old TBranchObject mechanism
// if split = -1 the event is streamed using the old TBranchObject mechanism
// if split > 0 the event is split using the new TBranchElement mechanism.
//
// if comp = 0 no compression at all.
// if comp = 1 event is compressed.
// if comp = 2 same as 1. In addition branches with floats in the TClonesArray
// are also compressed.
// The 4th argument fill can be set to 0 if one wants to time
// the percentage of time spent in creating the event structure and
// not write the event in the file.
// The 5th argument will enable IMT mode (Implicit Multi-Threading), allowing
// ROOT to use multiple threads internally, if enabled.
// The 6th argument allows the user to specify the compression algorithm:
// - 1 - zlib.
// - 2 - LZMA.
// - 3 - "old ROOT algorithm" A variant of zlib; do not use, kept for
// backwards compatability.
// - 4 - LZ4.
// In this example, one loops over nevent events.
// The branch "event" is created at the first event.
// The branch address is set for all other events.
// For each event, the event header is filled and ntrack tracks
// are generated and added to the TClonesArray list.
// For each event the event histogram is saved as well as the list
// of all tracks.
//
// The two TRefArray contain only references to the original tracks owned by
// the TClonesArray fTracks.
//
// The number of events can be given as the first argument to the program.
// By default 400 events are generated.
// The compression option can be activated/deactivated via the second argument.
//
// Additionally, if the environment ENABLE_TTREEPERFSTATS is set, then detailed
// statistics about IO performance will be reported.
//
// ---Running/Linking instructions----
// This program consists of the following files and procedures.
// - Event.h event class description
// - Event.C event class implementation
// - MainEvent.C the main program to demo this class might be used (this file)
// - EventCint.C the CINT dictionary for the event and Track classes
// this file is automatically generated by rootcint (see Makefile),
// when the class definition in Event.h is modified.
//
// ---Analyzing the Event.root file with the interactive root
// example of a simple session
// Root > TFile f("Event.root")
// Root > T.Draw("fNtrack") //histogram the number of tracks per event
// Root > T.Draw("fPx") //histogram fPx for all tracks in all events
// Root > T.Draw("fXfirst:fYfirst","fNtrack>600")
// //scatter-plot for x versus y of first point of each track
// Root > T.Draw("fH.GetRMS()") //histogram of the RMS of the event histogram
//
// Look also in the same directory at the following macros:
// - eventa.C an example how to read the tree
// - eventb.C how to read events conditionally
//
////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include "Riostream.h"
#include "TROOT.h"
#include "TFile.h"
#include "TNetFile.h"
#include "TRandom.h"
#include "TTree.h"
#include "TTreePerfStats.h"
#include "TBranch.h"
#include "TClonesArray.h"
#include "TStopwatch.h"
#include "Event.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
Int_t nevent = 400; // by default create 400 events
Int_t comp = 1; // by default file is compressed
Int_t split = 1; // by default, split Event in sub branches
Int_t write = 1; // by default the tree is filled
Int_t hfill = 0; // by default histograms are not filled
Int_t read = 0;
Int_t arg4 = 1;
Int_t arg5 = 600; //default number of tracks per event
Int_t enable_imt = 0; // Whether to enable IMT mode.
Int_t compAlg = 1; // Allow user to specify underlying compression algorithm.
Int_t netf = 0;
Int_t punzip = 0;
if (argc > 1) nevent = atoi(argv[1]);
if (argc > 2) comp = atoi(argv[2]);
if (argc > 3) split = atoi(argv[3]);
if (argc > 4) arg4 = atoi(argv[4]);
if (argc > 5) arg5 = atoi(argv[5]);
if (argc > 6) enable_imt = atoi(argv[6]);
if (argc > 7) compAlg = atoi(argv[7]);
if (arg4 == 0) { write = 0; hfill = 0; read = 1;}
if (arg4 == 1) { write = 1; hfill = 0;}
if (arg4 == 2) { write = 0; hfill = 0;}
if (arg4 == 10) { write = 0; hfill = 1;}
if (arg4 == 11) { write = 1; hfill = 1;}
if (arg4 == 20) { write = 0; read = 1;} //read sequential
if (arg4 == 21) { write = 0; read = 1; punzip = 1;} //read sequential + parallel unzipping
if (arg4 == 25) { write = 0; read = 2;} //read random
if (arg4 >= 30) { netf = 1; } //use TNetFile
if (arg4 == 30) { write = 0; read = 1;} //netfile + read sequential
if (arg4 == 35) { write = 0; read = 2;} //netfile + read random
if (arg4 == 36) { write = 1; } //netfile + write sequential
Int_t branchStyle = 1; //new style by default
if (split < 0) {branchStyle = 0; split = -1-split;}
#ifdef R__USE_IMT
if (enable_imt) {
ROOT::EnableImplicitMT();
}
#else
if (enable_imt) {
std::cerr << "IMT mode requested, but this version of ROOT "
"is built without IMT support." << std::endl;
return 1;
}
#endif
TFile *hfile;
TTree *tree;
TTreePerfStats *ioperf = nullptr;
Event *event = 0;
// Fill event, header and tracks with some random numbers
// Create a timer object to benchmark this loop
TStopwatch timer;
timer.Start();
Long64_t nb = 0;
Int_t ev;
Int_t bufsize;
Double_t told = 0;
Double_t tnew = 0;
Int_t printev = 100;
if (arg5 < 100) printev = 1000;
if (arg5 < 10) printev = 10000;
// Read case
if (read) {
if (netf) {
hfile = new TNetFile("root://localhost/root/test/EventNet.root");
} else
hfile = new TFile("Event.root");
tree = (TTree*)hfile->Get("T");
TBranch *branch = tree->GetBranch("event");
branch->SetAddress(&event);
Int_t nentries = (Int_t)tree->GetEntries();
nevent = TMath::Min(nevent,nentries);
if (read == 1) { //read sequential
ioperf = getenv("ENABLE_TTREEPERFSTATS") ? new TTreePerfStats("Perf Stats", tree) : nullptr;
//by setting the read cache to -1 we set it to the AutoFlush value when writing
Int_t cachesize = -1;
if (punzip) tree->SetParallelUnzip();
tree->SetCacheSize(cachesize);
tree->SetCacheLearnEntries(1); //one entry is sufficient to learn
tree->SetCacheEntryRange(0,nevent);
for (ev = 0; ev < nevent; ev++) {
tree->LoadTree(ev); //this call is required when using the cache
if (ev%printev == 0) {
tnew = timer.RealTime();
printf("event:%d, rtime=%f s\n",ev,tnew-told);
told=tnew;
timer.Continue();
}
nb += tree->GetEntry(ev); //read complete event in memory
}
if (ioperf) {
ioperf->Finish();
}
} else { //read random
Int_t evrandom;
for (ev = 0; ev < nevent; ev++) {
if (ev%printev == 0) std::cout<<"event="<<ev<<std::endl;
evrandom = Int_t(nevent*gRandom->Rndm());
nb += tree->GetEntry(evrandom); //read complete event in memory
}
}
} else {
// Write case
// Create a new ROOT binary machine independent file.
// Note that this file may contain any kind of ROOT objects, histograms,
// pictures, graphics objects, detector geometries, tracks, events, etc..
// This file is now becoming the current directory.
if (netf) {
hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file");
} else
hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file");
hfile->SetCompressionLevel(comp);
hfile->SetCompressionAlgorithm(compAlg);
// Create histogram to show write_time in function of time
Float_t curtime = -0.5;
Int_t ntime = nevent / printev;
TH1F *htime = new TH1F("htime", "Real-Time to write versus time", ntime, 0, ntime);
HistogramManager *hm = 0;
if (hfill) {
TDirectory *hdir = new TDirectory("histograms", "all histograms");
hm = new HistogramManager(hdir);
}
// Create a ROOT Tree and one superbranch
tree = new TTree("T","An example of a ROOT tree");
tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written
tree->SetCacheSize(10000000); // set a 10 MBytes cache (useless when writing local files)
bufsize = 64000;
if (split) bufsize /= 4;
event = new Event(); // By setting the value, we own the pointer and must delete it.
TTree::SetBranchStyle(branchStyle);
TBranch *branch = tree->Branch("event", &event, bufsize,split);
branch->SetAutoDelete(kFALSE);
if(split >= 0 && branchStyle) tree->BranchRef();
Float_t ptmin = 1;
for (ev = 0; ev < nevent; ev++) {
if (ev%printev == 0) {
tnew = timer.RealTime();
printf("event:%d, rtime=%f s\n",ev,tnew-told);
htime->Fill(curtime,tnew-told);
curtime += 1;
told=tnew;
timer.Continue();
}
event->Build(ev, arg5, ptmin);
if (write) nb += tree->Fill(); //fill the tree
if (hm) hm->Hfill(event); //fill histograms
}
if (write) {
hfile = tree->GetCurrentFile(); //just in case we switched to a new file
hfile->Write();
tree->Print();
}
}
// We own the event (since we set the branch address explicitly), we need to delete it.
delete event; event = 0;
// Stop timer and print results
timer.Stop();
Float_t mbytes = 0.000001*nb;
Double_t rtime = timer.RealTime();
Double_t ctime = timer.CpuTime();
printf("\n%d events and %lld bytes processed.\n",nevent,nb);
printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime);
if (read) {
tree->PrintCacheStats();
if (ioperf) {
ioperf->Print();
}
printf("You read %f Mbytes/Realtime seconds\n", mbytes / rtime);
printf("You read %f Mbytes/Cputime seconds\n", mbytes / ctime);
} else {
printf("compression level=%d, split=%d, arg4=%d, IMT=%d, compression algorithm=%d\n", comp, split, arg4,
enable_imt, compAlg);
printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime);
printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime);
//printf("file compression factor = %f\n",hfile.GetCompressionFactor());
}
hfile->Close();
return 0;
}
<|endoftext|> |
<commit_before>// @(#)root/test:$Id$
// Author: Rene Brun 19/01/97
////////////////////////////////////////////////////////////////////////
//
// A simple example with a ROOT tree
// =================================
//
// This program creates :
// - a ROOT file
// - a tree
// Additional arguments can be passed to the program to control the flow
// of execution. (see comments describing the arguments in the code).
// Event nevent comp split fill
// All arguments are optional. Default is:
// Event 400 1 1 1
//
// In this example, the tree consists of one single "super branch"
// The statement ***tree->Branch("event", &event, 64000,split);*** below
// will parse the structure described in Event.h and will make
// a new branch for each data member of the class if split is set to 1.
// - 9 branches corresponding to the basic types fType, fNtrack,fNseg,
// fNvertex,fFlag,fTemperature,fMeasures,fMatrix,fClosesDistance.
// - 3 branches corresponding to the members of the subobject EventHeader.
// - one branch for each data member of the class Track of TClonesArray.
// - one branch for the TRefArray of high Pt tracks
// - one branch for the TRefArray of muon tracks
// - one branch for the reference pointer to the last track
// - one branch for the object fH (histogram of class TH1F).
//
// if split = 0 only one single branch is created and the complete event
// is serialized in one single buffer.
// if split = -2 the event is split using the old TBranchObject mechanism
// if split = -1 the event is streamed using the old TBranchObject mechanism
// if split > 0 the event is split using the new TBranchElement mechanism.
// if split > 90 the branch buffer sizes are optimized once 10 MBytes written to the file
//
// if comp = 0 no compression at all.
// if comp = 1 event is compressed.
// if comp = 2 same as 1. In addition branches with floats in the TClonesArray
// are also compressed.
// The 4th argument fill can be set to 0 if one wants to time
// the percentage of time spent in creating the event structure and
// not write the event in the file.
// In this example, one loops over nevent events.
// The branch "event" is created at the first event.
// The branch address is set for all other events.
// For each event, the event header is filled and ntrack tracks
// are generated and added to the TClonesArray list.
// For each event the event histogram is saved as well as the list
// of all tracks.
//
// The two TRefArray contain only references to the original tracks owned by
// the TClonesArray fTracks.
//
// The number of events can be given as the first argument to the program.
// By default 400 events are generated.
// The compression option can be activated/deactivated via the second argument.
//
// ---Running/Linking instructions----
// This program consists of the following files and procedures.
// - Event.h event class description
// - Event.C event class implementation
// - MainEvent.C the main program to demo this class might be used (this file)
// - EventCint.C the CINT dictionary for the event and Track classes
// this file is automatically generated by rootcint (see Makefile),
// when the class definition in Event.h is modified.
//
// ---Analyzing the Event.root file with the interactive root
// example of a simple session
// Root > TFile f("Event.root")
// Root > T.Draw("fNtrack") //histogram the number of tracks per event
// Root > T.Draw("fPx") //histogram fPx for all tracks in all events
// Root > T.Draw("fXfirst:fYfirst","fNtrack>600")
// //scatter-plot for x versus y of first point of each track
// Root > T.Draw("fH.GetRMS()") //histogram of the RMS of the event histogram
//
// Look also in the same directory at the following macros:
// - eventa.C an example how to read the tree
// - eventb.C how to read events conditionally
//
////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include "Riostream.h"
#include "TROOT.h"
#include "TFile.h"
#include "TNetFile.h"
#include "TRandom.h"
#include "TTree.h"
#include "TBranch.h"
#include "TClonesArray.h"
#include "TStopwatch.h"
#include "Event.h"
//______________________________________________________________________________
int main(int argc, char **argv)
{
Int_t nevent = 400; // by default create 400 events
Int_t comp = 1; // by default file is compressed
Int_t split = 1; // by default, split Event in sub branches
Int_t write = 1; // by default the tree is filled
Int_t hfill = 0; // by default histograms are not filled
Int_t read = 0;
Int_t arg4 = 1;
Int_t arg5 = 600; //default number of tracks per event
Int_t netf = 0;
Int_t punzip = 0;
if (argc > 1) nevent = atoi(argv[1]);
if (argc > 2) comp = atoi(argv[2]);
if (argc > 3) split = atoi(argv[3]);
if (argc > 4) arg4 = atoi(argv[4]);
if (argc > 5) arg5 = atoi(argv[5]);
if (arg4 == 0) { write = 0; hfill = 0; read = 1;}
if (arg4 == 1) { write = 1; hfill = 0;}
if (arg4 == 2) { write = 0; hfill = 0;}
if (arg4 == 10) { write = 0; hfill = 1;}
if (arg4 == 11) { write = 1; hfill = 1;}
if (arg4 == 20) { write = 0; read = 1;} //read sequential
if (arg4 == 21) { write = 0; read = 1; punzip = 1;} //read sequential + parallel unzipping
if (arg4 == 25) { write = 0; read = 2;} //read random
if (arg4 >= 30) { netf = 1; } //use TNetFile
if (arg4 == 30) { write = 0; read = 1;} //netfile + read sequential
if (arg4 == 35) { write = 0; read = 2;} //netfile + read random
if (arg4 == 36) { write = 1; } //netfile + write sequential
Int_t branchStyle = 1; //new style by default
if (split < 0) {branchStyle = 0; split = -1-split;}
TFile *hfile;
TTree *tree;
Event *event = 0;
// Fill event, header and tracks with some random numbers
// Create a timer object to benchmark this loop
TStopwatch timer;
timer.Start();
Long64_t nb = 0;
Int_t ev;
Int_t bufsize;
Double_t told = 0;
Double_t tnew = 0;
Int_t printev = 100;
if (arg5 < 100) printev = 1000;
if (arg5 < 10) printev = 10000;
//Authorize Trees up to 2 Terabytes (if the system can do it)
TTree::SetMaxTreeSize(1000*Long64_t(2000000000));
// Read case
if (read) {
if (netf) {
hfile = new TNetFile("root://localhost/root/test/EventNet.root");
} else
hfile = new TFile("Event.root");
tree = (TTree*)hfile->Get("T");
TBranch *branch = tree->GetBranch("event");
branch->SetAddress(&event);
Int_t nentries = (Int_t)tree->GetEntries();
nevent = TMath::Min(nevent,nentries);
if (read == 1) { //read sequential
//set the read cache
Int_t cachesize = 10000000; //this is the default value: 10 MBytes
tree->SetCacheSize(cachesize);
tree->SetCacheLearnEntries(1); //one entry is sufficient to learn
tree->SetCacheEntryRange(0,nevent);
if(punzip) tree->SetParallelUnzip();
for (ev = 0; ev < nevent; ev++) {
tree->LoadTree(ev); //this call is required when using the cache
if (ev%printev == 0) {
tnew = timer.RealTime();
printf("event:%d, rtime=%f s\n",ev,tnew-told);
told=tnew;
timer.Continue();
}
nb += tree->GetEntry(ev); //read complete event in memory
}
} else { //read random
Int_t evrandom;
for (ev = 0; ev < nevent; ev++) {
if (ev%printev == 0) cout<<"event="<<ev<<endl;
evrandom = Int_t(nevent*gRandom->Rndm(1));
nb += tree->GetEntry(evrandom); //read complete event in memory
}
}
} else {
// Write case
// Create a new ROOT binary machine independent file.
// Note that this file may contain any kind of ROOT objects, histograms,
// pictures, graphics objects, detector geometries, tracks, events, etc..
// This file is now becoming the current directory.
if (netf) {
hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file");
} else
hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file");
hfile->SetCompressionLevel(comp);
// Create histogram to show write_time in function of time
Float_t curtime = -0.5;
Int_t ntime = nevent/printev;
TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime);
HistogramManager *hm = 0;
if (hfill) {
TDirectory *hdir = new TDirectory("histograms", "all histograms");
hm = new HistogramManager(hdir);
}
// Create a ROOT Tree and one superbranch
tree = new TTree("T","An example of a ROOT tree");
tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written
tree->SetCacheSize(10000000); //set a 10 MBytes cache (useless when writing local files)
bufsize = 64000;
if (split) bufsize /= 4;
event = new Event();
TTree::SetBranchStyle(branchStyle);
TBranch *branch = tree->Branch("event", &event, bufsize,split);
branch->SetAutoDelete(kFALSE);
if(split >= 0 && branchStyle) tree->BranchRef();
Float_t ptmin = 1;
Bool_t optimize = kTRUE;
if (split < 90) optimize = kFALSE;
for (ev = 0; ev < nevent; ev++) {
if (ev%printev == 0) {
tnew = timer.RealTime();
printf("event:%d, rtime=%f s\n",ev,tnew-told);
htime->Fill(curtime,tnew-told);
curtime += 1;
told=tnew;
timer.Continue();
}
event->Build(ev, arg5, ptmin);
if (write) nb += tree->Fill(); //fill the tree
if (optimize) { //optimize baskets sizes once we have written 10 MBytes
if (tree->GetZipBytes() > 10000000) {
tree->OptimizeBaskets(5000000,1); // 5Mbytes for basket buffers
optimize = kFALSE;
}
}
if (hm) hm->Hfill(event); //fill histograms
}
if (write) {
hfile = tree->GetCurrentFile(); //just in case we switched to a new file
hfile->Write();
tree->Print();
}
}
// Stop timer and print results
timer.Stop();
Float_t mbytes = 0.000001*nb;
Double_t rtime = timer.RealTime();
Double_t ctime = timer.CpuTime();
printf("\n%d events and %lld bytes processed.\n",nevent,nb);
printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime);
if (read) {
tree->PrintCacheStats();
printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime);
printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime);
} else {
printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4);
printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime);
printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime);
//printf("file compression factor = %f\n",hfile.GetCompressionFactor());
}
hfile->Close();
return 0;
}
<commit_msg>Simplify the test program: -no need to set a MaxTreeSize -no need to OptimizeBaskets since it happens now automatically when filling. -when reading use the default value for the cache<commit_after>// @(#)root/test:$Id$
// Author: Rene Brun 19/01/97
////////////////////////////////////////////////////////////////////////
//
// A simple example with a ROOT tree
// =================================
//
// This program creates :
// - a ROOT file
// - a tree
// Additional arguments can be passed to the program to control the flow
// of execution. (see comments describing the arguments in the code).
// Event nevent comp split fill
// All arguments are optional. Default is:
// Event 400 1 1 1
//
// In this example, the tree consists of one single "super branch"
// The statement ***tree->Branch("event", &event, 64000,split);*** below
// will parse the structure described in Event.h and will make
// a new branch for each data member of the class if split is set to 1.
// - 9 branches corresponding to the basic types fType, fNtrack,fNseg,
// fNvertex,fFlag,fTemperature,fMeasures,fMatrix,fClosesDistance.
// - 3 branches corresponding to the members of the subobject EventHeader.
// - one branch for each data member of the class Track of TClonesArray.
// - one branch for the TRefArray of high Pt tracks
// - one branch for the TRefArray of muon tracks
// - one branch for the reference pointer to the last track
// - one branch for the object fH (histogram of class TH1F).
//
// if split = 0 only one single branch is created and the complete event
// is serialized in one single buffer.
// if split = -2 the event is split using the old TBranchObject mechanism
// if split = -1 the event is streamed using the old TBranchObject mechanism
// if split > 0 the event is split using the new TBranchElement mechanism.
//
// if comp = 0 no compression at all.
// if comp = 1 event is compressed.
// if comp = 2 same as 1. In addition branches with floats in the TClonesArray
// are also compressed.
// The 4th argument fill can be set to 0 if one wants to time
// the percentage of time spent in creating the event structure and
// not write the event in the file.
// In this example, one loops over nevent events.
// The branch "event" is created at the first event.
// The branch address is set for all other events.
// For each event, the event header is filled and ntrack tracks
// are generated and added to the TClonesArray list.
// For each event the event histogram is saved as well as the list
// of all tracks.
//
// The two TRefArray contain only references to the original tracks owned by
// the TClonesArray fTracks.
//
// The number of events can be given as the first argument to the program.
// By default 400 events are generated.
// The compression option can be activated/deactivated via the second argument.
//
// ---Running/Linking instructions----
// This program consists of the following files and procedures.
// - Event.h event class description
// - Event.C event class implementation
// - MainEvent.C the main program to demo this class might be used (this file)
// - EventCint.C the CINT dictionary for the event and Track classes
// this file is automatically generated by rootcint (see Makefile),
// when the class definition in Event.h is modified.
//
// ---Analyzing the Event.root file with the interactive root
// example of a simple session
// Root > TFile f("Event.root")
// Root > T.Draw("fNtrack") //histogram the number of tracks per event
// Root > T.Draw("fPx") //histogram fPx for all tracks in all events
// Root > T.Draw("fXfirst:fYfirst","fNtrack>600")
// //scatter-plot for x versus y of first point of each track
// Root > T.Draw("fH.GetRMS()") //histogram of the RMS of the event histogram
//
// Look also in the same directory at the following macros:
// - eventa.C an example how to read the tree
// - eventb.C how to read events conditionally
//
////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include "Riostream.h"
#include "TROOT.h"
#include "TFile.h"
#include "TNetFile.h"
#include "TRandom.h"
#include "TTree.h"
#include "TBranch.h"
#include "TClonesArray.h"
#include "TStopwatch.h"
#include "Event.h"
//______________________________________________________________________________
int main(int argc, char **argv)
{
Int_t nevent = 400; // by default create 400 events
Int_t comp = 1; // by default file is compressed
Int_t split = 1; // by default, split Event in sub branches
Int_t write = 1; // by default the tree is filled
Int_t hfill = 0; // by default histograms are not filled
Int_t read = 0;
Int_t arg4 = 1;
Int_t arg5 = 600; //default number of tracks per event
Int_t netf = 0;
Int_t punzip = 0;
if (argc > 1) nevent = atoi(argv[1]);
if (argc > 2) comp = atoi(argv[2]);
if (argc > 3) split = atoi(argv[3]);
if (argc > 4) arg4 = atoi(argv[4]);
if (argc > 5) arg5 = atoi(argv[5]);
if (arg4 == 0) { write = 0; hfill = 0; read = 1;}
if (arg4 == 1) { write = 1; hfill = 0;}
if (arg4 == 2) { write = 0; hfill = 0;}
if (arg4 == 10) { write = 0; hfill = 1;}
if (arg4 == 11) { write = 1; hfill = 1;}
if (arg4 == 20) { write = 0; read = 1;} //read sequential
if (arg4 == 21) { write = 0; read = 1; punzip = 1;} //read sequential + parallel unzipping
if (arg4 == 25) { write = 0; read = 2;} //read random
if (arg4 >= 30) { netf = 1; } //use TNetFile
if (arg4 == 30) { write = 0; read = 1;} //netfile + read sequential
if (arg4 == 35) { write = 0; read = 2;} //netfile + read random
if (arg4 == 36) { write = 1; } //netfile + write sequential
Int_t branchStyle = 1; //new style by default
if (split < 0) {branchStyle = 0; split = -1-split;}
TFile *hfile;
TTree *tree;
Event *event = 0;
// Fill event, header and tracks with some random numbers
// Create a timer object to benchmark this loop
TStopwatch timer;
timer.Start();
Long64_t nb = 0;
Int_t ev;
Int_t bufsize;
Double_t told = 0;
Double_t tnew = 0;
Int_t printev = 100;
if (arg5 < 100) printev = 1000;
if (arg5 < 10) printev = 10000;
// Read case
if (read) {
if (netf) {
hfile = new TNetFile("root://localhost/root/test/EventNet.root");
} else
hfile = new TFile("Event.root");
tree = (TTree*)hfile->Get("T");
TBranch *branch = tree->GetBranch("event");
branch->SetAddress(&event);
Int_t nentries = (Int_t)tree->GetEntries();
nevent = TMath::Min(nevent,nentries);
if (read == 1) { //read sequential
//by setting the read cache to -1 we set it to the AutoFlush value when writing
Int_t cachesize = -1;
tree->SetCacheSize(cachesize);
tree->SetCacheLearnEntries(1); //one entry is sufficient to learn
tree->SetCacheEntryRange(0,nevent);
if(punzip) tree->SetParallelUnzip();
for (ev = 0; ev < nevent; ev++) {
tree->LoadTree(ev); //this call is required when using the cache
if (ev%printev == 0) {
tnew = timer.RealTime();
printf("event:%d, rtime=%f s\n",ev,tnew-told);
told=tnew;
timer.Continue();
}
nb += tree->GetEntry(ev); //read complete event in memory
}
} else { //read random
Int_t evrandom;
for (ev = 0; ev < nevent; ev++) {
if (ev%printev == 0) cout<<"event="<<ev<<endl;
evrandom = Int_t(nevent*gRandom->Rndm(1));
nb += tree->GetEntry(evrandom); //read complete event in memory
}
}
} else {
// Write case
// Create a new ROOT binary machine independent file.
// Note that this file may contain any kind of ROOT objects, histograms,
// pictures, graphics objects, detector geometries, tracks, events, etc..
// This file is now becoming the current directory.
if (netf) {
hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file");
} else
hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file");
hfile->SetCompressionLevel(comp);
// Create histogram to show write_time in function of time
Float_t curtime = -0.5;
Int_t ntime = nevent/printev;
TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime);
HistogramManager *hm = 0;
if (hfill) {
TDirectory *hdir = new TDirectory("histograms", "all histograms");
hm = new HistogramManager(hdir);
}
// Create a ROOT Tree and one superbranch
tree = new TTree("T","An example of a ROOT tree");
tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written
tree->SetCacheSize(10000000); //set a 10 MBytes cache (useless when writing local files)
bufsize = 64000;
if (split) bufsize /= 4;
event = new Event();
TTree::SetBranchStyle(branchStyle);
TBranch *branch = tree->Branch("event", &event, bufsize,split);
branch->SetAutoDelete(kFALSE);
if(split >= 0 && branchStyle) tree->BranchRef();
Float_t ptmin = 1;
for (ev = 0; ev < nevent; ev++) {
if (ev%printev == 0) {
tnew = timer.RealTime();
printf("event:%d, rtime=%f s\n",ev,tnew-told);
htime->Fill(curtime,tnew-told);
curtime += 1;
told=tnew;
timer.Continue();
}
event->Build(ev, arg5, ptmin);
if (write) nb += tree->Fill(); //fill the tree
if (hm) hm->Hfill(event); //fill histograms
}
if (write) {
hfile = tree->GetCurrentFile(); //just in case we switched to a new file
hfile->Write();
tree->Print();
}
}
// Stop timer and print results
timer.Stop();
Float_t mbytes = 0.000001*nb;
Double_t rtime = timer.RealTime();
Double_t ctime = timer.CpuTime();
printf("\n%d events and %lld bytes processed.\n",nevent,nb);
printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime);
if (read) {
tree->PrintCacheStats();
printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime);
printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime);
} else {
printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4);
printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime);
printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime);
//printf("file compression factor = %f\n",hfile.GetCompressionFactor());
}
hfile->Close();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 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.
*
* $Id$
*/
#include "ircutil.h"
#include <QString>
#include <QRegExp>
/*!
\class Irc::Util ircutil.h
\brief The Irc::Util class provides IRC related utility functions.
*/
//static QRegExp URL_PATTERN(QLatin1String("((www\\.(?!\\.)|(ssh|fish|irc|(f|sf|ht)tp(|s))://)(\\.?[\\d\\w/,\\':~\\?=;#@\\-\\+\\%\\*\\{\\}\\!\\(\\)]|&)+)|([-.\\d\\w]+@[-.\\d\\w]{2,}\\.[\\w]{2,})"), Qt::CaseInsensitive);
static QRegExp URL_PATTERN(QLatin1String("\\b(?:(?:ssh|fish|irc|ftp|sftp|http|https|nntp|telnet|file)://|(?:mailto|news):(?!/)|www[0-9]?(?=\\.)|ftp(?=\\.))(?:[$_.+!*(),;/\\\\?:@&~=-](?=[A-Za-z0-9%])|[A-Za-z0-9%*])(?:[A-Za-z0-9)]|[$_.+!*(,;/\\\\?:@&~=-](?!\\s|$)|%[A-Fa-f0-9]{2})*(?:#[/a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/\\\\?:@&~=%-]*)?"), Qt::CaseInsensitive);
namespace Irc
{
/*!
Parses and returns the nick part from \a target.
*/
QString Util::nickFromTarget(const QString& target)
{
int index = target.indexOf(QLatin1Char('!'));
return target.left(index);
}
/*!
Parses and returns the host part from \a target.
*/
QString Util::hostFromTarget(const QString& target)
{
int index = target.indexOf(QLatin1Char('!'));
return target.mid(index + 1);
}
/*!
Converts \a message to HTML. This function parses the
message and replaces IRC-style formatting like colors,
bold and underline to the corresponding HTML formatting.
Furthermore, this function detects URLs and replaces
them with appropriate HTML hyperlinks.
*/
QString Util::messageToHtml(const QString& message)
{
QString processed = message;
processed.replace(QLatin1Char('&'), QLatin1String("&"));
//processed.replace(QLatin1Char('%'), QLatin1String("%"));
processed.replace(QLatin1Char('<'), QLatin1String("<"));
processed.replace(QLatin1Char('>'), QLatin1String(">"));
enum
{
None = 0x0,
Bold = 0x1,
Color = 0x2,
Italic = 0x4,
StrikeThrough = 0x8,
Underline = 0x10,
Inverse = 0x20
};
int state = None;
int pos = 0;
while (pos < processed.size())
{
if (state & Color)
{
QString tmp = processed.mid(pos, 2);
processed.remove(pos, 2);
processed = processed.arg(colorNameFromCode(tmp.toInt()));
state &= ~Color;
pos += 2;
continue;
}
QString replacement;
switch (processed.at(pos).unicode())
{
case '\x02': // bold
if (state & Bold)
replacement = QLatin1String("</span>");
else
replacement = QLatin1String("<span style='font-weight: bold'>");
state ^= Bold;
break;
case '\x03': // color
if (state & Color)
replacement = QLatin1String("</span>");
else
replacement = QLatin1String("<span style='color: %1'>");
state ^= Color;
break;
case '\x09': // italic
if (state & Italic)
replacement = QLatin1String("</span>");
else
replacement = QLatin1String("<span style='text-decoration: underline'>");
state ^= Italic;
break;
case '\x13': // strike-through
if (state & StrikeThrough)
replacement = QLatin1String("</span>");
else
replacement = QLatin1String("<span style='text-decoration: line-through'>");
state ^= StrikeThrough;
break;
case '\x15': // underline
case '\x1f': // underline
if (state & Underline)
replacement = QLatin1String("</span>");
else
replacement = QLatin1String("<span style='text-decoration: underline'>");
state ^= Underline;
break;
case '\x16': // inverse
state ^= Inverse;
break;
case '\x0f': // none
replacement = QLatin1String("</span>");
state = None;
break;
default:
break;
}
if (!replacement.isNull())
{
processed.replace(pos, 1, replacement);
pos += replacement.length();
}
else
{
++pos;
}
}
pos = 0;
while ((pos = URL_PATTERN.indexIn(processed, pos)) >= 0)
{
int len = URL_PATTERN.matchedLength();
QString href = processed.mid(pos, len);
// Don't consider trailing > as part of the link.
QString append;
if (href.endsWith(QLatin1String(">")))
{
append.append(href.right(4));
href.chop(4);
}
// Don't consider trailing comma or semi-colon as part of the link.
if (href.endsWith(QLatin1Char(',')) || href.endsWith(QLatin1Char(';')))
{
append.append(href.right(1));
href.chop(1);
}
// Don't consider trailing closing parenthesis part of the link when
// there's an opening parenthesis preceding in the beginning of the
// URL or there is no opening parenthesis in the URL at all.
if (pos > 0 && href.endsWith(QLatin1Char(')'))
&& (processed.at(pos-1) == QLatin1Char('(')
|| !href.contains(QLatin1Char('('))))
{
append.prepend(href.right(1));
href.chop(1);
}
// Qt doesn't support (?<=pattern) so we do it here
if (pos > 0 && processed.at(pos-1).isLetterOrNumber())
{
pos++;
continue;
}
QString protocol;
if (URL_PATTERN.cap(1).startsWith(QLatin1String("www."), Qt::CaseInsensitive))
protocol = QLatin1String("http://");
else if (URL_PATTERN.cap(1).isEmpty())
protocol = QLatin1String("mailto:");
QString source = href;
source.replace(QLatin1String("&"), QLatin1String("&"));
QString link = QString(QLatin1String("<a href='%1%2'>%3</a>")).arg(protocol, source, href) + append;
processed.replace(pos, len, link);
pos += link.length();
}
return processed;
}
/*!
Converts \a code to a color name.
*/
QString Util::colorNameFromCode(int code)
{
switch (code)
{
case 0: return QLatin1String("white");
case 1: return QLatin1String("black");
case 2: return QLatin1String("navy");
case 3: return QLatin1String("green");
case 4: return QLatin1String("red");
case 5: return QLatin1String("maroon");
case 6: return QLatin1String("purple");
case 7: return QLatin1String("orange");
case 8: return QLatin1String("yellow");
case 9: return QLatin1String("lime");
case 10: return QLatin1String("darkcyan");
case 11: return QLatin1String("cyan");
case 12: return QLatin1String("blue");
case 13: return QLatin1String("magenta");
case 14: return QLatin1String("gray");
case 15: return QLatin1String("lightgray");
default: return QLatin1String("black");
}
}
}
<commit_msg>Reverted the url regexp change.<commit_after>/*
* Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 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.
*
* $Id$
*/
#include "ircutil.h"
#include <QString>
#include <QRegExp>
/*!
\class Irc::Util ircutil.h
\brief The Irc::Util class provides IRC related utility functions.
*/
static QRegExp URL_PATTERN(QLatin1String("((www\\.(?!\\.)|(ssh|fish|irc|(f|sf|ht)tp(|s))://)(\\.?[\\d\\w/,\\':~\\?=;#@\\-\\+\\%\\*\\{\\}\\!\\(\\)]|&)+)|([-.\\d\\w]+@[-.\\d\\w]{2,}\\.[\\w]{2,})"), Qt::CaseInsensitive);
//static QRegExp URL_PATTERN(QLatin1String("\\b(?:(?:ssh|fish|irc|ftp|sftp|http|https|nntp|telnet|file)://|(?:mailto|news):(?!/)|www[0-9]?(?=\\.)|ftp(?=\\.))(?:[$_.+!*(),;/\\\\?:@&~=-](?=[A-Za-z0-9%])|[A-Za-z0-9%*])(?:[A-Za-z0-9)]|[$_.+!*(,;/\\\\?:@&~=-](?!\\s|$)|%[A-Fa-f0-9]{2})*(?:#[/a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/\\\\?:@&~=%-]*)?"), Qt::CaseInsensitive);
namespace Irc
{
/*!
Parses and returns the nick part from \a target.
*/
QString Util::nickFromTarget(const QString& target)
{
int index = target.indexOf(QLatin1Char('!'));
return target.left(index);
}
/*!
Parses and returns the host part from \a target.
*/
QString Util::hostFromTarget(const QString& target)
{
int index = target.indexOf(QLatin1Char('!'));
return target.mid(index + 1);
}
/*!
Converts \a message to HTML. This function parses the
message and replaces IRC-style formatting like colors,
bold and underline to the corresponding HTML formatting.
Furthermore, this function detects URLs and replaces
them with appropriate HTML hyperlinks.
*/
QString Util::messageToHtml(const QString& message)
{
QString processed = message;
processed.replace(QLatin1Char('&'), QLatin1String("&"));
processed.replace(QLatin1Char('<'), QLatin1String("<"));
processed.replace(QLatin1Char('>'), QLatin1String(">"));
enum
{
None = 0x0,
Bold = 0x1,
Color = 0x2,
Italic = 0x4,
StrikeThrough = 0x8,
Underline = 0x10,
Inverse = 0x20
};
int state = None;
int pos = 0;
while (pos < processed.size())
{
if (state & Color)
{
QString tmp = processed.mid(pos, 2);
processed.remove(pos, 2);
processed = processed.arg(colorNameFromCode(tmp.toInt()));
state &= ~Color;
pos += 2;
continue;
}
QString replacement;
switch (processed.at(pos).unicode())
{
case '\x02': // bold
if (state & Bold)
replacement = QLatin1String("</span>");
else
replacement = QLatin1String("<span style='font-weight: bold'>");
state ^= Bold;
break;
case '\x03': // color
if (state & Color)
replacement = QLatin1String("</span>");
else
replacement = QLatin1String("<span style='color: %1'>");
state ^= Color;
break;
case '\x09': // italic
if (state & Italic)
replacement = QLatin1String("</span>");
else
replacement = QLatin1String("<span style='text-decoration: underline'>");
state ^= Italic;
break;
case '\x13': // strike-through
if (state & StrikeThrough)
replacement = QLatin1String("</span>");
else
replacement = QLatin1String("<span style='text-decoration: line-through'>");
state ^= StrikeThrough;
break;
case '\x15': // underline
case '\x1f': // underline
if (state & Underline)
replacement = QLatin1String("</span>");
else
replacement = QLatin1String("<span style='text-decoration: underline'>");
state ^= Underline;
break;
case '\x16': // inverse
state ^= Inverse;
break;
case '\x0f': // none
replacement = QLatin1String("</span>");
state = None;
break;
default:
break;
}
if (!replacement.isNull())
{
processed.replace(pos, 1, replacement);
pos += replacement.length();
}
else
{
++pos;
}
}
pos = 0;
while ((pos = URL_PATTERN.indexIn(processed, pos)) >= 0)
{
int len = URL_PATTERN.matchedLength();
QString href = processed.mid(pos, len);
// Don't consider trailing > as part of the link.
QString append;
if (href.endsWith(QLatin1String(">")))
{
append.append(href.right(4));
href.chop(4);
}
// Don't consider trailing comma or semi-colon as part of the link.
if (href.endsWith(QLatin1Char(',')) || href.endsWith(QLatin1Char(';')))
{
append.append(href.right(1));
href.chop(1);
}
// Don't consider trailing closing parenthesis part of the link when
// there's an opening parenthesis preceding in the beginning of the
// URL or there is no opening parenthesis in the URL at all.
if (pos > 0 && href.endsWith(QLatin1Char(')'))
&& (processed.at(pos-1) == QLatin1Char('(')
|| !href.contains(QLatin1Char('('))))
{
append.prepend(href.right(1));
href.chop(1);
}
// Qt doesn't support (?<=pattern) so we do it here
if (pos > 0 && processed.at(pos-1).isLetterOrNumber())
{
pos++;
continue;
}
QString protocol;
if (URL_PATTERN.cap(1).startsWith(QLatin1String("www."), Qt::CaseInsensitive))
protocol = QLatin1String("http://");
else if (URL_PATTERN.cap(1).isEmpty())
protocol = QLatin1String("mailto:");
QString source = href;
source.replace(QLatin1String("&"), QLatin1String("&"));
QString link = QString(QLatin1String("<a href='%1%2'>%3</a>")).arg(protocol, source, href) + append;
processed.replace(pos, len, link);
pos += link.length();
}
return processed;
}
/*!
Converts \a code to a color name.
*/
QString Util::colorNameFromCode(int code)
{
switch (code)
{
case 0: return QLatin1String("white");
case 1: return QLatin1String("black");
case 2: return QLatin1String("navy");
case 3: return QLatin1String("green");
case 4: return QLatin1String("red");
case 5: return QLatin1String("maroon");
case 6: return QLatin1String("purple");
case 7: return QLatin1String("orange");
case 8: return QLatin1String("yellow");
case 9: return QLatin1String("lime");
case 10: return QLatin1String("darkcyan");
case 11: return QLatin1String("cyan");
case 12: return QLatin1String("blue");
case 13: return QLatin1String("magenta");
case 14: return QLatin1String("gray");
case 15: return QLatin1String("lightgray");
default: return QLatin1String("black");
}
}
}
<|endoftext|> |
<commit_before>// Copyright © 2013,2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>
#include <nix/hdf5/FileHDF5.hpp>
#include "TestGroup.hpp"
unsigned int & TestGroup::open_mode()
{
static unsigned int openMode = H5F_ACC_TRUNC;
return openMode;
}
void TestGroup::setUp() {
unsigned int &openMode = open_mode();
if (openMode == H5F_ACC_TRUNC) {
h5file = H5Fcreate("test_group.h5", openMode, H5P_DEFAULT, H5P_DEFAULT);
} else {
h5file = H5Fopen("test_group.h5", openMode, H5P_DEFAULT);
}
CPPUNIT_ASSERT(H5Iis_valid(h5file));
if (openMode == H5F_ACC_TRUNC) {
h5group = H5Gcreate2(h5file, "tstGroup", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
} else {
h5group = H5Gopen2(h5file, "tstGroup", H5P_DEFAULT);
}
openMode = H5F_ACC_RDWR;
}
void TestGroup::tearDown() {
H5Fclose(h5file);
H5Oclose(h5group);
}
void TestGroup::testBaseTypes() {
nix::hdf5::Group group(h5group);
//int
//attr
group.setAttr("t_int", 42);
int tint;
group.getAttr("t_int", tint);
CPPUNIT_ASSERT_EQUAL(tint, 42);
//double
//attr
double deps = std::numeric_limits<double>::epsilon();
double dpi = boost::math::constants::pi<double>();
group.setAttr("t_double", dpi);
double dbl;
group.getAttr("t_double", dbl);
CPPUNIT_ASSERT_DOUBLES_EQUAL(dpi, dbl, deps);
//string
const std::string testStr = "I saw the best minds of my generation destroyed by madness";
group.setAttr("t_string", testStr);
std::string retString;
group.getAttr("t_string", retString);
CPPUNIT_ASSERT_EQUAL(testStr, retString);
}
void TestGroup::testMultiArray() {
nix::hdf5::Group group(h5group);
//arrays
typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);
int values = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
A[i][j][k] = values++;
group.setAttr<array_type>("t_doubleArray", A);
array_type B(boost::extents[1][1][1]);
group.getAttr("t_doubleArray", B);
int verify = 0;
int errors = 0;
for(index i = 0; i != 3; ++i) {
for(index j = 0; j != 4; ++j) {
for(index k = 0; k != 2; ++k) {
int v = verify++;
errors += B[i][j][k] != v;
}
}
}
CPPUNIT_ASSERT_EQUAL(errors, 0);
//data
group.setData("t_doubleArray", A);
array_type C(boost::extents[1][1][1]);
group.getData("t_doubleArray", C);
verify = 0;
errors = 0;
for(index i = 0; i != 3; ++i) {
for(index j = 0; j != 4; ++j) {
for(index k = 0; k != 2; ++k) {
int v = verify++;
errors += B[i][j][k] != v;
}
}
}
CPPUNIT_ASSERT_EQUAL(errors, 0);
}
void TestGroup::testVector() {
nix::hdf5::Group group(h5group);
std::vector<int> iv;
iv.push_back(7);
iv.push_back(23);
iv.push_back(42);
iv.push_back(1982);
group.setAttr("t_intvector", iv);
std::vector<int> tiv;
group.getAttr("t_intvector", tiv);
assert_vectors_equal(iv, tiv);
std::vector<std::string> sv;
sv.push_back("Alle");
sv.push_back("meine");
sv.push_back("Entchen");
group.setAttr("t_strvector", sv);
std::vector<std::string> tsv;
group.getAttr("t_strvector", tsv);
assert_vectors_equal(sv, tsv);
}
void TestGroup::testArray() {
nix::hdf5::Group group(h5group);
int ia1d[5] = {1, 2, 3, 4, 5};
group.setAttr("t_intarray1d", ia1d);
int tia1d[5] = {0, };
group.getAttr("t_intarray1d", tia1d);
for (int i = 0; i < 5; i++) {
CPPUNIT_ASSERT_EQUAL(ia1d[i], tia1d[i]);
}
#ifndef _WIN32 //cf. issue #72
int ia2d[3][2] = { {1, 2}, {3, 4}, {5, 6} };
group.setAttr("t_intarray2d", ia2d);
int tia2d[3][2] = { {0, }, };
group.getAttr("t_intarray2d", tia2d);
for (int i = 0; i < 3*2; i++) {
CPPUNIT_ASSERT_EQUAL(*(ia2d[0] + i), *(tia2d[0] + i));
}
#endif
}
void TestGroup::testOpen() {
nix::hdf5::Group root(h5group);
nix::hdf5::Group g = root.openGroup("name_a", true);
std::string uuid = nix::util::createId();
g.setAttr("entity_id", uuid);
CPPUNIT_ASSERT(root.hasGroup("name_a"));
std::string idout;
boost::optional<nix::hdf5::Group> a = root.findGroupByNameOrAttribute("entity_id", "name_a");
CPPUNIT_ASSERT(a);
CPPUNIT_ASSERT(a->hasAttr("entity_id"));
a->getAttr("entity_id", idout);
CPPUNIT_ASSERT_EQUAL(uuid, idout);
boost::optional<nix::hdf5::Group> b = root.findGroupByNameOrAttribute("entity_id", uuid);
CPPUNIT_ASSERT(b);
CPPUNIT_ASSERT(b->hasAttr("entity_id"));
b->getAttr("entity_id", idout);
CPPUNIT_ASSERT_EQUAL(uuid, idout);
}
void TestGroup::testRefCount() {
nix::hdf5::Group wrapped(h5group);
CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(h5group));
CPPUNIT_ASSERT_EQUAL(h5group, wrapped.h5id());
CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(h5group));
nix::hdf5::Group g;
CPPUNIT_ASSERT_EQUAL(H5I_INVALID_HID, g.h5id());
g = nix::hdf5::Group(h5group);
CPPUNIT_ASSERT_EQUAL(h5group, g.h5id());
CPPUNIT_ASSERT_EQUAL(3, H5Iget_ref(h5group));
nix::hdf5::Group c = g;
CPPUNIT_ASSERT_EQUAL(h5group, c.h5id());
CPPUNIT_ASSERT_EQUAL(4, H5Iget_ref(h5group));
{
nix::hdf5::Group tmp = g;
CPPUNIT_ASSERT_EQUAL(h5group, tmp.h5id());
CPPUNIT_ASSERT_EQUAL(5, H5Iget_ref(h5group));
}
CPPUNIT_ASSERT_EQUAL(4, H5Iget_ref(h5group));
hid_t ha = H5Gopen2(h5file, "/", H5P_DEFAULT);
CPPUNIT_ASSERT(ha != h5group);
CPPUNIT_ASSERT_EQUAL(1, H5Iget_ref(ha));
nix::hdf5::Group b(ha);
CPPUNIT_ASSERT_EQUAL(ha, b.h5id());
CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(ha));
wrapped = nix::hdf5::Group(h5group); // test self assignment! no inc ref
CPPUNIT_ASSERT_EQUAL(h5group, wrapped.h5id());
CPPUNIT_ASSERT_EQUAL(4, H5Iget_ref(h5group));
CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(ha));
c = nix::hdf5::Group(b);
CPPUNIT_ASSERT_EQUAL(ha, c.h5id());
CPPUNIT_ASSERT_EQUAL(3, H5Iget_ref(h5group));
CPPUNIT_ASSERT_EQUAL(3, H5Iget_ref(ha));
wrapped = c;
CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(h5group));
CPPUNIT_ASSERT_EQUAL(4, H5Iget_ref(ha));
b = wrapped;
CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(h5group));
CPPUNIT_ASSERT_EQUAL(4, H5Iget_ref(ha));
}
<commit_msg>[test] Group: replace ref-cnt test with RefTester<commit_after>// Copyright © 2013,2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>
#include <nix/hdf5/FileHDF5.hpp>
#include "TestGroup.hpp"
#include "RefTester.hpp"
unsigned int & TestGroup::open_mode()
{
static unsigned int openMode = H5F_ACC_TRUNC;
return openMode;
}
void TestGroup::setUp() {
unsigned int &openMode = open_mode();
if (openMode == H5F_ACC_TRUNC) {
h5file = H5Fcreate("test_group.h5", openMode, H5P_DEFAULT, H5P_DEFAULT);
} else {
h5file = H5Fopen("test_group.h5", openMode, H5P_DEFAULT);
}
CPPUNIT_ASSERT(H5Iis_valid(h5file));
if (openMode == H5F_ACC_TRUNC) {
h5group = H5Gcreate2(h5file, "tstGroup", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
} else {
h5group = H5Gopen2(h5file, "tstGroup", H5P_DEFAULT);
}
openMode = H5F_ACC_RDWR;
}
void TestGroup::tearDown() {
H5Fclose(h5file);
H5Oclose(h5group);
}
void TestGroup::testBaseTypes() {
nix::hdf5::Group group(h5group);
//int
//attr
group.setAttr("t_int", 42);
int tint;
group.getAttr("t_int", tint);
CPPUNIT_ASSERT_EQUAL(tint, 42);
//double
//attr
double deps = std::numeric_limits<double>::epsilon();
double dpi = boost::math::constants::pi<double>();
group.setAttr("t_double", dpi);
double dbl;
group.getAttr("t_double", dbl);
CPPUNIT_ASSERT_DOUBLES_EQUAL(dpi, dbl, deps);
//string
const std::string testStr = "I saw the best minds of my generation destroyed by madness";
group.setAttr("t_string", testStr);
std::string retString;
group.getAttr("t_string", retString);
CPPUNIT_ASSERT_EQUAL(testStr, retString);
}
void TestGroup::testMultiArray() {
nix::hdf5::Group group(h5group);
//arrays
typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);
int values = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
A[i][j][k] = values++;
group.setAttr<array_type>("t_doubleArray", A);
array_type B(boost::extents[1][1][1]);
group.getAttr("t_doubleArray", B);
int verify = 0;
int errors = 0;
for(index i = 0; i != 3; ++i) {
for(index j = 0; j != 4; ++j) {
for(index k = 0; k != 2; ++k) {
int v = verify++;
errors += B[i][j][k] != v;
}
}
}
CPPUNIT_ASSERT_EQUAL(errors, 0);
//data
group.setData("t_doubleArray", A);
array_type C(boost::extents[1][1][1]);
group.getData("t_doubleArray", C);
verify = 0;
errors = 0;
for(index i = 0; i != 3; ++i) {
for(index j = 0; j != 4; ++j) {
for(index k = 0; k != 2; ++k) {
int v = verify++;
errors += B[i][j][k] != v;
}
}
}
CPPUNIT_ASSERT_EQUAL(errors, 0);
}
void TestGroup::testVector() {
nix::hdf5::Group group(h5group);
std::vector<int> iv;
iv.push_back(7);
iv.push_back(23);
iv.push_back(42);
iv.push_back(1982);
group.setAttr("t_intvector", iv);
std::vector<int> tiv;
group.getAttr("t_intvector", tiv);
assert_vectors_equal(iv, tiv);
std::vector<std::string> sv;
sv.push_back("Alle");
sv.push_back("meine");
sv.push_back("Entchen");
group.setAttr("t_strvector", sv);
std::vector<std::string> tsv;
group.getAttr("t_strvector", tsv);
assert_vectors_equal(sv, tsv);
}
void TestGroup::testArray() {
nix::hdf5::Group group(h5group);
int ia1d[5] = {1, 2, 3, 4, 5};
group.setAttr("t_intarray1d", ia1d);
int tia1d[5] = {0, };
group.getAttr("t_intarray1d", tia1d);
for (int i = 0; i < 5; i++) {
CPPUNIT_ASSERT_EQUAL(ia1d[i], tia1d[i]);
}
#ifndef _WIN32 //cf. issue #72
int ia2d[3][2] = { {1, 2}, {3, 4}, {5, 6} };
group.setAttr("t_intarray2d", ia2d);
int tia2d[3][2] = { {0, }, };
group.getAttr("t_intarray2d", tia2d);
for (int i = 0; i < 3*2; i++) {
CPPUNIT_ASSERT_EQUAL(*(ia2d[0] + i), *(tia2d[0] + i));
}
#endif
}
void TestGroup::testOpen() {
nix::hdf5::Group root(h5group);
nix::hdf5::Group g = root.openGroup("name_a", true);
std::string uuid = nix::util::createId();
g.setAttr("entity_id", uuid);
CPPUNIT_ASSERT(root.hasGroup("name_a"));
std::string idout;
boost::optional<nix::hdf5::Group> a = root.findGroupByNameOrAttribute("entity_id", "name_a");
CPPUNIT_ASSERT(a);
CPPUNIT_ASSERT(a->hasAttr("entity_id"));
a->getAttr("entity_id", idout);
CPPUNIT_ASSERT_EQUAL(uuid, idout);
boost::optional<nix::hdf5::Group> b = root.findGroupByNameOrAttribute("entity_id", uuid);
CPPUNIT_ASSERT(b);
CPPUNIT_ASSERT(b->hasAttr("entity_id"));
b->getAttr("entity_id", idout);
CPPUNIT_ASSERT_EQUAL(uuid, idout);
}
void TestGroup::testRefCount() {
hid_t ha = H5Gopen2(h5file, "/", H5P_DEFAULT);
test_refcounting<nix::hdf5::Group>(h5group, ha);
H5Gclose(ha);
}
<|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 "ui/app_list/contents_view.h"
#include <algorithm>
#include "ui/app_list/app_list_view.h"
#include "ui/app_list/apps_grid_view.h"
#include "ui/app_list/page_switcher.h"
#include "ui/app_list/pagination_model.h"
#include "ui/app_list/search_result_list_view.h"
#include "ui/base/event.h"
#include "ui/views/animation/bounds_animator.h"
#include "ui/views/view_model.h"
#include "ui/views/view_model_utils.h"
namespace app_list {
namespace {
const int kPreferredIconDimension = 48;
const int kPreferredCols = 4;
const int kPreferredRows = 4;
// Indexes of interesting views in ViewModel of ContentsView.
const int kIndexAppsGrid = 0;
const int kIndexPageSwitcher = 1;
const int kIndexSearchResults = 2;
const int kMinMouseWheelToSwitchPage = 20;
const int kMinScrollToSwitchPage = 20;
const int kMinHorizVelocityToSwitchPage = 1100;
// Helpers to get certain child view from |model|.
AppsGridView* GetAppsGridView(views::ViewModel* model) {
return static_cast<AppsGridView*>(model->view_at(kIndexAppsGrid));
}
PageSwitcher* GetPageSwitcherView(views::ViewModel* model) {
return static_cast<PageSwitcher*>(model->view_at(kIndexPageSwitcher));
}
SearchResultListView* GetSearchResultListView(views::ViewModel* model) {
return static_cast<SearchResultListView*>(
model->view_at(kIndexSearchResults));
}
} // namespace
ContentsView::ContentsView(AppListView* app_list_view,
PaginationModel* pagination_model)
: show_state_(SHOW_APPS),
pagination_model_(pagination_model),
view_model_(new views::ViewModel),
ALLOW_THIS_IN_INITIALIZER_LIST(
bounds_animator_(new views::BoundsAnimator(this))) {
AppsGridView* apps_grid_view = new AppsGridView(app_list_view,
pagination_model);
apps_grid_view->SetLayout(kPreferredIconDimension,
kPreferredCols,
kPreferredRows);
AddChildView(apps_grid_view);
view_model_->Add(apps_grid_view, kIndexAppsGrid);
PageSwitcher* page_switcher_view = new PageSwitcher(pagination_model);
AddChildView(page_switcher_view);
view_model_->Add(page_switcher_view, kIndexPageSwitcher);
SearchResultListView* search_results_view = new SearchResultListView(
app_list_view);
AddChildView(search_results_view);
view_model_->Add(search_results_view, kIndexSearchResults);
}
ContentsView::~ContentsView() {
}
void ContentsView::SetModel(AppListModel* model) {
if (model) {
GetAppsGridView(view_model_.get())->SetModel(model->apps());
GetSearchResultListView(view_model_.get())->SetResults(model->results());
} else {
GetAppsGridView(view_model_.get())->SetModel(NULL);
GetSearchResultListView(view_model_.get())->SetResults(NULL);
}
}
void ContentsView::SetShowState(ShowState show_state) {
if (show_state_ == show_state)
return;
show_state_ = show_state;
ShowStateChanged();
}
void ContentsView::ShowStateChanged() {
if (show_state_ == SHOW_SEARCH_RESULTS) {
// TODO(xiyuan): Highlight default match instead of the first.
SearchResultListView* results_view =
GetSearchResultListView(view_model_.get());
if (results_view->visible())
results_view->SetSelectedIndex(0);
}
AnimateToIdealBounds();
}
void ContentsView::CalculateIdealBounds() {
gfx::Rect rect(GetContentsBounds());
if (rect.IsEmpty())
return;
const int x = rect.x();
const int width = rect.width();
// AppsGridView and PageSwitcher uses a vertical box layout.
int y = rect.y();
const int grid_height =
GetAppsGridView(view_model_.get())->GetPreferredSize().height();
gfx::Rect grid_frame(gfx::Point(x, y), gfx::Size(width, grid_height));
grid_frame = rect.Intersect(grid_frame);
y = grid_frame.bottom();
const int page_switcher_height = rect.bottom() - y;
gfx::Rect page_switcher_frame(gfx::Point(x, y),
gfx::Size(width, page_switcher_height));
page_switcher_frame = rect.Intersect(page_switcher_frame);
// SearchResultListView occupies the whole space when visible.
gfx::Rect results_frame(rect);
// Offsets apps grid, page switcher and result list based on |show_state_|.
// SearchResultListView is on top of apps grid + page switcher. Visible view
// is left in visible area and invisible ones is put out of the visible area.
int contents_area_height = rect.height();
switch (show_state_) {
case SHOW_APPS:
results_frame.Offset(0, -contents_area_height);
break;
case SHOW_SEARCH_RESULTS:
grid_frame.Offset(0, contents_area_height);
page_switcher_frame.Offset(0, contents_area_height);
break;
default:
NOTREACHED() << "Unknown show_state_ " << show_state_;
break;
}
view_model_->set_ideal_bounds(kIndexAppsGrid, grid_frame);
view_model_->set_ideal_bounds(kIndexPageSwitcher, page_switcher_frame);
view_model_->set_ideal_bounds(kIndexSearchResults, results_frame);
}
void ContentsView::AnimateToIdealBounds() {
CalculateIdealBounds();
for (int i = 0; i < view_model_->view_size(); ++i) {
bounds_animator_->AnimateViewTo(view_model_->view_at(i),
view_model_->ideal_bounds(i));
}
}
void ContentsView::ShowSearchResults(bool show) {
SetShowState(show ? SHOW_SEARCH_RESULTS : SHOW_APPS);
}
gfx::Size ContentsView::GetPreferredSize() {
const gfx::Size grid_size =
GetAppsGridView(view_model_.get())->GetPreferredSize();
const gfx::Size page_switcher_size =
GetPageSwitcherView(view_model_.get())->GetPreferredSize();
const gfx::Size results_size =
GetSearchResultListView(view_model_.get())->GetPreferredSize();
int width = std::max(
std::max(grid_size.width(), page_switcher_size.width()),
results_size.width());
int height = std::max(grid_size.height() + page_switcher_size.height(),
results_size.height());
return gfx::Size(width, height);
}
void ContentsView::Layout() {
CalculateIdealBounds();
views::ViewModelUtils::SetViewBoundsToIdealBounds(*view_model_);
}
ui::GestureStatus ContentsView::OnGestureEvent(
const ui::GestureEvent& event) {
if (show_state_ != SHOW_APPS)
return ui::GESTURE_STATUS_UNKNOWN;
switch (event.type()) {
case ui::ET_GESTURE_SCROLL_BEGIN:
pagination_model_->StartScroll();
return ui::GESTURE_STATUS_CONSUMED;
case ui::ET_GESTURE_SCROLL_UPDATE:
// event.details.scroll_x() > 0 means moving contents to right. That is,
// transitioning to previous page.
pagination_model_->UpdateScroll(
event.details().scroll_x() / GetContentsBounds().width());
return ui::GESTURE_STATUS_CONSUMED;
case ui::ET_GESTURE_SCROLL_END:
pagination_model_->EndScroll();
return ui::GESTURE_STATUS_CONSUMED;
case ui::ET_SCROLL_FLING_START: {
pagination_model_->EndScroll();
if (fabs(event.details().velocity_x()) > kMinHorizVelocityToSwitchPage) {
pagination_model_->ResetTransitionAnimation();
pagination_model_->SelectPageRelative(
event.details().velocity_x() < 0 ? 1 : -1,
true);
}
return ui::GESTURE_STATUS_CONSUMED;
}
default:
break;
}
return ui::GESTURE_STATUS_UNKNOWN;
}
bool ContentsView::OnKeyPressed(const ui::KeyEvent& event) {
switch (show_state_) {
case SHOW_APPS:
return GetAppsGridView(view_model_.get())->OnKeyPressed(event);
case SHOW_SEARCH_RESULTS:
return GetSearchResultListView(view_model_.get())->OnKeyPressed(event);
default:
NOTREACHED() << "Unknown show state " << show_state_;
}
return false;
}
bool ContentsView::OnMouseWheel(const ui::MouseWheelEvent& event) {
if (show_state_ != SHOW_APPS)
return false;
if (abs(event.offset()) > kMinMouseWheelToSwitchPage) {
if (!pagination_model_->has_transition())
pagination_model_->SelectPageRelative(event.offset() > 0 ? -1 : 1, true);
return true;
}
return false;
}
bool ContentsView::OnScrollEvent(const ui::ScrollEvent& event) {
if (show_state_ != SHOW_APPS)
return false;
if (abs(event.x_offset()) > kMinScrollToSwitchPage) {
if (!pagination_model_->has_transition()) {
pagination_model_->SelectPageRelative(event.x_offset() > 0 ? 1 : -1,
true);
}
return true;
}
return false;
}
} // namespace app_list
<commit_msg>app_list: Swap two-finger scroll direction.<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 "ui/app_list/contents_view.h"
#include <algorithm>
#include "ui/app_list/app_list_view.h"
#include "ui/app_list/apps_grid_view.h"
#include "ui/app_list/page_switcher.h"
#include "ui/app_list/pagination_model.h"
#include "ui/app_list/search_result_list_view.h"
#include "ui/base/event.h"
#include "ui/views/animation/bounds_animator.h"
#include "ui/views/view_model.h"
#include "ui/views/view_model_utils.h"
namespace app_list {
namespace {
const int kPreferredIconDimension = 48;
const int kPreferredCols = 4;
const int kPreferredRows = 4;
// Indexes of interesting views in ViewModel of ContentsView.
const int kIndexAppsGrid = 0;
const int kIndexPageSwitcher = 1;
const int kIndexSearchResults = 2;
const int kMinMouseWheelToSwitchPage = 20;
const int kMinScrollToSwitchPage = 20;
const int kMinHorizVelocityToSwitchPage = 1100;
// Helpers to get certain child view from |model|.
AppsGridView* GetAppsGridView(views::ViewModel* model) {
return static_cast<AppsGridView*>(model->view_at(kIndexAppsGrid));
}
PageSwitcher* GetPageSwitcherView(views::ViewModel* model) {
return static_cast<PageSwitcher*>(model->view_at(kIndexPageSwitcher));
}
SearchResultListView* GetSearchResultListView(views::ViewModel* model) {
return static_cast<SearchResultListView*>(
model->view_at(kIndexSearchResults));
}
} // namespace
ContentsView::ContentsView(AppListView* app_list_view,
PaginationModel* pagination_model)
: show_state_(SHOW_APPS),
pagination_model_(pagination_model),
view_model_(new views::ViewModel),
ALLOW_THIS_IN_INITIALIZER_LIST(
bounds_animator_(new views::BoundsAnimator(this))) {
AppsGridView* apps_grid_view = new AppsGridView(app_list_view,
pagination_model);
apps_grid_view->SetLayout(kPreferredIconDimension,
kPreferredCols,
kPreferredRows);
AddChildView(apps_grid_view);
view_model_->Add(apps_grid_view, kIndexAppsGrid);
PageSwitcher* page_switcher_view = new PageSwitcher(pagination_model);
AddChildView(page_switcher_view);
view_model_->Add(page_switcher_view, kIndexPageSwitcher);
SearchResultListView* search_results_view = new SearchResultListView(
app_list_view);
AddChildView(search_results_view);
view_model_->Add(search_results_view, kIndexSearchResults);
}
ContentsView::~ContentsView() {
}
void ContentsView::SetModel(AppListModel* model) {
if (model) {
GetAppsGridView(view_model_.get())->SetModel(model->apps());
GetSearchResultListView(view_model_.get())->SetResults(model->results());
} else {
GetAppsGridView(view_model_.get())->SetModel(NULL);
GetSearchResultListView(view_model_.get())->SetResults(NULL);
}
}
void ContentsView::SetShowState(ShowState show_state) {
if (show_state_ == show_state)
return;
show_state_ = show_state;
ShowStateChanged();
}
void ContentsView::ShowStateChanged() {
if (show_state_ == SHOW_SEARCH_RESULTS) {
// TODO(xiyuan): Highlight default match instead of the first.
SearchResultListView* results_view =
GetSearchResultListView(view_model_.get());
if (results_view->visible())
results_view->SetSelectedIndex(0);
}
AnimateToIdealBounds();
}
void ContentsView::CalculateIdealBounds() {
gfx::Rect rect(GetContentsBounds());
if (rect.IsEmpty())
return;
const int x = rect.x();
const int width = rect.width();
// AppsGridView and PageSwitcher uses a vertical box layout.
int y = rect.y();
const int grid_height =
GetAppsGridView(view_model_.get())->GetPreferredSize().height();
gfx::Rect grid_frame(gfx::Point(x, y), gfx::Size(width, grid_height));
grid_frame = rect.Intersect(grid_frame);
y = grid_frame.bottom();
const int page_switcher_height = rect.bottom() - y;
gfx::Rect page_switcher_frame(gfx::Point(x, y),
gfx::Size(width, page_switcher_height));
page_switcher_frame = rect.Intersect(page_switcher_frame);
// SearchResultListView occupies the whole space when visible.
gfx::Rect results_frame(rect);
// Offsets apps grid, page switcher and result list based on |show_state_|.
// SearchResultListView is on top of apps grid + page switcher. Visible view
// is left in visible area and invisible ones is put out of the visible area.
int contents_area_height = rect.height();
switch (show_state_) {
case SHOW_APPS:
results_frame.Offset(0, -contents_area_height);
break;
case SHOW_SEARCH_RESULTS:
grid_frame.Offset(0, contents_area_height);
page_switcher_frame.Offset(0, contents_area_height);
break;
default:
NOTREACHED() << "Unknown show_state_ " << show_state_;
break;
}
view_model_->set_ideal_bounds(kIndexAppsGrid, grid_frame);
view_model_->set_ideal_bounds(kIndexPageSwitcher, page_switcher_frame);
view_model_->set_ideal_bounds(kIndexSearchResults, results_frame);
}
void ContentsView::AnimateToIdealBounds() {
CalculateIdealBounds();
for (int i = 0; i < view_model_->view_size(); ++i) {
bounds_animator_->AnimateViewTo(view_model_->view_at(i),
view_model_->ideal_bounds(i));
}
}
void ContentsView::ShowSearchResults(bool show) {
SetShowState(show ? SHOW_SEARCH_RESULTS : SHOW_APPS);
}
gfx::Size ContentsView::GetPreferredSize() {
const gfx::Size grid_size =
GetAppsGridView(view_model_.get())->GetPreferredSize();
const gfx::Size page_switcher_size =
GetPageSwitcherView(view_model_.get())->GetPreferredSize();
const gfx::Size results_size =
GetSearchResultListView(view_model_.get())->GetPreferredSize();
int width = std::max(
std::max(grid_size.width(), page_switcher_size.width()),
results_size.width());
int height = std::max(grid_size.height() + page_switcher_size.height(),
results_size.height());
return gfx::Size(width, height);
}
void ContentsView::Layout() {
CalculateIdealBounds();
views::ViewModelUtils::SetViewBoundsToIdealBounds(*view_model_);
}
ui::GestureStatus ContentsView::OnGestureEvent(
const ui::GestureEvent& event) {
if (show_state_ != SHOW_APPS)
return ui::GESTURE_STATUS_UNKNOWN;
switch (event.type()) {
case ui::ET_GESTURE_SCROLL_BEGIN:
pagination_model_->StartScroll();
return ui::GESTURE_STATUS_CONSUMED;
case ui::ET_GESTURE_SCROLL_UPDATE:
// event.details.scroll_x() > 0 means moving contents to right. That is,
// transitioning to previous page.
pagination_model_->UpdateScroll(
event.details().scroll_x() / GetContentsBounds().width());
return ui::GESTURE_STATUS_CONSUMED;
case ui::ET_GESTURE_SCROLL_END:
pagination_model_->EndScroll();
return ui::GESTURE_STATUS_CONSUMED;
case ui::ET_SCROLL_FLING_START: {
pagination_model_->EndScroll();
if (fabs(event.details().velocity_x()) > kMinHorizVelocityToSwitchPage) {
pagination_model_->ResetTransitionAnimation();
pagination_model_->SelectPageRelative(
event.details().velocity_x() < 0 ? 1 : -1,
true);
}
return ui::GESTURE_STATUS_CONSUMED;
}
default:
break;
}
return ui::GESTURE_STATUS_UNKNOWN;
}
bool ContentsView::OnKeyPressed(const ui::KeyEvent& event) {
switch (show_state_) {
case SHOW_APPS:
return GetAppsGridView(view_model_.get())->OnKeyPressed(event);
case SHOW_SEARCH_RESULTS:
return GetSearchResultListView(view_model_.get())->OnKeyPressed(event);
default:
NOTREACHED() << "Unknown show state " << show_state_;
}
return false;
}
bool ContentsView::OnMouseWheel(const ui::MouseWheelEvent& event) {
if (show_state_ != SHOW_APPS)
return false;
if (abs(event.offset()) > kMinMouseWheelToSwitchPage) {
if (!pagination_model_->has_transition())
pagination_model_->SelectPageRelative(event.offset() > 0 ? -1 : 1, true);
return true;
}
return false;
}
bool ContentsView::OnScrollEvent(const ui::ScrollEvent& event) {
if (show_state_ != SHOW_APPS)
return false;
if (abs(event.x_offset()) > kMinScrollToSwitchPage) {
if (!pagination_model_->has_transition()) {
pagination_model_->SelectPageRelative(event.x_offset() > 0 ? -1 : 1,
true);
}
return true;
}
return false;
}
} // namespace app_list
<|endoftext|> |
<commit_before>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#pragma once
template <class TBlockAttributes>
void
SmallHeapBlockT<TBlockAttributes>::SetAttributes(void * address, unsigned char attributes)
{
Assert(this->address != nullptr);
Assert(this->segment != nullptr);
ushort index = GetAddressIndex(address);
Assert(this->ObjectInfo(index) == 0);
Assert(index != SmallHeapBlockT<TBlockAttributes>::InvalidAddressBit);
ObjectInfo(index) = attributes;
}
inline
IdleDecommitPageAllocator*
HeapBlock::GetPageAllocator(Recycler* recycler)
{
switch (this->GetHeapBlockType())
{
case SmallLeafBlockType:
case MediumLeafBlockType:
return recycler->GetRecyclerLeafPageAllocator();
case LargeBlockType:
return recycler->GetRecyclerLargeBlockPageAllocator();
#ifdef RECYCLER_WRITE_BARRIER
case SmallNormalBlockWithBarrierType:
case SmallFinalizableBlockWithBarrierType:
case MediumNormalBlockWithBarrierType:
case MediumFinalizableBlockWithBarrierType:
#ifdef RECYCLER_WRITE_BARRIER_ALLOC_THREAD_PAGE
return recycler->GetRecyclerLeafPageAllocator();
#elif defined(RECYCLER_WRITE_BARRIER_ALLOC_SEPARATE_PAGE)
return recycler->GetRecyclerWithBarrierPageAllocator();
#endif
#endif
default:
return recycler->GetRecyclerPageAllocator();
};
}
template <class TBlockAttributes>
template <class Fn>
void SmallHeapBlockT<TBlockAttributes>::ForEachAllocatedObject(Fn fn)
{
uint const objectBitDelta = this->GetObjectBitDelta();
SmallHeapBlockBitVector * free = this->EnsureFreeBitVector();
char * address = this->GetAddress();
uint objectSize = this->GetObjectSize();
for (uint i = 0; i < objectCount; i++)
{
if (!free->Test(i * objectBitDelta))
{
fn(i, address + i * objectSize);
}
}
}
template <class TBlockAttributes>
template <typename Fn>
void SmallHeapBlockT<TBlockAttributes>::ForEachAllocatedObject(ObjectInfoBits attributes, Fn fn)
{
ForEachAllocatedObject([=](uint index, void * objectAddress)
{
if ((ObjectInfo(index) & attributes) != 0)
{
fn(index, objectAddress);
}
});
};
template <class TBlockAttributes>
template <typename Fn>
void SmallHeapBlockT<TBlockAttributes>::ScanNewImplicitRootsBase(Fn fn)
{
uint const localObjectCount = this->objectCount;
// NOTE: we no longer track the mark count as we mark. So this value
// is basically the mark count we set during the initial implicit root scan
// plus any subsequent new implicit root scan.
uint localMarkCount = this->markCount;
if (localMarkCount == localObjectCount)
{
// The block is full when we first do the initial implicit root scan
// So there can't be any new implicit roots
return;
}
#if DBG
HeapBlockMap& map = this->GetRecycler()->heapBlockMap;
ushort newlyMarkedCountForPage[TBlockAttributes::PageCount];
for (uint i = 0; i < TBlockAttributes::PageCount; i++)
{
newlyMarkedCountForPage[i] = 0;
}
#endif
uint const localObjectBitDelta = this->GetObjectBitDelta();
uint const localObjectSize = this->GetObjectSize();
Assert(localObjectSize <= HeapConstants::MaxMediumObjectSize);
SmallHeapBlockBitVector * mark = this->GetMarkedBitVector();
char * address = this->GetAddress();
for (uint i = 0; i < localObjectCount; i++)
{
if ((this->ObjectInfo(i) & ImplicitRootBit) != 0
&& !mark->TestAndSet(i * localObjectBitDelta))
{
uint objectOffset = i * localObjectSize;
localMarkCount++;
#if DBG
uint pageNumber = objectOffset / AutoSystemInfo::PageSize;
Assert(pageNumber < TBlockAttributes::PageCount);
newlyMarkedCountForPage[pageNumber]++;
#endif
fn(address + objectOffset, localObjectSize);
}
}
Assert(localMarkCount <= USHRT_MAX);
#if DBG
// Add newly marked count
for (uint i = 0; i < TBlockAttributes::PageCount; i++)
{
char* pageAddress = address + (AutoSystemInfo::PageSize * i);
ushort oldPageMarkCount = map.GetPageMarkCount(pageAddress);
map.SetPageMarkCount(pageAddress, oldPageMarkCount + newlyMarkedCountForPage[i]);
}
#endif
this->markCount = (ushort)localMarkCount;
}
template <class TBlockAttributes>
bool
SmallHeapBlockT<TBlockAttributes>::FindImplicitRootObject(void* candidate, Recycler* recycler, RecyclerHeapObjectInfo& heapObject)
{
ushort index = GetAddressIndex(candidate);
if (index == InvalidAddressBit)
{
return false;
}
byte& attributes = ObjectInfo(index);
heapObject = RecyclerHeapObjectInfo(candidate, recycler, this, &attributes);
return true;
}
template <bool doSpecialMark, typename Fn>
bool
HeapBlock::UpdateAttributesOfMarkedObjects(MarkContext * markContext, void * objectAddress, size_t objectSize, unsigned char attributes, Fn fn)
{
Assert(GetHeapBlockType() != HeapBlock::HeapBlockType::SmallRecyclerVisitedHostBlockType && GetHeapBlockType() != HeapBlock::HeapBlockType::MediumRecyclerVisitedHostBlockType);
bool noOOMDuringMark = true;
if (attributes & TrackBit)
{
FinalizableObject * trackedObject = (FinalizableObject *)objectAddress;
#if ENABLE_PARTIAL_GC
if (!markContext->GetRecycler()->inPartialCollectMode)
#endif
{
#if ENABLE_CONCURRENT_GC
if (markContext->GetRecycler()->DoQueueTrackedObject())
{
if (!markContext->AddTrackedObject(trackedObject))
{
noOOMDuringMark = false;
}
}
else
#endif
{
// Process the tracked object right now
markContext->MarkTrackedObject(trackedObject);
}
}
if (noOOMDuringMark)
{
// Object has been successfully processed, so clear NewTrackBit
attributes &= ~NewTrackBit;
}
else
{
// Set the NewTrackBit, so that the main thread will redo tracking
attributes |= NewTrackBit;
noOOMDuringMark = false;
}
fn(attributes);
}
// only need to scan non-leaf objects
if ((attributes & LeafBit) == 0)
{
if (!markContext->AddMarkedObject(objectAddress, objectSize))
{
noOOMDuringMark = false;
}
}
// Special mark-time behavior for finalizable objects on certain GC's
if (doSpecialMark)
{
if (attributes & FinalizeBit)
{
FinalizableObject * trackedObject = (FinalizableObject *)objectAddress;
trackedObject->OnMark();
}
}
#ifdef RECYCLER_STATS
RECYCLER_STATS_INTERLOCKED_INC(markContext->GetRecycler(), markData.markCount);
RECYCLER_STATS_INTERLOCKED_ADD(markContext->GetRecycler(), markData.markBytes, objectSize);
// Don't count track or finalize it if we still have to process it in thread because of OOM
if ((attributes & (TrackBit | NewTrackBit)) != (TrackBit | NewTrackBit))
{
// Only count those we have queued, so we don't double count
if (attributes & TrackBit)
{
RECYCLER_STATS_INTERLOCKED_INC(markContext->GetRecycler(), trackCount);
}
if (attributes & FinalizeBit)
{
// we counted the finalizable object here,
// turn off the new bit so we don't count it again
// on Rescan
attributes &= ~NewFinalizeBit;
fn(attributes);
RECYCLER_STATS_INTERLOCKED_INC(markContext->GetRecycler(), finalizeCount);
}
}
#endif
return noOOMDuringMark;
}
<commit_msg>Fix OSX build with RECYCLER_VISITED_HOST ifdef check<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#pragma once
template <class TBlockAttributes>
void
SmallHeapBlockT<TBlockAttributes>::SetAttributes(void * address, unsigned char attributes)
{
Assert(this->address != nullptr);
Assert(this->segment != nullptr);
ushort index = GetAddressIndex(address);
Assert(this->ObjectInfo(index) == 0);
Assert(index != SmallHeapBlockT<TBlockAttributes>::InvalidAddressBit);
ObjectInfo(index) = attributes;
}
inline
IdleDecommitPageAllocator*
HeapBlock::GetPageAllocator(Recycler* recycler)
{
switch (this->GetHeapBlockType())
{
case SmallLeafBlockType:
case MediumLeafBlockType:
return recycler->GetRecyclerLeafPageAllocator();
case LargeBlockType:
return recycler->GetRecyclerLargeBlockPageAllocator();
#ifdef RECYCLER_WRITE_BARRIER
case SmallNormalBlockWithBarrierType:
case SmallFinalizableBlockWithBarrierType:
case MediumNormalBlockWithBarrierType:
case MediumFinalizableBlockWithBarrierType:
#ifdef RECYCLER_WRITE_BARRIER_ALLOC_THREAD_PAGE
return recycler->GetRecyclerLeafPageAllocator();
#elif defined(RECYCLER_WRITE_BARRIER_ALLOC_SEPARATE_PAGE)
return recycler->GetRecyclerWithBarrierPageAllocator();
#endif
#endif
default:
return recycler->GetRecyclerPageAllocator();
};
}
template <class TBlockAttributes>
template <class Fn>
void SmallHeapBlockT<TBlockAttributes>::ForEachAllocatedObject(Fn fn)
{
uint const objectBitDelta = this->GetObjectBitDelta();
SmallHeapBlockBitVector * free = this->EnsureFreeBitVector();
char * address = this->GetAddress();
uint objectSize = this->GetObjectSize();
for (uint i = 0; i < objectCount; i++)
{
if (!free->Test(i * objectBitDelta))
{
fn(i, address + i * objectSize);
}
}
}
template <class TBlockAttributes>
template <typename Fn>
void SmallHeapBlockT<TBlockAttributes>::ForEachAllocatedObject(ObjectInfoBits attributes, Fn fn)
{
ForEachAllocatedObject([=](uint index, void * objectAddress)
{
if ((ObjectInfo(index) & attributes) != 0)
{
fn(index, objectAddress);
}
});
};
template <class TBlockAttributes>
template <typename Fn>
void SmallHeapBlockT<TBlockAttributes>::ScanNewImplicitRootsBase(Fn fn)
{
uint const localObjectCount = this->objectCount;
// NOTE: we no longer track the mark count as we mark. So this value
// is basically the mark count we set during the initial implicit root scan
// plus any subsequent new implicit root scan.
uint localMarkCount = this->markCount;
if (localMarkCount == localObjectCount)
{
// The block is full when we first do the initial implicit root scan
// So there can't be any new implicit roots
return;
}
#if DBG
HeapBlockMap& map = this->GetRecycler()->heapBlockMap;
ushort newlyMarkedCountForPage[TBlockAttributes::PageCount];
for (uint i = 0; i < TBlockAttributes::PageCount; i++)
{
newlyMarkedCountForPage[i] = 0;
}
#endif
uint const localObjectBitDelta = this->GetObjectBitDelta();
uint const localObjectSize = this->GetObjectSize();
Assert(localObjectSize <= HeapConstants::MaxMediumObjectSize);
SmallHeapBlockBitVector * mark = this->GetMarkedBitVector();
char * address = this->GetAddress();
for (uint i = 0; i < localObjectCount; i++)
{
if ((this->ObjectInfo(i) & ImplicitRootBit) != 0
&& !mark->TestAndSet(i * localObjectBitDelta))
{
uint objectOffset = i * localObjectSize;
localMarkCount++;
#if DBG
uint pageNumber = objectOffset / AutoSystemInfo::PageSize;
Assert(pageNumber < TBlockAttributes::PageCount);
newlyMarkedCountForPage[pageNumber]++;
#endif
fn(address + objectOffset, localObjectSize);
}
}
Assert(localMarkCount <= USHRT_MAX);
#if DBG
// Add newly marked count
for (uint i = 0; i < TBlockAttributes::PageCount; i++)
{
char* pageAddress = address + (AutoSystemInfo::PageSize * i);
ushort oldPageMarkCount = map.GetPageMarkCount(pageAddress);
map.SetPageMarkCount(pageAddress, oldPageMarkCount + newlyMarkedCountForPage[i]);
}
#endif
this->markCount = (ushort)localMarkCount;
}
template <class TBlockAttributes>
bool
SmallHeapBlockT<TBlockAttributes>::FindImplicitRootObject(void* candidate, Recycler* recycler, RecyclerHeapObjectInfo& heapObject)
{
ushort index = GetAddressIndex(candidate);
if (index == InvalidAddressBit)
{
return false;
}
byte& attributes = ObjectInfo(index);
heapObject = RecyclerHeapObjectInfo(candidate, recycler, this, &attributes);
return true;
}
template <bool doSpecialMark, typename Fn>
bool
HeapBlock::UpdateAttributesOfMarkedObjects(MarkContext * markContext, void * objectAddress, size_t objectSize, unsigned char attributes, Fn fn)
{
#ifdef RECYCLER_VISITED_HOST
Assert(GetHeapBlockType() != HeapBlock::HeapBlockType::SmallRecyclerVisitedHostBlockType && GetHeapBlockType() != HeapBlock::HeapBlockType::MediumRecyclerVisitedHostBlockType);
#endif
bool noOOMDuringMark = true;
if (attributes & TrackBit)
{
FinalizableObject * trackedObject = (FinalizableObject *)objectAddress;
#if ENABLE_PARTIAL_GC
if (!markContext->GetRecycler()->inPartialCollectMode)
#endif
{
#if ENABLE_CONCURRENT_GC
if (markContext->GetRecycler()->DoQueueTrackedObject())
{
if (!markContext->AddTrackedObject(trackedObject))
{
noOOMDuringMark = false;
}
}
else
#endif
{
// Process the tracked object right now
markContext->MarkTrackedObject(trackedObject);
}
}
if (noOOMDuringMark)
{
// Object has been successfully processed, so clear NewTrackBit
attributes &= ~NewTrackBit;
}
else
{
// Set the NewTrackBit, so that the main thread will redo tracking
attributes |= NewTrackBit;
noOOMDuringMark = false;
}
fn(attributes);
}
// only need to scan non-leaf objects
if ((attributes & LeafBit) == 0)
{
if (!markContext->AddMarkedObject(objectAddress, objectSize))
{
noOOMDuringMark = false;
}
}
// Special mark-time behavior for finalizable objects on certain GC's
if (doSpecialMark)
{
if (attributes & FinalizeBit)
{
FinalizableObject * trackedObject = (FinalizableObject *)objectAddress;
trackedObject->OnMark();
}
}
#ifdef RECYCLER_STATS
RECYCLER_STATS_INTERLOCKED_INC(markContext->GetRecycler(), markData.markCount);
RECYCLER_STATS_INTERLOCKED_ADD(markContext->GetRecycler(), markData.markBytes, objectSize);
// Don't count track or finalize it if we still have to process it in thread because of OOM
if ((attributes & (TrackBit | NewTrackBit)) != (TrackBit | NewTrackBit))
{
// Only count those we have queued, so we don't double count
if (attributes & TrackBit)
{
RECYCLER_STATS_INTERLOCKED_INC(markContext->GetRecycler(), trackCount);
}
if (attributes & FinalizeBit)
{
// we counted the finalizable object here,
// turn off the new bit so we don't count it again
// on Rescan
attributes &= ~NewFinalizeBit;
fn(attributes);
RECYCLER_STATS_INTERLOCKED_INC(markContext->GetRecycler(), finalizeCount);
}
}
#endif
return noOOMDuringMark;
}
<|endoftext|> |
<commit_before>//===---- LoadStoreOpts.cpp - SIL Load/Store Optimizations Forwarding ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This pass eliminates redundent loads, dead stores, and performs load
// forwarding.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "load-store-opts"
#include "swift/SILPasses/Passes.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SILAnalysis/AliasAnalysis.h"
#include "swift/SILPasses/Utils/Local.h"
#include "swift/SILPasses/Transforms.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
STATISTIC(NumDeadStores, "Number of dead stores removed");
STATISTIC(NumDupLoads, "Number of dup loads removed");
STATISTIC(NumForwardedLoads, "Number of loads forwarded");
//===----------------------------------------------------------------------===//
// Utility Functions
//===----------------------------------------------------------------------===//
/// Given the already emitted load PrevLI, see if we can find a projection
/// address path to LI. If we can, emit the corresponding aggregate projection
/// insts and return the last such inst.
static SILValue findExtractPathBetweenValues(LoadInst *PrevLI, LoadInst *LI) {
// Attempt to find the projection path from LI -> PrevLI.
SILValue PrevLIOp = PrevLI->getOperand();
SILValue LIOp = LI->getOperand();
llvm::SmallVector<Projection, 4> ProjectionPath;
// If we failed to find the path, return an empty value early.
if (!findAddressProjectionPathBetweenValues(PrevLIOp, LIOp, ProjectionPath))
return SILValue();
// If we found a projection path, but there are no projections, then the two
// loads must be the same, return PrevLI.
if (ProjectionPath.empty())
return PrevLI;
// Ok, at this point we know that we can construct our aggregate projections
// from our list of address projections.
SILValue LastExtract = PrevLI;
SILBuilder Builder(LI);
while (!ProjectionPath.empty()) {
auto P = ProjectionPath.pop_back_val();
if (auto *D = P.getDecl()) {
assert(P.getNominalType() != Projection::NominalType::Class &&
"Aggregate projections do not exist for classes.");
LastExtract = Builder.createStructExtract(LI->getLoc(), LastExtract,
D,
P.getType().getObjectType());
assert(cast<StructExtractInst>(*LastExtract).getStructDecl() &&
"Instruction must have a struct decl!");
} else {
LastExtract = Builder.createTupleExtract(LI->getLoc(), LastExtract,
P.getIndex(),
P.getType().getObjectType());
assert(cast<TupleExtractInst>(*LastExtract).getTupleType() &&
"Instruction must have a tuple type!");
}
}
// Return the last extract we created.
return LastExtract;
}
static void
invalidateAliasingLoads(SILInstruction *Inst,
llvm::SmallPtrSetImpl<LoadInst *> &Loads,
AliasAnalysis *AA) {
llvm::SmallVector<LoadInst *, 4> InvalidatedLoadList;
for (auto *LI : Loads)
if (AA->mayWriteToMemory(Inst, LI->getOperand()))
InvalidatedLoadList.push_back(LI);
for (auto *LI : InvalidatedLoadList) {
DEBUG(llvm::dbgs() << " Found an instruction that writes to memory "
"such that a load is invalidated:" << *LI);
Loads.erase(LI);
}
}
//===----------------------------------------------------------------------===//
// Implementation
//===----------------------------------------------------------------------===//
/// \brief Promote stored values to loads, remove dead stores and merge
/// duplicated loads.
bool performLoadStoreOptimizations(SILBasicBlock *BB, AliasAnalysis *AA) {
bool Changed = false;
StoreInst *PrevStore = nullptr;
// This is a list of LoadInst instructions that reference memory locations
// were not clobbered by instructions that write to memory. In other words
// the SSA value of the load is known to be the same value as the referenced
// pointer. The values in the list are potentially updated on each iteration
// of the loop below.
llvm::SmallPtrSet<LoadInst *, 8> Loads;
auto II = BB->begin(), E = BB->end();
while (II != E) {
SILInstruction *Inst = II++;
DEBUG(llvm::dbgs() << "Visiting: " << *Inst);
// This is a StoreInst. Let's see if we can remove the previous stores.
if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
// If we are storing a value that is available in the load list then we
// know that no one clobbered that address and the current store is
// redundant and we can remove it.
if (LoadInst *LdSrc = dyn_cast<LoadInst>(SI->getSrc())) {
// Check that the loaded value is live and that the destination address
// is the same as the loaded address.
if (Loads.count(LdSrc) && LdSrc->getOperand() == SI->getDest()) {
Changed = true;
recursivelyDeleteTriviallyDeadInstructions(SI, true);
NumDeadStores++;
continue;
}
}
// Invalidate any load that we can not prove does not read from the stores
// destination.
invalidateAliasingLoads(Inst, Loads, AA);
// If we are storing to the previously stored address then delete the old
// store.
if (PrevStore && PrevStore->getDest() == SI->getDest()) {
DEBUG(llvm::dbgs() << " Found a dead previous store... Removing...:"
<< *PrevStore);
Changed = true;
recursivelyDeleteTriviallyDeadInstructions(PrevStore, true);
PrevStore = SI;
NumDeadStores++;
continue;
}
PrevStore = SI;
continue;
}
if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
// If we are loading a value that we just saved then use the saved value.
if (PrevStore && PrevStore->getDest() == LI->getOperand()) {
DEBUG(llvm::dbgs() << " Forwarding store from: " << *PrevStore);
SILValue(LI, 0).replaceAllUsesWith(PrevStore->getSrc());
recursivelyDeleteTriviallyDeadInstructions(LI, true);
Changed = true;
NumForwardedLoads++;
continue;
}
// Promote partial loads.
// Check that we are loading a struct element:
if (auto *SEAI = dyn_cast<StructElementAddrInst>(LI->getOperand())) {
// And that the previous store stores into that struct.
if (PrevStore && PrevStore->getDest() == SEAI->getOperand()) {
// And that the stored value is a struct construction instruction:
if (auto *SI = dyn_cast<StructInst>(PrevStore->getSrc())) {
DEBUG(llvm::dbgs() << " Forwarding element store from: " <<
*PrevStore);
unsigned FieldNo = SEAI->getFieldNo();
SILValue(LI, 0).replaceAllUsesWith(SI->getOperand(FieldNo));
recursivelyDeleteTriviallyDeadInstructions(LI, true);
Changed = true;
NumForwardedLoads++;
continue;
}
}
}
// Search the previous loads and replace the current load with one of the
// previous loads.
for (auto PrevLI : Loads) {
SILValue ForwardingExtract = findExtractPathBetweenValues(PrevLI, LI);
if (!ForwardingExtract)
continue;
DEBUG(llvm::dbgs() << " Replacing with previous load: "
<< *ForwardingExtract);
SILValue(LI, 0).replaceAllUsesWith(ForwardingExtract);
recursivelyDeleteTriviallyDeadInstructions(LI, true);
Changed = true;
LI = nullptr;
NumDupLoads++;
break;
}
if (LI)
Loads.insert(LI);
continue;
}
// Retains write to memory but they don't affect loads and stores.
if (isa<StrongRetainInst>(Inst)) {
DEBUG(llvm::dbgs() << " Found strong retain, does not affect loads and"
" stores.\n");
continue;
}
// Dealloc stack does not affect loads and stores.
if (isa<DeallocStackInst>(Inst)) {
DEBUG(llvm::dbgs() << "Found a dealloc stack. Does not affect loads and "
"stores.\n");
continue;
}
if (auto *AI = dyn_cast<ApplyInst>(Inst))
if (auto *BI = dyn_cast<BuiltinFunctionRefInst>(&*AI->getCallee()))
if (isReadNone(BI)) {
DEBUG(llvm::dbgs() << " Found readnone builtin, does not affect "
"loads and stores.\n");
continue;
}
// cond_fail does not read/write memory in a manner that we care about.
if (isa<CondFailInst>(Inst)) {
DEBUG(llvm::dbgs() << " Found a cond fail, does not affect "
"loads and stores.\n");
continue;
}
// All other instructions that read from memory invalidate the store.
if (Inst->mayReadFromMemory()) {
DEBUG(llvm::dbgs() << " Found an instruction that reads from memory."
" Invalidating store.\n");
PrevStore = nullptr;
}
// If we have an instruction that may write to memory and we can not prove
// that it and its operands can not alias a load we have visited, invalidate
// that load.
if (Inst->mayWriteToMemory()) {
// Invalidate any load that we can not prove does not read from one of the
// writing instructions operands.
invalidateAliasingLoads(Inst, Loads, AA);
PrevStore = nullptr;
}
}
return Changed;
}
//===----------------------------------------------------------------------===//
// Top Level Entry Point
//===----------------------------------------------------------------------===//
namespace {
class LoadStoreOpts : public SILFunctionTransform {
/// The entry point to the transformation.
void run() {
SILFunction &F = *getFunction();
DEBUG(llvm::dbgs() << "***** Load Store Elimination on function: "
<< F.getName() << " *****\n");
AliasAnalysis *AA = PM->getAnalysis<AliasAnalysis>();
// Remove dead stores, merge duplicate loads, and forward stores to loads.
bool Changed = false;
for (auto &BB : F)
Changed |= performLoadStoreOptimizations(&BB, AA);
if (Changed)
invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions);
}
StringRef getName() override { return "SIL Load Store Opts"; }
};
} // end anonymous namespace
SILTransform *swift::createLoadStoreOpts() {
return new LoadStoreOpts();
}
<commit_msg>[LoadStoreOpt] make sure Loads do not hold deleted SILInstructions.<commit_after>//===---- LoadStoreOpts.cpp - SIL Load/Store Optimizations Forwarding ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This pass eliminates redundent loads, dead stores, and performs load
// forwarding.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "load-store-opts"
#include "swift/SILPasses/Passes.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SILAnalysis/AliasAnalysis.h"
#include "swift/SILPasses/Utils/Local.h"
#include "swift/SILPasses/Transforms.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
STATISTIC(NumDeadStores, "Number of dead stores removed");
STATISTIC(NumDupLoads, "Number of dup loads removed");
STATISTIC(NumForwardedLoads, "Number of loads forwarded");
//===----------------------------------------------------------------------===//
// Utility Functions
//===----------------------------------------------------------------------===//
/// Given the already emitted load PrevLI, see if we can find a projection
/// address path to LI. If we can, emit the corresponding aggregate projection
/// insts and return the last such inst.
static SILValue findExtractPathBetweenValues(LoadInst *PrevLI, LoadInst *LI) {
// Attempt to find the projection path from LI -> PrevLI.
SILValue PrevLIOp = PrevLI->getOperand();
SILValue LIOp = LI->getOperand();
llvm::SmallVector<Projection, 4> ProjectionPath;
// If we failed to find the path, return an empty value early.
if (!findAddressProjectionPathBetweenValues(PrevLIOp, LIOp, ProjectionPath))
return SILValue();
// If we found a projection path, but there are no projections, then the two
// loads must be the same, return PrevLI.
if (ProjectionPath.empty())
return PrevLI;
// Ok, at this point we know that we can construct our aggregate projections
// from our list of address projections.
SILValue LastExtract = PrevLI;
SILBuilder Builder(LI);
while (!ProjectionPath.empty()) {
auto P = ProjectionPath.pop_back_val();
if (auto *D = P.getDecl()) {
assert(P.getNominalType() != Projection::NominalType::Class &&
"Aggregate projections do not exist for classes.");
LastExtract = Builder.createStructExtract(LI->getLoc(), LastExtract,
D,
P.getType().getObjectType());
assert(cast<StructExtractInst>(*LastExtract).getStructDecl() &&
"Instruction must have a struct decl!");
} else {
LastExtract = Builder.createTupleExtract(LI->getLoc(), LastExtract,
P.getIndex(),
P.getType().getObjectType());
assert(cast<TupleExtractInst>(*LastExtract).getTupleType() &&
"Instruction must have a tuple type!");
}
}
// Return the last extract we created.
return LastExtract;
}
static void
invalidateAliasingLoads(SILInstruction *Inst,
llvm::SmallPtrSetImpl<LoadInst *> &Loads,
AliasAnalysis *AA) {
llvm::SmallVector<LoadInst *, 4> InvalidatedLoadList;
for (auto *LI : Loads)
if (AA->mayWriteToMemory(Inst, LI->getOperand()))
InvalidatedLoadList.push_back(LI);
for (auto *LI : InvalidatedLoadList) {
DEBUG(llvm::dbgs() << " Found an instruction that writes to memory "
"such that a load is invalidated:" << *LI);
Loads.erase(LI);
}
}
//===----------------------------------------------------------------------===//
// Implementation
//===----------------------------------------------------------------------===//
/// \brief Promote stored values to loads, remove dead stores and merge
/// duplicated loads.
bool performLoadStoreOptimizations(SILBasicBlock *BB, AliasAnalysis *AA) {
bool Changed = false;
StoreInst *PrevStore = nullptr;
// This is a list of LoadInst instructions that reference memory locations
// were not clobbered by instructions that write to memory. In other words
// the SSA value of the load is known to be the same value as the referenced
// pointer. The values in the list are potentially updated on each iteration
// of the loop below.
llvm::SmallPtrSet<LoadInst *, 8> Loads;
auto II = BB->begin(), E = BB->end();
while (II != E) {
SILInstruction *Inst = II++;
DEBUG(llvm::dbgs() << "Visiting: " << *Inst);
// This is a StoreInst. Let's see if we can remove the previous stores.
if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
// If we are storing a value that is available in the load list then we
// know that no one clobbered that address and the current store is
// redundant and we can remove it.
if (LoadInst *LdSrc = dyn_cast<LoadInst>(SI->getSrc())) {
// Check that the loaded value is live and that the destination address
// is the same as the loaded address.
if (Loads.count(LdSrc) && LdSrc->getOperand() == SI->getDest()) {
Changed = true;
recursivelyDeleteTriviallyDeadInstructions(SI, true,
[&](SILInstruction *DeadI) {
if (LoadInst *LI = dyn_cast<LoadInst>(DeadI))
Loads.erase(LI);
});
NumDeadStores++;
continue;
}
}
// Invalidate any load that we can not prove does not read from the stores
// destination.
invalidateAliasingLoads(Inst, Loads, AA);
// If we are storing to the previously stored address then delete the old
// store.
if (PrevStore && PrevStore->getDest() == SI->getDest()) {
DEBUG(llvm::dbgs() << " Found a dead previous store... Removing...:"
<< *PrevStore);
Changed = true;
recursivelyDeleteTriviallyDeadInstructions(PrevStore, true,
[&](SILInstruction *DeadI) {
if (LoadInst *LI = dyn_cast<LoadInst>(DeadI))
Loads.erase(LI);
});
PrevStore = SI;
NumDeadStores++;
continue;
}
PrevStore = SI;
continue;
}
if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
// If we are loading a value that we just saved then use the saved value.
if (PrevStore && PrevStore->getDest() == LI->getOperand()) {
DEBUG(llvm::dbgs() << " Forwarding store from: " << *PrevStore);
SILValue(LI, 0).replaceAllUsesWith(PrevStore->getSrc());
recursivelyDeleteTriviallyDeadInstructions(LI, true,
[&](SILInstruction *DeadI) {
if (LoadInst *LI = dyn_cast<LoadInst>(DeadI))
Loads.erase(LI);
});
Changed = true;
NumForwardedLoads++;
continue;
}
// Promote partial loads.
// Check that we are loading a struct element:
if (auto *SEAI = dyn_cast<StructElementAddrInst>(LI->getOperand())) {
// And that the previous store stores into that struct.
if (PrevStore && PrevStore->getDest() == SEAI->getOperand()) {
// And that the stored value is a struct construction instruction:
if (auto *SI = dyn_cast<StructInst>(PrevStore->getSrc())) {
DEBUG(llvm::dbgs() << " Forwarding element store from: " <<
*PrevStore);
unsigned FieldNo = SEAI->getFieldNo();
SILValue(LI, 0).replaceAllUsesWith(SI->getOperand(FieldNo));
recursivelyDeleteTriviallyDeadInstructions(LI, true,
[&](SILInstruction *DeadI) {
if (LoadInst *LI = dyn_cast<LoadInst>(DeadI))
Loads.erase(LI);
});
Changed = true;
NumForwardedLoads++;
continue;
}
}
}
// Search the previous loads and replace the current load with one of the
// previous loads.
for (auto PrevLI : Loads) {
SILValue ForwardingExtract = findExtractPathBetweenValues(PrevLI, LI);
if (!ForwardingExtract)
continue;
DEBUG(llvm::dbgs() << " Replacing with previous load: "
<< *ForwardingExtract);
SILValue(LI, 0).replaceAllUsesWith(ForwardingExtract);
recursivelyDeleteTriviallyDeadInstructions(LI, true,
[&](SILInstruction *DeadI) {
if (LoadInst *LI = dyn_cast<LoadInst>(DeadI))
Loads.erase(LI);
});
Changed = true;
LI = nullptr;
NumDupLoads++;
break;
}
if (LI)
Loads.insert(LI);
continue;
}
// Retains write to memory but they don't affect loads and stores.
if (isa<StrongRetainInst>(Inst)) {
DEBUG(llvm::dbgs() << " Found strong retain, does not affect loads and"
" stores.\n");
continue;
}
// Dealloc stack does not affect loads and stores.
if (isa<DeallocStackInst>(Inst)) {
DEBUG(llvm::dbgs() << "Found a dealloc stack. Does not affect loads and "
"stores.\n");
continue;
}
if (auto *AI = dyn_cast<ApplyInst>(Inst))
if (auto *BI = dyn_cast<BuiltinFunctionRefInst>(&*AI->getCallee()))
if (isReadNone(BI)) {
DEBUG(llvm::dbgs() << " Found readnone builtin, does not affect "
"loads and stores.\n");
continue;
}
// cond_fail does not read/write memory in a manner that we care about.
if (isa<CondFailInst>(Inst)) {
DEBUG(llvm::dbgs() << " Found a cond fail, does not affect "
"loads and stores.\n");
continue;
}
// All other instructions that read from memory invalidate the store.
if (Inst->mayReadFromMemory()) {
DEBUG(llvm::dbgs() << " Found an instruction that reads from memory."
" Invalidating store.\n");
PrevStore = nullptr;
}
// If we have an instruction that may write to memory and we can not prove
// that it and its operands can not alias a load we have visited, invalidate
// that load.
if (Inst->mayWriteToMemory()) {
// Invalidate any load that we can not prove does not read from one of the
// writing instructions operands.
invalidateAliasingLoads(Inst, Loads, AA);
PrevStore = nullptr;
}
}
return Changed;
}
//===----------------------------------------------------------------------===//
// Top Level Entry Point
//===----------------------------------------------------------------------===//
namespace {
class LoadStoreOpts : public SILFunctionTransform {
/// The entry point to the transformation.
void run() {
SILFunction &F = *getFunction();
DEBUG(llvm::dbgs() << "***** Load Store Elimination on function: "
<< F.getName() << " *****\n");
AliasAnalysis *AA = PM->getAnalysis<AliasAnalysis>();
// Remove dead stores, merge duplicate loads, and forward stores to loads.
bool Changed = false;
for (auto &BB : F)
Changed |= performLoadStoreOptimizations(&BB, AA);
if (Changed)
invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions);
}
StringRef getName() override { return "SIL Load Store Opts"; }
};
} // end anonymous namespace
SILTransform *swift::createLoadStoreOpts() {
return new LoadStoreOpts();
}
<|endoftext|> |
<commit_before>//===-- ELFTargetAsmInfo.cpp - ELF asm properties ---------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines target asm properties related what form asm statements
// should take in general on ELF-based targets
//
//===----------------------------------------------------------------------===//
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/GlobalVariable.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Target/ELFTargetAsmInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetData.h"
using namespace llvm;
ELFTargetAsmInfo::ELFTargetAsmInfo(const TargetMachine &TM) {
ETM = &TM;
TextSection_ = getUnnamedSection("\t.text", SectionFlags::Code);
DataSection_ = getUnnamedSection("\t.data", SectionFlags::Writeable);
BSSSection_ = getUnnamedSection("\t.bss",
SectionFlags::Writeable | SectionFlags::BSS);
ReadOnlySection_ = getNamedSection("\t.rodata", SectionFlags::None);
TLSDataSection_ = getNamedSection("\t.tdata",
SectionFlags::Writeable | SectionFlags::TLS);
TLSBSSSection_ = getNamedSection("\t.tbss",
SectionFlags::Writeable | SectionFlags::TLS | SectionFlags::BSS);
}
const Section*
ELFTargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const {
SectionKind::Kind Kind = SectionKindForGlobal(GV);
if (const Function *F = dyn_cast<Function>(GV)) {
switch (F->getLinkage()) {
default: assert(0 && "Unknown linkage type!");
case Function::InternalLinkage:
case Function::DLLExportLinkage:
case Function::ExternalLinkage:
return getTextSection_();
case Function::WeakLinkage:
case Function::LinkOnceLinkage:
std::string Name = UniqueSectionForGlobal(GV, Kind);
unsigned Flags = SectionFlagsForGlobal(GV, Name.c_str());
return getNamedSection(Name.c_str(), Flags);
}
} else if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
if (GVar->isWeakForLinker()) {
std::string Name = UniqueSectionForGlobal(GVar, Kind);
unsigned Flags = SectionFlagsForGlobal(GVar, Name.c_str());
return getNamedSection(Name.c_str(), Flags);
} else {
switch (Kind) {
case SectionKind::Data:
return getDataSection_();
case SectionKind::BSS:
// ELF targets usually have BSS sections
return getBSSSection_();
case SectionKind::ROData:
return getReadOnlySection_();
case SectionKind::RODataMergeStr:
return MergeableStringSection(GVar);
case SectionKind::RODataMergeConst:
return MergeableConstSection(GVar);
case SectionKind::ThreadData:
// ELF targets usually support TLS stuff
return getTLSDataSection_();
case SectionKind::ThreadBSS:
return getTLSBSSSection_();
default:
assert(0 && "Unsuported section kind for global");
}
}
} else
assert(0 && "Unsupported global");
}
const Section*
ELFTargetAsmInfo::MergeableConstSection(const GlobalVariable *GV) const {
const TargetData *TD = ETM->getTargetData();
Constant *C = cast<GlobalVariable>(GV)->getInitializer();
const Type *Type = C->getType();
// FIXME: string here is temporary, until stuff will fully land in.
// We cannot use {Four,Eight,Sixteen}ByteConstantSection here, since it's
// currently directly used by asmprinter.
unsigned Size = TD->getABITypeSize(Type);
if (Size == 4 || Size == 8 || Size == 16) {
std::string Name = ".rodata.cst" + utostr(Size);
return getNamedSection(Name.c_str(),
SectionFlags::setEntitySize(SectionFlags::Mergeable,
Size));
}
return getReadOnlySection_();
}
const Section*
ELFTargetAsmInfo::MergeableStringSection(const GlobalVariable *GV) const {
const TargetData *TD = ETM->getTargetData();
Constant *C = cast<GlobalVariable>(GV)->getInitializer();
const ConstantArray *CVA = cast<ConstantArray>(C);
const Type *Type = CVA->getType()->getElementType();
unsigned Size = TD->getABITypeSize(Type);
if (Size <= 16) {
// We also need alignment here
const TargetData *TD = ETM->getTargetData();
unsigned Align = TD->getPreferredAlignment(GV);
if (Align < Size)
Align = Size;
std::string Name = getCStringSection() + utostr(Size) + '.' + utostr(Align);
unsigned Flags = SectionFlags::setEntitySize(SectionFlags::Mergeable |
SectionFlags::Strings,
Size);
return getNamedSection(Name.c_str(), Flags);
}
return getReadOnlySection_();
}
std::string ELFTargetAsmInfo::PrintSectionFlags(unsigned flags) const {
std::string Flags = ",\"";
if (!(flags & SectionFlags::Debug))
Flags += 'a';
if (flags & SectionFlags::Code)
Flags += 'x';
if (flags & SectionFlags::Writeable)
Flags += 'w';
if (flags & SectionFlags::Mergeable)
Flags += 'M';
if (flags & SectionFlags::Strings)
Flags += 'S';
if (flags & SectionFlags::TLS)
Flags += 'T';
Flags += "\"";
// FIXME: There can be exceptions here
if (flags & SectionFlags::BSS)
Flags += ",@nobits";
else
Flags += ",@progbits";
if (unsigned entitySize = SectionFlags::getEntitySize(flags))
Flags += "," + utostr(entitySize);
return Flags;
}
<commit_msg>Don't use larger alignment.<commit_after>//===-- ELFTargetAsmInfo.cpp - ELF asm properties ---------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines target asm properties related what form asm statements
// should take in general on ELF-based targets
//
//===----------------------------------------------------------------------===//
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/GlobalVariable.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Target/ELFTargetAsmInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetData.h"
using namespace llvm;
ELFTargetAsmInfo::ELFTargetAsmInfo(const TargetMachine &TM) {
ETM = &TM;
TextSection_ = getUnnamedSection("\t.text", SectionFlags::Code);
DataSection_ = getUnnamedSection("\t.data", SectionFlags::Writeable);
BSSSection_ = getUnnamedSection("\t.bss",
SectionFlags::Writeable | SectionFlags::BSS);
ReadOnlySection_ = getNamedSection("\t.rodata", SectionFlags::None);
TLSDataSection_ = getNamedSection("\t.tdata",
SectionFlags::Writeable | SectionFlags::TLS);
TLSBSSSection_ = getNamedSection("\t.tbss",
SectionFlags::Writeable | SectionFlags::TLS | SectionFlags::BSS);
}
const Section*
ELFTargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const {
SectionKind::Kind Kind = SectionKindForGlobal(GV);
if (const Function *F = dyn_cast<Function>(GV)) {
switch (F->getLinkage()) {
default: assert(0 && "Unknown linkage type!");
case Function::InternalLinkage:
case Function::DLLExportLinkage:
case Function::ExternalLinkage:
return getTextSection_();
case Function::WeakLinkage:
case Function::LinkOnceLinkage:
std::string Name = UniqueSectionForGlobal(GV, Kind);
unsigned Flags = SectionFlagsForGlobal(GV, Name.c_str());
return getNamedSection(Name.c_str(), Flags);
}
} else if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
if (GVar->isWeakForLinker()) {
std::string Name = UniqueSectionForGlobal(GVar, Kind);
unsigned Flags = SectionFlagsForGlobal(GVar, Name.c_str());
return getNamedSection(Name.c_str(), Flags);
} else {
switch (Kind) {
case SectionKind::Data:
return getDataSection_();
case SectionKind::BSS:
// ELF targets usually have BSS sections
return getBSSSection_();
case SectionKind::ROData:
return getReadOnlySection_();
case SectionKind::RODataMergeStr:
return MergeableStringSection(GVar);
case SectionKind::RODataMergeConst:
return MergeableConstSection(GVar);
case SectionKind::ThreadData:
// ELF targets usually support TLS stuff
return getTLSDataSection_();
case SectionKind::ThreadBSS:
return getTLSBSSSection_();
default:
assert(0 && "Unsuported section kind for global");
}
}
} else
assert(0 && "Unsupported global");
}
const Section*
ELFTargetAsmInfo::MergeableConstSection(const GlobalVariable *GV) const {
const TargetData *TD = ETM->getTargetData();
Constant *C = cast<GlobalVariable>(GV)->getInitializer();
const Type *Type = C->getType();
// FIXME: string here is temporary, until stuff will fully land in.
// We cannot use {Four,Eight,Sixteen}ByteConstantSection here, since it's
// currently directly used by asmprinter.
unsigned Size = TD->getABITypeSize(Type);
if (Size == 4 || Size == 8 || Size == 16) {
std::string Name = ".rodata.cst" + utostr(Size);
return getNamedSection(Name.c_str(),
SectionFlags::setEntitySize(SectionFlags::Mergeable,
Size));
}
return getReadOnlySection_();
}
const Section*
ELFTargetAsmInfo::MergeableStringSection(const GlobalVariable *GV) const {
const TargetData *TD = ETM->getTargetData();
Constant *C = cast<GlobalVariable>(GV)->getInitializer();
const ConstantArray *CVA = cast<ConstantArray>(C);
const Type *Type = CVA->getType()->getElementType();
unsigned Size = TD->getABITypeSize(Type);
if (Size <= 16) {
// We also need alignment here
const TargetData *TD = ETM->getTargetData();
unsigned Align = TD->getPrefTypeAlignment(Type);
if (Align < Size)
Align = Size;
std::string Name = getCStringSection() + utostr(Size) + '.' + utostr(Align);
unsigned Flags = SectionFlags::setEntitySize(SectionFlags::Mergeable |
SectionFlags::Strings,
Size);
return getNamedSection(Name.c_str(), Flags);
}
return getReadOnlySection_();
}
std::string ELFTargetAsmInfo::PrintSectionFlags(unsigned flags) const {
std::string Flags = ",\"";
if (!(flags & SectionFlags::Debug))
Flags += 'a';
if (flags & SectionFlags::Code)
Flags += 'x';
if (flags & SectionFlags::Writeable)
Flags += 'w';
if (flags & SectionFlags::Mergeable)
Flags += 'M';
if (flags & SectionFlags::Strings)
Flags += 'S';
if (flags & SectionFlags::TLS)
Flags += 'T';
Flags += "\"";
// FIXME: There can be exceptions here
if (flags & SectionFlags::BSS)
Flags += ",@nobits";
else
Flags += ",@progbits";
if (unsigned entitySize = SectionFlags::getEntitySize(flags))
Flags += "," + utostr(entitySize);
return Flags;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "YouTuber.h"
//#define YOUTUBE_EXPERIMENT
#ifdef YOUTUBE_EXPERIMENT
#include <Shlobj.h>
#include <boost/python/exec.hpp>
#include <boost/python/import.hpp>
#include <boost/python/extract.hpp>
#include <boost/log/trivial.hpp>
#include <regex>
#include <fstream>
#include <iterator>
#include <streambuf>
#include "unzip.h"
namespace {
const char PYTUBE_URL[] = "https://github.com/nficano/pytube/archive/master.zip";
const char SCRIPT_TEMPLATE[] = R"(import sys
sys.path.append("%s")
from pytube import YouTube
def getYoutubeUrl(url):
return YouTube(url).streams.filter(progressive=True).order_by('resolution').desc().first().url)";
char* replace_char(char* str, char find, char replace)
{
char *current_pos = strchr(str,find);
while (current_pos) {
*current_pos = replace;
current_pos = strchr(++current_pos, find);
}
return str;
}
int from_hex(char ch)
{
return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;
}
std::string UrlUnescapeString(const std::string& s)
{
std::istringstream ss(s);
std::string result;
std::getline(ss, result, '%');
std::string buffer;
while (std::getline(ss, buffer, '%'))
{
if (buffer.size() >= 2)
{
result += char((from_hex(buffer[0]) << 4) | from_hex(buffer[1])) + buffer.substr(2);
}
}
return result;
}
bool extractYoutubeUrl(std::string& s)
{
std::regex txt_regex(R"((http(s)?:\/\/)?((w){3}.)?youtu(be|.be)?(\.com)?\/.+)");
std::string copy = s;
for (int unescaped = 0; unescaped < 2; ++unescaped)
{
std::smatch m;
if (std::regex_search(copy, m, txt_regex))
{
s = copy.substr(m.position());
return true;
}
if (!unescaped)
copy = UrlUnescapeString(copy);
}
return false;
}
bool DownloadAndExtractZip(const char* zipfile, const TCHAR* root)
{
unzFile uf = unzOpen((voidpf)zipfile);
if (!uf)
{
return false;
}
unzGoToFirstFile(uf);
do {
char filename[MAX_PATH];
unzGetCurrentFileInfo(uf, 0, filename, sizeof(filename), 0, 0, 0, 0);
TCHAR path[MAX_PATH];
_tcscpy_s(path, root);
PathAppend(path, CA2T(filename, CP_UTF8));
auto pathlen = _tcslen(path);
if (pathlen > 0 && (path[pathlen - 1] == _T('/') || path[pathlen - 1] == _T('\\')))
{
if (_tmkdir(path) != 0)
return false;
}
else
{
unzOpenCurrentFile(uf);
std::ofstream f(path, std::ofstream::binary);
char buf[1024 * 64];
int r;
do
{
r = unzReadCurrentFile(uf, buf, sizeof(buf));
if (r > 0)
{
f.write(buf, r);
}
} while (r > 0);
unzCloseCurrentFile(uf);
}
} while (unzGoToNextFile(uf) == UNZ_OK);
unzClose(uf);
return true;
}
class YouTubeDealer
{
public:
YouTubeDealer();
~YouTubeDealer();
bool isValid() const { return !!m_obj; }
std::string getYoutubeUrl(const std::string& url);
private:
boost::python::object m_obj;
};
YouTubeDealer::YouTubeDealer()
{
// String buffer for holding the path.
TCHAR strPath[MAX_PATH]{};
// Get the special folder path.
SHGetSpecialFolderPath(
0, // Hwnd
strPath, // String buffer
CSIDL_LOCAL_APPDATA, // CSLID of folder
TRUE); // Create if doesn't exist?
CString localAppdataPath = strPath;
PathAppend(strPath, _T("pytube-master"));
if (-1 == _taccess(strPath, 0)
&& (!DownloadAndExtractZip(PYTUBE_URL, localAppdataPath)
|| -1 == _taccess(strPath, 0)))
{
return;
}
using namespace boost::python;
Py_Initialize();
try {
// Retrieve the main module.
object main = import("__main__");
// Retrieve the main module's namespace
object global(main.attr("__dict__"));
CT2A convert(strPath, CP_UTF8);
replace_char(convert, '\\', '/');
char script[4096];
sprintf_s(script, SCRIPT_TEMPLATE, static_cast<LPSTR>(convert));
// Define greet function in Python.
object exec_result = exec(script, global, global);
// Create a reference to it.
m_obj = global["getYoutubeUrl"];
if (!m_obj)
Py_Finalize();
}
catch (const std::exception&)
{
Py_Finalize();
return;
}
catch (const error_already_set&)
{
Py_Finalize();
return;
}
}
YouTubeDealer::~YouTubeDealer()
{
if (isValid())
Py_Finalize();
}
std::string YouTubeDealer::getYoutubeUrl(const std::string& url)
{
using namespace boost::python;
std::string result;
try
{
result = extract<std::string>(m_obj(url));
}
catch (const std::exception&)
{
}
catch (const error_already_set&)
{
}
BOOST_LOG_TRIVIAL(trace) << "getYoutubeUrl() returning \"" << result << "\"";
return result;
}
} // namespace
std::string getYoutubeUrl(std::string url)
{
if (extractYoutubeUrl(url))
{
CWaitCursor wait;
static YouTubeDealer buddy;
if (buddy.isValid())
return buddy.getYoutubeUrl(url);
}
return url;
}
#else // YOUTUBE_EXPERIMENT
std::string getYoutubeUrl(std::string url)
{
return url;
}
#endif // YOUTUBE_EXPERIMENT
<commit_msg>tiny refactoring<commit_after>#include "stdafx.h"
#include "YouTuber.h"
//#define YOUTUBE_EXPERIMENT
#ifdef YOUTUBE_EXPERIMENT
#include <Shlobj.h>
#include <boost/python/exec.hpp>
#include <boost/python/import.hpp>
#include <boost/python/extract.hpp>
#include <boost/log/trivial.hpp>
#include <regex>
#include <fstream>
#include <iterator>
#include <streambuf>
#include <algorithm>
#include "unzip.h"
namespace {
const char PYTUBE_URL[] = "https://github.com/nficano/pytube/archive/master.zip";
const char SCRIPT_TEMPLATE[] = R"(import sys
sys.path.append("%s")
from pytube import YouTube
def getYoutubeUrl(url):
return YouTube(url).streams.filter(progressive=True).order_by('resolution').desc().first().url)";
int from_hex(char ch)
{
return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;
}
std::string UrlUnescapeString(const std::string& s)
{
std::istringstream ss(s);
std::string result;
std::getline(ss, result, '%');
std::string buffer;
while (std::getline(ss, buffer, '%'))
{
if (buffer.size() >= 2)
{
result += char((from_hex(buffer[0]) << 4) | from_hex(buffer[1])) + buffer.substr(2);
}
}
return result;
}
bool extractYoutubeUrl(std::string& s)
{
std::regex txt_regex(R"((http(s)?:\/\/)?((w){3}.)?youtu(be|.be)?(\.com)?\/.+)");
std::string copy = s;
for (int unescaped = 0; unescaped < 2; ++unescaped)
{
std::smatch m;
if (std::regex_search(copy, m, txt_regex))
{
s = copy.substr(m.position());
return true;
}
if (!unescaped)
copy = UrlUnescapeString(copy);
}
return false;
}
bool DownloadAndExtractZip(const char* zipfile, const TCHAR* root)
{
unzFile uf = unzOpen((voidpf)zipfile);
if (!uf)
{
return false;
}
unzGoToFirstFile(uf);
do {
char filename[MAX_PATH];
unzGetCurrentFileInfo(uf, 0, filename, sizeof(filename), 0, 0, 0, 0);
TCHAR path[MAX_PATH];
_tcscpy_s(path, root);
PathAppend(path, CA2T(filename, CP_UTF8));
auto pathlen = _tcslen(path);
if (pathlen > 0 && (path[pathlen - 1] == _T('/') || path[pathlen - 1] == _T('\\')))
{
if (_tmkdir(path) != 0)
return false;
}
else
{
unzOpenCurrentFile(uf);
std::ofstream f(path, std::ofstream::binary);
char buf[1024 * 64];
int r;
do
{
r = unzReadCurrentFile(uf, buf, sizeof(buf));
if (r > 0)
{
f.write(buf, r);
}
} while (r > 0);
unzCloseCurrentFile(uf);
}
} while (unzGoToNextFile(uf) == UNZ_OK);
unzClose(uf);
return true;
}
class YouTubeDealer
{
public:
YouTubeDealer();
~YouTubeDealer();
bool isValid() const { return !!m_obj; }
std::string getYoutubeUrl(const std::string& url);
private:
boost::python::object m_obj;
};
YouTubeDealer::YouTubeDealer()
{
// String buffer for holding the path.
TCHAR strPath[MAX_PATH]{};
// Get the special folder path.
SHGetSpecialFolderPath(
0, // Hwnd
strPath, // String buffer
CSIDL_LOCAL_APPDATA, // CSLID of folder
TRUE); // Create if doesn't exist?
CString localAppdataPath = strPath;
PathAppend(strPath, _T("pytube-master"));
if (-1 == _taccess(strPath, 0)
&& (!DownloadAndExtractZip(PYTUBE_URL, localAppdataPath)
|| -1 == _taccess(strPath, 0)))
{
return;
}
using namespace boost::python;
Py_Initialize();
try {
// Retrieve the main module.
object main = import("__main__");
// Retrieve the main module's namespace
object global(main.attr("__dict__"));
CT2A const convert(strPath, CP_UTF8);
LPSTR const pszConvert = convert;
std::replace(pszConvert, pszConvert + strlen(pszConvert), '\\', '/');
char script[4096];
sprintf_s(script, SCRIPT_TEMPLATE, pszConvert);
// Define function in Python.
object exec_result = exec(script, global, global);
// Create a reference to it.
m_obj = global["getYoutubeUrl"];
if (!m_obj)
Py_Finalize();
}
catch (const std::exception&)
{
Py_Finalize();
return;
}
catch (const error_already_set&)
{
Py_Finalize();
return;
}
}
YouTubeDealer::~YouTubeDealer()
{
if (isValid())
Py_Finalize();
}
std::string YouTubeDealer::getYoutubeUrl(const std::string& url)
{
using namespace boost::python;
std::string result;
try
{
result = extract<std::string>(m_obj(url));
}
catch (const std::exception&)
{
}
catch (const error_already_set&)
{
}
BOOST_LOG_TRIVIAL(trace) << "getYoutubeUrl() returning \"" << result << "\"";
return result;
}
} // namespace
std::string getYoutubeUrl(std::string url)
{
if (extractYoutubeUrl(url))
{
CWaitCursor wait;
static YouTubeDealer buddy;
if (buddy.isValid())
return buddy.getYoutubeUrl(url);
}
return url;
}
#else // YOUTUBE_EXPERIMENT
std::string getYoutubeUrl(std::string url)
{
return url;
}
#endif // YOUTUBE_EXPERIMENT
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageSpatialFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to C. Charles Law who developed this class.
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <math.h>
#include "vtkImageSpatialFilter.h"
//----------------------------------------------------------------------------
// Description:
// Construct an instance of vtkImageSpatialFilter fitler.
vtkImageSpatialFilter::vtkImageSpatialFilter()
{
int idx;
for (idx = 0; idx < VTK_IMAGE_DIMENSIONS; ++idx)
{
this->KernelSize[idx] = 1;
this->KernelMiddle[idx] = 0;
}
this->HandleBoundariesOn();
this->UseExecuteCenterOn();
}
//----------------------------------------------------------------------------
void vtkImageSpatialFilter::PrintSelf(ostream& os, vtkIndent indent)
{
int idx;
vtkImageFilter::PrintSelf(os, indent);
os << indent << "KernelSize: (" << this->KernelSize[0];
for (idx = 1; idx < VTK_IMAGE_DIMENSIONS; ++idx)
{
os << ", " << this->KernelSize[idx];
}
os << ").\n";
os << indent << "KernelMiddle: (" << this->KernelMiddle[0];
for (idx = 1; idx < VTK_IMAGE_DIMENSIONS; ++idx)
{
os << ", " << this->KernelMiddle[idx];
}
os << ").\n";
os << indent << "UseExecuteCenter: " << this->UseExecuteCenter << "\n";
}
//----------------------------------------------------------------------------
// Description:
// This method is passed a region that holds the image extent of this filters
// input, and changes the region to hold the image extent of this filters
// output.
void vtkImageSpatialFilter::ComputeOutputImageInformation(
vtkImageRegion *inRegion, vtkImageRegion *outRegion)
{
int extent[8];
int idx;
if (this->HandleBoundaries)
{
// Output image extent same as input region extent
return;
}
// shrink output image extent.
inRegion->GetImageExtent(extent, 4);
for (idx = 0; idx < 4; ++idx)
{
extent[idx*2] += this->KernelMiddle[idx];
extent[idx*2 + 1] -= (this->KernelSize[idx] - 1) - this->KernelMiddle[idx];
}
outRegion->SetImageExtent(extent, 4);
}
//----------------------------------------------------------------------------
// Description:
// This method computes the extent of the input region necessary to generate
// an output region. Before this method is called "region" should have the
// extent of the output region. After this method finishes, "region" should
// have the extent of the required input region.
void vtkImageSpatialFilter::ComputeRequiredInputRegionExtent(
vtkImageRegion *outRegion,
vtkImageRegion *inRegion)
{
int extent[8];
int imageExtent[8];
int idx;
outRegion->GetExtent(extent, 4);
inRegion->GetImageExtent(imageExtent, 4);
for (idx = 0; idx < 4; ++idx)
{
// Expand to get inRegion Extent
extent[idx*2] -= this->KernelMiddle[idx];
extent[idx*2 + 1] += (this->KernelSize[idx] - 1) - this->KernelMiddle[idx];
// If the expanded region is out of the IMAGE Extent (grow min)
if (extent[idx*2] < imageExtent[idx*2])
{
if (this->HandleBoundaries)
{
// shrink the required region extent
extent[idx*2] = imageExtent[idx*2];
}
else
{
vtkWarningMacro(<< "Required region is out of the image extent.");
}
}
// If the expanded region is out of the IMAGE Extent (shrink max)
if (extent[idx*2+1] > imageExtent[idx*2+1])
{
if (this->HandleBoundaries)
{
// shrink the required region extent
extent[idx*2+1] = imageExtent[idx*2+1];
}
else
{
vtkWarningMacro(<< "Required region is out of the image extent.");
}
}
}
inRegion->SetExtent(extent, 4);
}
//----------------------------------------------------------------------------
// Description:
// This Execute method breaks the regions into pieces that have boundaries
// and a piece that does not need boundary handling. It calls subclass
// defined execute methods for these pieces.
void vtkImageSpatialFilter::Execute(int axisIdx, vtkImageRegion *inRegion,
vtkImageRegion *outRegion)
{
int idx, idx2;
int *extent = new int[axisIdx*2];
int *outImageExtent = new int[axisIdx*2];
int *outCenterExtent = new int[axisIdx*2];
int *inExtentSave = new int[axisIdx*2];
int *outExtentSave = new int[axisIdx*2];
// If a separate center method does not exist, don't bother splitting
if ( ! this->UseExecuteCenter)
{
this->vtkImageFilter::Execute(axisIdx, inRegion, outRegion);
delete [] extent;
delete [] outImageExtent;
delete [] outCenterExtent;
delete [] inExtentSave;
delete [] outExtentSave;
return;
}
// Save the extent of the two regions
inRegion->GetExtent(inExtentSave, axisIdx);
outRegion->GetExtent(outExtentSave, axisIdx);
// Compute the image extent of the output region (no boundary handling)
inRegion->GetImageExtent(outImageExtent, axisIdx);
for (idx = 0; idx < axisIdx; ++idx)
{
outImageExtent[idx*2] += this->KernelMiddle[idx];
outImageExtent[idx*2+1] -= (this->KernelSize[idx]-1)
- this->KernelMiddle[idx];
// In case the image is so small, it is all boundary conditions.
if (outImageExtent[idx*2] > outImageExtent[idx*2+1])
{
outImageExtent[idx*2] =(outImageExtent[idx*2]+outImageExtent[idx*2+1])/2;
outImageExtent[idx*2+1] = outImageExtent[idx*2]-1;
}
}
// Compute the out region that does not need boundary handling.
outRegion->GetExtent(outCenterExtent, axisIdx);
for (idx = 0; idx < axisIdx; ++idx)
{
// Intersection
if (outCenterExtent[idx*2] < outImageExtent[idx*2])
{
outCenterExtent[idx*2] = outImageExtent[idx*2];
}
if (outCenterExtent[idx*2+1] > outImageExtent[idx*2+1])
{
outCenterExtent[idx*2+1] = outImageExtent[idx*2+1];
}
}
// Call center execute
outRegion->SetExtent(outCenterExtent, axisIdx);
this->ComputeRequiredInputRegionExtent(outRegion, inRegion);
// Just in cass the image is so small there is no center.
if (outRegion->GetVolume() > 0)
{
this->ExecuteCenter(axisIdx, inRegion, outRegion);
}
// Do stuff for all boundary pieces
if (this->HandleBoundaries)
{
// start getting and executing boundary pieces.
for (idx = 0; idx < axisIdx; ++idx)
{
// for piece left of min
if (outExtentSave[idx*2] < outCenterExtent[idx*2])
{
for (idx2 = 0; idx2 < axisIdx*2; ++idx2)
{
extent[idx2] = outCenterExtent[idx2];
}
extent[idx*2] = outExtentSave[idx*2];
extent[idx*2+1] = outCenterExtent[idx*2];
outRegion->SetExtent(extent, axisIdx);
this->ComputeRequiredInputRegionExtent(outRegion, inRegion);
this->vtkImageFilter::Execute(axisIdx, inRegion, outRegion);
outCenterExtent[idx*2] = outExtentSave[idx*2];
}
// for piece right of max
if (outExtentSave[idx*2+1] > outCenterExtent[idx*2+1])
{
for (idx2 = 0; idx2 < axisIdx*2; ++idx2)
{
extent[idx2] = outCenterExtent[idx2];
}
extent[idx*2] = outCenterExtent[idx*2+1];
extent[idx*2+1] = outExtentSave[idx*2+1];
outRegion->SetExtent(extent, axisIdx);
this->ComputeRequiredInputRegionExtent(outRegion, inRegion);
this->vtkImageFilter::Execute(inRegion, outRegion);
outCenterExtent[idx*2+1] = outExtentSave[idx*2+1];
}
}
}
// Restore original extent just in case
outRegion->SetExtent(outExtentSave, axisIdx);
inRegion->SetExtent(inExtentSave, axisIdx);
delete [] extent;
delete [] outImageExtent;
delete [] outCenterExtent;
delete [] inExtentSave;
delete [] outExtentSave;
}
//----------------------------------------------------------------------------
// Description:
// The default execute4d breaks the image in 3d volumes.
void vtkImageSpatialFilter::ExecuteCenter(int axisIdx,
vtkImageRegion *inRegion,
vtkImageRegion *outRegion)
{
int coordinate, min, max;
int inExtent[axisIdx*2], outExtent[axisIdx*2];
// Terminate recursion?
if (axisIdx <= this->NumberOfAxes)
{
this->ExecuteCenter(inRegion, outRegion);
return;
}
// Get the extent of the third dimension to be eliminated.
inRegion->GetExtent(inExtent, axisIdx);
outRegion->GetExtent(outExtent, axisIdx);
// This method assumes that the third axis of in and out have same extent.
min = inExtent[axisIdx*2 - 2];
max = inExtent[axisIdx*2 - 1];
if (min != outExtent[axisIdx*2 - 2] || max != outExtent[axisIdx*2 - 1])
{
vtkErrorMacro(<< "ExecuteCenter: Extent mismatch.");
return;
}
// loop over extra axis
for (coordinate = min; coordinate <= max; ++coordinate)
{
// set up the lower dimensional regions.
inExtent[axisIdx*2 - 2] = inExtent[axisIdx*2 - 1] = coordinate;
inRegion->SetExtent(inExtent, axisIdx);
outExtent[axisIdx*2 - 2] = outExtent[axisIdx*2 - 1] = coordinate;
outRegion->SetExtent(outExtent, axisIdx);
this->ExecuteCenter(axisIdx, inRegion, outRegion);
}
// restore the original extent
inExtent[axisIdx*2 - 2] = min;
inExtent[axisIdx*2 - 1] = max;
outExtent[axisIdx*2 - 2] = min;
outExtent[axisIdx*2 - 1] = max;
inRegion->SetExtent(inExtent, axisIdx);
outRegion->SetExtent(outExtent, axisIdx);
}
//----------------------------------------------------------------------------
// Description:
// Subclass must provide this function if UseExecuteCenter is on.
void vtkImageSpatialFilter::ExecuteCenter(vtkImageRegion *inRegion,
vtkImageRegion *outRegion)
{
inRegion = outRegion;
vtkErrorMacro(<< "Subclass does not have an ExecuteCenter method.");
}
<commit_msg>thanks Rick<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageSpatialFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to C. Charles Law who developed this class.
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <math.h>
#include "vtkImageSpatialFilter.h"
//----------------------------------------------------------------------------
// Description:
// Construct an instance of vtkImageSpatialFilter fitler.
vtkImageSpatialFilter::vtkImageSpatialFilter()
{
int idx;
for (idx = 0; idx < VTK_IMAGE_DIMENSIONS; ++idx)
{
this->KernelSize[idx] = 1;
this->KernelMiddle[idx] = 0;
}
this->HandleBoundariesOn();
this->UseExecuteCenterOn();
}
//----------------------------------------------------------------------------
void vtkImageSpatialFilter::PrintSelf(ostream& os, vtkIndent indent)
{
int idx;
vtkImageFilter::PrintSelf(os, indent);
os << indent << "KernelSize: (" << this->KernelSize[0];
for (idx = 1; idx < VTK_IMAGE_DIMENSIONS; ++idx)
{
os << ", " << this->KernelSize[idx];
}
os << ").\n";
os << indent << "KernelMiddle: (" << this->KernelMiddle[0];
for (idx = 1; idx < VTK_IMAGE_DIMENSIONS; ++idx)
{
os << ", " << this->KernelMiddle[idx];
}
os << ").\n";
os << indent << "UseExecuteCenter: " << this->UseExecuteCenter << "\n";
}
//----------------------------------------------------------------------------
// Description:
// This method is passed a region that holds the image extent of this filters
// input, and changes the region to hold the image extent of this filters
// output.
void vtkImageSpatialFilter::ComputeOutputImageInformation(
vtkImageRegion *inRegion, vtkImageRegion *outRegion)
{
int extent[8];
int idx;
if (this->HandleBoundaries)
{
// Output image extent same as input region extent
return;
}
// shrink output image extent.
inRegion->GetImageExtent(extent, 4);
for (idx = 0; idx < 4; ++idx)
{
extent[idx*2] += this->KernelMiddle[idx];
extent[idx*2 + 1] -= (this->KernelSize[idx] - 1) - this->KernelMiddle[idx];
}
outRegion->SetImageExtent(extent, 4);
}
//----------------------------------------------------------------------------
// Description:
// This method computes the extent of the input region necessary to generate
// an output region. Before this method is called "region" should have the
// extent of the output region. After this method finishes, "region" should
// have the extent of the required input region.
void vtkImageSpatialFilter::ComputeRequiredInputRegionExtent(
vtkImageRegion *outRegion,
vtkImageRegion *inRegion)
{
int extent[8];
int imageExtent[8];
int idx;
outRegion->GetExtent(extent, 4);
inRegion->GetImageExtent(imageExtent, 4);
for (idx = 0; idx < 4; ++idx)
{
// Expand to get inRegion Extent
extent[idx*2] -= this->KernelMiddle[idx];
extent[idx*2 + 1] += (this->KernelSize[idx] - 1) - this->KernelMiddle[idx];
// If the expanded region is out of the IMAGE Extent (grow min)
if (extent[idx*2] < imageExtent[idx*2])
{
if (this->HandleBoundaries)
{
// shrink the required region extent
extent[idx*2] = imageExtent[idx*2];
}
else
{
vtkWarningMacro(<< "Required region is out of the image extent.");
}
}
// If the expanded region is out of the IMAGE Extent (shrink max)
if (extent[idx*2+1] > imageExtent[idx*2+1])
{
if (this->HandleBoundaries)
{
// shrink the required region extent
extent[idx*2+1] = imageExtent[idx*2+1];
}
else
{
vtkWarningMacro(<< "Required region is out of the image extent.");
}
}
}
inRegion->SetExtent(extent, 4);
}
//----------------------------------------------------------------------------
// Description:
// This Execute method breaks the regions into pieces that have boundaries
// and a piece that does not need boundary handling. It calls subclass
// defined execute methods for these pieces.
void vtkImageSpatialFilter::Execute(int axisIdx, vtkImageRegion *inRegion,
vtkImageRegion *outRegion)
{
int idx, idx2;
int *extent = new int[axisIdx*2];
int *outImageExtent = new int[axisIdx*2];
int *outCenterExtent = new int[axisIdx*2];
int *inExtentSave = new int[axisIdx*2];
int *outExtentSave = new int[axisIdx*2];
// If a separate center method does not exist, don't bother splitting
if ( ! this->UseExecuteCenter)
{
this->vtkImageFilter::Execute(axisIdx, inRegion, outRegion);
delete [] extent;
delete [] outImageExtent;
delete [] outCenterExtent;
delete [] inExtentSave;
delete [] outExtentSave;
return;
}
// Save the extent of the two regions
inRegion->GetExtent(inExtentSave, axisIdx);
outRegion->GetExtent(outExtentSave, axisIdx);
// Compute the image extent of the output region (no boundary handling)
inRegion->GetImageExtent(outImageExtent, axisIdx);
for (idx = 0; idx < axisIdx; ++idx)
{
outImageExtent[idx*2] += this->KernelMiddle[idx];
outImageExtent[idx*2+1] -= (this->KernelSize[idx]-1)
- this->KernelMiddle[idx];
// In case the image is so small, it is all boundary conditions.
if (outImageExtent[idx*2] > outImageExtent[idx*2+1])
{
outImageExtent[idx*2] =(outImageExtent[idx*2]+outImageExtent[idx*2+1])/2;
outImageExtent[idx*2+1] = outImageExtent[idx*2]-1;
}
}
// Compute the out region that does not need boundary handling.
outRegion->GetExtent(outCenterExtent, axisIdx);
for (idx = 0; idx < axisIdx; ++idx)
{
// Intersection
if (outCenterExtent[idx*2] < outImageExtent[idx*2])
{
outCenterExtent[idx*2] = outImageExtent[idx*2];
}
if (outCenterExtent[idx*2+1] > outImageExtent[idx*2+1])
{
outCenterExtent[idx*2+1] = outImageExtent[idx*2+1];
}
}
// Call center execute
outRegion->SetExtent(outCenterExtent, axisIdx);
this->ComputeRequiredInputRegionExtent(outRegion, inRegion);
// Just in cass the image is so small there is no center.
if (outRegion->GetVolume() > 0)
{
this->ExecuteCenter(axisIdx, inRegion, outRegion);
}
// Do stuff for all boundary pieces
if (this->HandleBoundaries)
{
// start getting and executing boundary pieces.
for (idx = 0; idx < axisIdx; ++idx)
{
// for piece left of min
if (outExtentSave[idx*2] < outCenterExtent[idx*2])
{
for (idx2 = 0; idx2 < axisIdx*2; ++idx2)
{
extent[idx2] = outCenterExtent[idx2];
}
extent[idx*2] = outExtentSave[idx*2];
extent[idx*2+1] = outCenterExtent[idx*2];
outRegion->SetExtent(extent, axisIdx);
this->ComputeRequiredInputRegionExtent(outRegion, inRegion);
this->vtkImageFilter::Execute(axisIdx, inRegion, outRegion);
outCenterExtent[idx*2] = outExtentSave[idx*2];
}
// for piece right of max
if (outExtentSave[idx*2+1] > outCenterExtent[idx*2+1])
{
for (idx2 = 0; idx2 < axisIdx*2; ++idx2)
{
extent[idx2] = outCenterExtent[idx2];
}
extent[idx*2] = outCenterExtent[idx*2+1];
extent[idx*2+1] = outExtentSave[idx*2+1];
outRegion->SetExtent(extent, axisIdx);
this->ComputeRequiredInputRegionExtent(outRegion, inRegion);
this->vtkImageFilter::Execute(inRegion, outRegion);
outCenterExtent[idx*2+1] = outExtentSave[idx*2+1];
}
}
}
// Restore original extent just in case
outRegion->SetExtent(outExtentSave, axisIdx);
inRegion->SetExtent(inExtentSave, axisIdx);
delete [] extent;
delete [] outImageExtent;
delete [] outCenterExtent;
delete [] inExtentSave;
delete [] outExtentSave;
}
//----------------------------------------------------------------------------
// Description:
// The default execute4d breaks the image in 3d volumes.
void vtkImageSpatialFilter::ExecuteCenter(int axisIdx,
vtkImageRegion *inRegion,
vtkImageRegion *outRegion)
{
int coordinate, min, max;
int *inExtent = new int[axisIdx*2];
int *outExtent = new int[axisIdx*2];
// Terminate recursion?
if (axisIdx <= this->NumberOfAxes)
{
this->ExecuteCenter(inRegion, outRegion);
delete [] inExtent;
delete [] outExtent;
return;
}
// Get the extent of the third dimension to be eliminated.
inRegion->GetExtent(inExtent, axisIdx);
outRegion->GetExtent(outExtent, axisIdx);
// This method assumes that the third axis of in and out have same extent.
min = inExtent[axisIdx*2 - 2];
max = inExtent[axisIdx*2 - 1];
if (min != outExtent[axisIdx*2 - 2] || max != outExtent[axisIdx*2 - 1])
{
vtkErrorMacro(<< "ExecuteCenter: Extent mismatch.");
delete [] inExtent;
delete [] outExtent;
return;
}
// loop over extra axis
for (coordinate = min; coordinate <= max; ++coordinate)
{
// set up the lower dimensional regions.
inExtent[axisIdx*2 - 2] = inExtent[axisIdx*2 - 1] = coordinate;
inRegion->SetExtent(inExtent, axisIdx);
outExtent[axisIdx*2 - 2] = outExtent[axisIdx*2 - 1] = coordinate;
outRegion->SetExtent(outExtent, axisIdx);
this->ExecuteCenter(axisIdx, inRegion, outRegion);
}
// restore the original extent
inExtent[axisIdx*2 - 2] = min;
inExtent[axisIdx*2 - 1] = max;
outExtent[axisIdx*2 - 2] = min;
outExtent[axisIdx*2 - 1] = max;
inRegion->SetExtent(inExtent, axisIdx);
outRegion->SetExtent(outExtent, axisIdx);
delete [] inExtent;
delete [] outExtent;
}
//----------------------------------------------------------------------------
// Description:
// Subclass must provide this function if UseExecuteCenter is on.
void vtkImageSpatialFilter::ExecuteCenter(vtkImageRegion *inRegion,
vtkImageRegion *outRegion)
{
inRegion = outRegion;
vtkErrorMacro(<< "Subclass does not have an ExecuteCenter method.");
}
<|endoftext|> |
<commit_before>#include <memory>
#include <set>
#include <Bull/Core/System/Config.hpp>
#include <Bull/Core/Thread/LocalPtr.hpp>
#include <Bull/Core/Thread/Lock.hpp>
#include <Bull/Render/Context/Context.hpp>
#include <Bull/Render/Context/GlContext.hpp>
#include <Bull/Render/OpenGL.hpp>
#include <Bull/Render/GlLoader.hpp>
#include <Bull/Utility/Window/VideoMode.hpp>
#if defined BULL_OS_WINDOWS
#include <Bull/Render/Context/Wgl/WglContext.hpp>
typedef Bull::prv::WglContext ContextType;
#else
#include <Bull/Render/Context/Glx/GlxContext.hpp>
typedef Bull::prv::GlxContext ContextType;
#endif
namespace Bull
{
namespace prv
{
namespace
{
thread_local std::shared_ptr<Context> internal(nullptr);
std::set<std::shared_ptr<Context>> internals;
Mutex internalsMutex;
LocalPtr<GlContext> current(nullptr);
std::shared_ptr<ContextType> shared;
Mutex sharedContextMutex;
std::shared_ptr<Context> getInternalContext()
{
if(internal == nullptr)
{
internal = std::make_shared<Context>();
Lock lock(internalsMutex);
internals.insert(internal);
}
return internal;
}
}
/*! \brief Perform internal initialization
*
*/
void GlContext::globalInit()
{
Lock lock(sharedContextMutex);
shared = std::make_shared<ContextType>(nullptr);
shared->setActive(true);
/// We load OpenGL functions before initialize because this method uses OpenGL functions (glEnable, glGetIntegerv...)
ExtensionsLoader::Instance loader = ExtensionsLoader::get(shared->getSurfaceHandler());
ContextType::requireExtensions(loader);
GlLoader::load();
loader->load();
shared->initialize();
/// Ensure two things:
/// + The shared context is disabled
/// + The internal context is enable
shared->setActive(false);
}
/*! \brief Perform internal cleanup
*
*/
void GlContext::globalCleanup()
{
Lock lockInternals(internalsMutex);
internals.clear();
Lock lockShared(sharedContextMutex);
shared.reset();
}
/*! \brief Ensure there is an active OpenGL context in this thread
*
*/
void GlContext::ensureContext()
{
if(Context::getActive() == nullptr)
{
getInternalContext();
}
}
/*! \brief Create an OS specific instance of GlContext
*
* \return Return the created context
*
*/
GlContext* GlContext::createInstance()
{
ContextType* context = new ContextType(shared);
context->initialize();
return context;
}
/*! \brief Create an OS specific instance of GlContext
*
* \param mode The VideoMode to use to create the context
* \param settings Settings to use to create the context
*
* \return Return the created context
*
*/
GlContext* GlContext::createInstance(const VideoMode& mode, const ContextSettings& settings)
{
ContextType* context = new ContextType(shared, mode, settings);
context->initialize();
return context;
}
/*! \brief Create an OS specific instance of GlContext
*
* \param bitsPerPixel Number of bits per pixel to use
* \param settings Settings to use to create the context
*
* \return Return the created context
*
*/
GlContext* GlContext::createInstance(unsigned int bitsPerPixel, const ContextSettings& settings)
{
ContextType* context = new ContextType(shared, bitsPerPixel, settings);
context->initialize(settings);
return context;
}
/*! \brief Create an OS specific instance of GlContext
*
* \param window The window to bind the created context
* \param bitsPerPixel The number of bits to use per pixel
* \param settings Parameters to create the OpenGL context
*
* \return Return the created context
*
*/
GlContext* GlContext::createInstance(WindowHandler window, unsigned int bitsPerPixel, const ContextSettings& settings)
{
ContextType* context = new ContextType(shared, window, bitsPerPixel, settings);
context->initialize(settings);
return context;
}
/*! \brief Get an OpenGL function
*
* \param function The function name
*
* \param Return the function, nullptr if the function is not available
*
*/
void* GlContext::getFunction(const String& function)
{
return ContextType::getFunction(function);
}
/*! \brief Check whether an extensions is loaded
*
* \param extension The name of the extension
*
* \return Return true if the extension is loaded, false otherwise
*
*/
bool GlContext::isLoaded(const String& extension)
{
return ExtensionsLoader::isSet() ? ExtensionsLoader::get()->isLoaded(extension) : false;
}
/*! \brief Check whether an extensions is loaded
*
* \param extension The extension
*
* \return Return true if the extension is loaded, false otherwise
*
*/
bool GlContext::isLoaded(const ExtensionsLoader::Extension& extension)
{
return ExtensionsLoader::isSet() ? ExtensionsLoader::get()->isLoaded(extension) : false;
}
/*! \brief Check whether an extensions is loaded
*
* \param extension The name of the extension
*
* \return Return true if the extension is supported, false otherwise
*
*/
bool GlContext::isSupported(const String& extension)
{
return ExtensionsLoader::isSet() ? ExtensionsLoader::get()->isSupported(extension) : false;
}
/*! \brief Check whether an extensions is loaded
*
* \param extension The extension
*
* \return Return true if the extension is supported, false otherwise
*
*/
bool GlContext::isSupported(const ExtensionsLoader::Extension& extension)
{
return ExtensionsLoader::isSet() ? ExtensionsLoader::get()->isSupported(extension) : false;
}
/*! \brief Give a mark to a pixel format
*
* \param bitsPerPixel
* \param depths
* \param stencil
* \param antialiasing
* \param bitsPerPixelWanted
* \param settingsWanted
*
* \return Return the mark of the pixel format
*
*/
int GlContext::evaluatePixelFormat(unsigned int bitsPerPixel, int depths, int stencil, unsigned int antialiasing, unsigned int bitsPerPixelWanted, const ContextSettings& settingsWanted)
{
int colorDiff = static_cast<int>(bitsPerPixelWanted) - bitsPerPixel;
int depthDiff = static_cast<int>(settingsWanted.depths) - depths;
int stencilDiff = static_cast<int>(settingsWanted.stencil) - stencil;
int antialiasingDiff = static_cast<int>(settingsWanted.antialiasing) - antialiasing;
colorDiff *= ((colorDiff > 0) ? 100000 : 1);
depthDiff *= ((depthDiff > 0) ? 100000 : 1);
stencilDiff *= ((stencilDiff > 0) ? 100000 : 1);
antialiasingDiff *= ((antialiasingDiff > 0) ? 100000 : 1);
int score = std::abs(colorDiff) + std::abs(depthDiff) + std::abs(stencilDiff) + std::abs(antialiasingDiff);
return score;
}
/*! \brief Destructor
*
*/
GlContext::~GlContext()
{
/// Nothing
}
/*! \brief Activate or deactivate the context
*
* \param active True to activate, false to deactivate the context
*
* \return Return true if the context's status changed successfully, false otherwise
*
*/
bool GlContext::setActive(bool active)
{
if(active)
{
if(current != this)
{
if(makeCurrent())
{
current = this;
return true;
}
return false;
}
return true;
}
else
{
if(current == this)
{
return getInternalContext()->setActive(true);
}
return true;
}
}
/*! \brief Get the ContextSettings of the context
*
* \return Return the ContextSettings
*
*/
const ContextSettings& GlContext::getSettings() const
{
return m_settings;
}
/*! \brief Constructor
*
* \param settings Settings to use to create the context
*
*/
GlContext::GlContext(const ContextSettings& settings) :
m_settings(settings)
{
/// Nothing
}
/*! \brief Enable and perform initializations
*
* \param wanted Settings wanted to create the context
*
*/
void GlContext::initialize(const ContextSettings& wanted)
{
if(setActive(true))
{
int majorVersion = 0;
int minorVersion = 0;
gl::getIntegerv(GL_MAJOR_VERSION, &majorVersion);
gl::getIntegerv(GL_MINOR_VERSION, &minorVersion);
if(gl::getError() != GL_INVALID_ENUM)
{
m_settings.major = static_cast<unsigned int>(majorVersion);
m_settings.minor = static_cast<unsigned int>(minorVersion);
}
else
{
const GLubyte* version = gl::getString(GL_VERSION);
if (version)
{
m_settings.major = String::intToChar(version[0]);
m_settings.minor = String::intToChar(version[2]);
}
else
{
m_settings.major = 1;
m_settings.minor = 1;
}
}
m_settings.flags = ContextSettings::Default;
if(m_settings.major >= 3)
{
int flags;
gl::getIntegerv(GL_CONTEXT_FLAGS, &flags);
if(flags && GL_CONTEXT_FLAG_DEBUG_BIT)
{
m_settings.flags |= ContextSettings::Debug;
}
if(flags && GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT)
{
m_settings.flags |= ContextSettings::ForwardCompatible;
}
if(m_settings.major == 3 && m_settings.minor == 1 && isSupported("GL_ARB_compatibility"))
{
m_settings.flags |= ContextSettings::Compatibility;
}
}
if(m_settings.antialiasing > 0 && wanted.antialiasing > 0)
{
gl::enable(GL_MULTISAMPLE);
if(!gl::isEnabled(GL_MULTISAMPLE))
{
m_settings.antialiasing = 0;
}
}
else
{
m_settings.antialiasing = 0;
}
}
}
}
}
<commit_msg>[Render/Context/GlContext] Use thread_local instread of Bull::Local<commit_after>#include <memory>
#include <set>
#include <Bull/Core/System/Config.hpp>
#include <Bull/Core/Thread/Lock.hpp>
#include <Bull/Render/Context/Context.hpp>
#include <Bull/Render/Context/GlContext.hpp>
#include <Bull/Render/OpenGL.hpp>
#include <Bull/Render/GlLoader.hpp>
#include <Bull/Utility/Window/VideoMode.hpp>
#if defined BULL_OS_WINDOWS
#include <Bull/Render/Context/Wgl/WglContext.hpp>
typedef Bull::prv::WglContext ContextType;
#else
#include <Bull/Render/Context/Glx/GlxContext.hpp>
typedef Bull::prv::GlxContext ContextType;
#endif
namespace Bull
{
namespace prv
{
namespace
{
thread_local std::shared_ptr<Context> internal(nullptr);
std::set<std::shared_ptr<Context>> internals;
Mutex internalsMutex;
thread_local const GlContext* current(nullptr);
std::shared_ptr<ContextType> shared;
Mutex sharedContextMutex;
std::shared_ptr<Context> getInternalContext()
{
if(internal == nullptr)
{
internal = std::make_shared<Context>();
Lock lock(internalsMutex);
internals.insert(internal);
}
return internal;
}
}
/*! \brief Perform internal initialization
*
*/
void GlContext::globalInit()
{
Lock lock(sharedContextMutex);
shared = std::make_shared<ContextType>(nullptr);
shared->setActive(true);
/// We load OpenGL functions before initialize because this method uses OpenGL functions (glEnable, glGetIntegerv...)
ExtensionsLoader::Instance loader = ExtensionsLoader::get(shared->getSurfaceHandler());
ContextType::requireExtensions(loader);
GlLoader::load();
loader->load();
shared->initialize();
/// Ensure two things:
/// + The shared context is disabled
/// + The internal context is enable
shared->setActive(false);
}
/*! \brief Perform internal cleanup
*
*/
void GlContext::globalCleanup()
{
Lock lockInternals(internalsMutex);
internals.clear();
Lock lockShared(sharedContextMutex);
shared.reset();
}
/*! \brief Ensure there is an active OpenGL context in this thread
*
*/
void GlContext::ensureContext()
{
if(Context::getActive() == nullptr)
{
getInternalContext();
}
}
/*! \brief Create an OS specific instance of GlContext
*
* \return Return the created context
*
*/
GlContext* GlContext::createInstance()
{
ContextType* context = new ContextType(shared);
context->initialize();
return context;
}
/*! \brief Create an OS specific instance of GlContext
*
* \param mode The VideoMode to use to create the context
* \param settings Settings to use to create the context
*
* \return Return the created context
*
*/
GlContext* GlContext::createInstance(const VideoMode& mode, const ContextSettings& settings)
{
ContextType* context = new ContextType(shared, mode, settings);
context->initialize();
return context;
}
/*! \brief Create an OS specific instance of GlContext
*
* \param bitsPerPixel Number of bits per pixel to use
* \param settings Settings to use to create the context
*
* \return Return the created context
*
*/
GlContext* GlContext::createInstance(unsigned int bitsPerPixel, const ContextSettings& settings)
{
ContextType* context = new ContextType(shared, bitsPerPixel, settings);
context->initialize(settings);
return context;
}
/*! \brief Create an OS specific instance of GlContext
*
* \param window The window to bind the created context
* \param bitsPerPixel The number of bits to use per pixel
* \param settings Parameters to create the OpenGL context
*
* \return Return the created context
*
*/
GlContext* GlContext::createInstance(WindowHandler window, unsigned int bitsPerPixel, const ContextSettings& settings)
{
ContextType* context = new ContextType(shared, window, bitsPerPixel, settings);
context->initialize(settings);
return context;
}
/*! \brief Get an OpenGL function
*
* \param function The function name
*
* \param Return the function, nullptr if the function is not available
*
*/
void* GlContext::getFunction(const String& function)
{
return ContextType::getFunction(function);
}
/*! \brief Check whether an extensions is loaded
*
* \param extension The name of the extension
*
* \return Return true if the extension is loaded, false otherwise
*
*/
bool GlContext::isLoaded(const String& extension)
{
return ExtensionsLoader::isSet() ? ExtensionsLoader::get()->isLoaded(extension) : false;
}
/*! \brief Check whether an extensions is loaded
*
* \param extension The extension
*
* \return Return true if the extension is loaded, false otherwise
*
*/
bool GlContext::isLoaded(const ExtensionsLoader::Extension& extension)
{
return ExtensionsLoader::isSet() ? ExtensionsLoader::get()->isLoaded(extension) : false;
}
/*! \brief Check whether an extensions is loaded
*
* \param extension The name of the extension
*
* \return Return true if the extension is supported, false otherwise
*
*/
bool GlContext::isSupported(const String& extension)
{
return ExtensionsLoader::isSet() ? ExtensionsLoader::get()->isSupported(extension) : false;
}
/*! \brief Check whether an extensions is loaded
*
* \param extension The extension
*
* \return Return true if the extension is supported, false otherwise
*
*/
bool GlContext::isSupported(const ExtensionsLoader::Extension& extension)
{
return ExtensionsLoader::isSet() ? ExtensionsLoader::get()->isSupported(extension) : false;
}
/*! \brief Give a mark to a pixel format
*
* \param bitsPerPixel
* \param depths
* \param stencil
* \param antialiasing
* \param bitsPerPixelWanted
* \param settingsWanted
*
* \return Return the mark of the pixel format
*
*/
int GlContext::evaluatePixelFormat(unsigned int bitsPerPixel, int depths, int stencil, unsigned int antialiasing, unsigned int bitsPerPixelWanted, const ContextSettings& settingsWanted)
{
int colorDiff = static_cast<int>(bitsPerPixelWanted) - bitsPerPixel;
int depthDiff = static_cast<int>(settingsWanted.depths) - depths;
int stencilDiff = static_cast<int>(settingsWanted.stencil) - stencil;
int antialiasingDiff = static_cast<int>(settingsWanted.antialiasing) - antialiasing;
colorDiff *= ((colorDiff > 0) ? 100000 : 1);
depthDiff *= ((depthDiff > 0) ? 100000 : 1);
stencilDiff *= ((stencilDiff > 0) ? 100000 : 1);
antialiasingDiff *= ((antialiasingDiff > 0) ? 100000 : 1);
int score = std::abs(colorDiff) + std::abs(depthDiff) + std::abs(stencilDiff) + std::abs(antialiasingDiff);
return score;
}
/*! \brief Destructor
*
*/
GlContext::~GlContext()
{
/// Nothing
}
/*! \brief Activate or deactivate the context
*
* \param active True to activate, false to deactivate the context
*
* \return Return true if the context's status changed successfully, false otherwise
*
*/
bool GlContext::setActive(bool active)
{
if(active)
{
if(current != this)
{
if(makeCurrent())
{
current = this;
return true;
}
return false;
}
return true;
}
else
{
if(current == this)
{
return getInternalContext()->setActive(true);
}
return true;
}
}
/*! \brief Get the ContextSettings of the context
*
* \return Return the ContextSettings
*
*/
const ContextSettings& GlContext::getSettings() const
{
return m_settings;
}
/*! \brief Constructor
*
* \param settings Settings to use to create the context
*
*/
GlContext::GlContext(const ContextSettings& settings) :
m_settings(settings)
{
/// Nothing
}
/*! \brief Enable and perform initializations
*
* \param wanted Settings wanted to create the context
*
*/
void GlContext::initialize(const ContextSettings& wanted)
{
if(setActive(true))
{
int majorVersion = 0;
int minorVersion = 0;
gl::getIntegerv(GL_MAJOR_VERSION, &majorVersion);
gl::getIntegerv(GL_MINOR_VERSION, &minorVersion);
if(gl::getError() != GL_INVALID_ENUM)
{
m_settings.major = static_cast<unsigned int>(majorVersion);
m_settings.minor = static_cast<unsigned int>(minorVersion);
}
else
{
const GLubyte* version = gl::getString(GL_VERSION);
if (version)
{
m_settings.major = String::intToChar(version[0]);
m_settings.minor = String::intToChar(version[2]);
}
else
{
m_settings.major = 1;
m_settings.minor = 1;
}
}
m_settings.flags = ContextSettings::Default;
if(m_settings.major >= 3)
{
int flags;
gl::getIntegerv(GL_CONTEXT_FLAGS, &flags);
if(flags && GL_CONTEXT_FLAG_DEBUG_BIT)
{
m_settings.flags |= ContextSettings::Debug;
}
if(flags && GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT)
{
m_settings.flags |= ContextSettings::ForwardCompatible;
}
if(m_settings.major == 3 && m_settings.minor == 1 && isSupported("GL_ARB_compatibility"))
{
m_settings.flags |= ContextSettings::Compatibility;
}
}
if(m_settings.antialiasing > 0 && wanted.antialiasing > 0)
{
gl::enable(GL_MULTISAMPLE);
if(!gl::isEnabled(GL_MULTISAMPLE))
{
m_settings.antialiasing = 0;
}
}
else
{
m_settings.antialiasing = 0;
}
}
}
}
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief Space Invaders Emulator (side)
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "side/arcade.h"
namespace emu {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief スペース・インベーダー・エミュレーション・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class spinv {
InvadersMachine im_;
uint16_t scan_lines_[InvadersMachine::ScreenHeight];
bool load_sounds_(const char* root)
{
static const char* sdf[] = {
"BaseHit.wav", "InvHit.Wav", "Shot.wav", "Ufo.wav",
"UfoHit.wav", "Walk1.wav", "Walk2.wav", "Walk3.wav",
"Walk4.wav"
};
return true;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクタ
*/
//-----------------------------------------------------------------//
spinv() : im_() { }
//-----------------------------------------------------------------//
/*!
@brief 開始
@param[in] root ルート・パス
@return 成功なら「tue」
*/
//-----------------------------------------------------------------//
bool start(const char* root)
{
static const char* rom_files[] = {
"invaders.h", "invaders.g", "invaders.f", "invaders.e"
};
{
char rom[0x2000];
for(uint32_t i = 0; i < 4; ++i) {
char tmp[256];
if(root != nullptr) {
strcpy(tmp, root);
} else {
strcpy(tmp, "/");
}
strcat(tmp, "/");
strcat(tmp, rom_files[i]);
FILE* fp = fopen(tmp, "rb");
if(fp == nullptr) {
utils::format("Can't open: '%s'\n") % tmp;
return false;
}
if(fread(&rom[i * 0x800], 1, 0x800, fp) != 0x800) {
utils::format("Can't read data: '%s'\n") % tmp;
fclose(fp);
return false;
}
utils::format("Read ROM: '%s'\n") % tmp;
fclose(fp);
}
uint32_t sum = 0;
for(uint32_t i = 0; i < 0x2000; ++i) {
sum += (uint8_t)rom[i];
}
utils::format("ROM SUM: %08X\n") % sum;
im_.setROM(rom);
}
if(!load_sounds_(root)) {
utils::format("Sound files not found. no sound\n");
}
im_.reset();
// auto fr = im_.getFrameRate();
// utils::format("FrameRate: %d\n") % fr;
for(int i = 0; i < InvadersMachine::ScreenHeight; ++i) {
uint16_t c = 0b11111'111111'11111;
if( i >= 32 && i < 64 ) c = 0b11111'000000'00000; // Red
if( i >= 184 && i < 240 ) c = 0b00000'111111'00000; // Green
scan_lines_[i] = c;
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief サービス
@param[in] org フレームバッファアドレス
@param[in] w 横幅
@param[in] h 高さ
*/
//-----------------------------------------------------------------//
void service(void* org, int w, int h)
{
const uint8_t* video = im_.getVideo();
if(video != nullptr) {
uint16_t* fb = static_cast<uint16_t*>(org);
uint32_t yo = (h - InvadersMachine::ScreenHeight) / 2;
uint32_t xo = (w - InvadersMachine::ScreenWidth) / 2;
for(uint32_t y = 0; y < InvadersMachine::ScreenHeight; ++y) {
uint32_t c = scan_lines_[y];
for(uint32_t x = 0; x < InvadersMachine::ScreenWidth; ++x) {
if( *video ) {
fb[(y + yo) * w + x + xo] = c;
} else {
fb[(y + yo) * w + x + xo] = 0x0000;
}
++video;
}
}
}
im_.step();
}
};
}
<commit_msg>update: read rom file<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief Space Invaders Emulator (side)
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "side/arcade.h"
#include "common/file_io.hpp"
namespace emu {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief スペース・インベーダー・エミュレーション・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class spinv {
InvadersMachine im_;
uint16_t scan_lines_[InvadersMachine::ScreenHeight];
bool load_sounds_(const char* root)
{
static const char* sdf[] = {
"BaseHit.wav", "InvHit.Wav", "Shot.wav", "Ufo.wav",
"UfoHit.wav", "Walk1.wav", "Walk2.wav", "Walk3.wav",
"Walk4.wav"
};
return true;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクタ
*/
//-----------------------------------------------------------------//
spinv() : im_() { }
//-----------------------------------------------------------------//
/*!
@brief 開始
@param[in] root ルート・パス
@return 成功なら「tue」
*/
//-----------------------------------------------------------------//
bool start(const char* root)
{
static const char* rom_files[] = {
"invaders.h", "invaders.g", "invaders.f", "invaders.e"
};
{
char rom[0x2000];
for(uint32_t i = 0; i < 4; ++i) {
char tmp[256];
if(root != nullptr) {
strcpy(tmp, root);
} else {
strcpy(tmp, "/");
}
strcat(tmp, "/");
strcat(tmp, rom_files[i]);
utils::file_io fi;
if(!fi.open(tmp, "rb")) {
utils::format("Can't open: '%s'\n") % tmp;
return false;
}
if(fi.read(&rom[i * 0x800], 0x800) != 0x800) {
utils::format("Can't read data: '%s'\n") % tmp;
fi.close();
return false;
}
utils::format("Read ROM: '%s'\n") % tmp;
fi.close();
}
uint32_t sum = 0;
for(uint32_t i = 0; i < 0x2000; ++i) {
sum += (uint8_t)rom[i];
}
utils::format("ROM SUM: %08X\n") % sum;
im_.setROM(rom);
}
if(!load_sounds_(root)) {
utils::format("Sound files not found. no sound\n");
}
im_.reset();
// auto fr = im_.getFrameRate();
// utils::format("FrameRate: %d\n") % fr;
for(int i = 0; i < InvadersMachine::ScreenHeight; ++i) {
uint16_t c = 0b11111'111111'11111;
if( i >= 32 && i < 64 ) c = 0b11111'000000'00000; // Red
if( i >= 184 && i < 240 ) c = 0b00000'111111'00000; // Green
scan_lines_[i] = c;
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief サービス
@param[in] org フレームバッファアドレス
@param[in] w 横幅
@param[in] h 高さ
*/
//-----------------------------------------------------------------//
void service(void* org, int w, int h)
{
const uint8_t* video = im_.getVideo();
if(video != nullptr) {
uint16_t* fb = static_cast<uint16_t*>(org);
uint32_t yo = (h - InvadersMachine::ScreenHeight) / 2;
uint32_t xo = (w - InvadersMachine::ScreenWidth) / 2;
for(uint32_t y = 0; y < InvadersMachine::ScreenHeight; ++y) {
uint32_t c = scan_lines_[y];
for(uint32_t x = 0; x < InvadersMachine::ScreenWidth; ++x) {
if( *video ) {
fb[(y + yo) * w + x + xo] = c;
} else {
fb[(y + yo) * w + x + xo] = 0x0000;
}
++video;
}
}
}
im_.step();
}
};
}
<|endoftext|> |
<commit_before>#include <numeric>
#include <cassert>
namespace Arcv {
template <typename T>
Matrix<T> Image::threshold(Matrix<T> mat, T firstLowerBound, T firstUpperBound,
T secondLowerBound, T secondUpperBound,
T thirdLowerBound, T thirdUpperBound) {
assert(("Error: Input matrix should have 3 or 4 channels", mat.getChannelCount() == 3 || mat.getChannelCount() == 4));
Matrix<T> res(mat.getWidth(), mat.getHeight(), 1, mat.getImgBitDepth(), ARCV_COLORSPACE_GRAY);
std::size_t resIndex = 0;
for (auto elt = mat.getData().begin(); elt != mat.getData().end(); elt += mat.getChannelCount(), ++resIndex)
res[resIndex] = (*elt <= firstUpperBound && *elt >= firstLowerBound
&& *(elt + 1) <= secondUpperBound && *(elt + 1) >= secondLowerBound
&& *(elt + 2) <= thirdUpperBound && *(elt + 2) >= thirdLowerBound ? 255 : 0);
return res;
}
template <typename T>
Matrix <T> Image::rotateLeft(const Matrix <T>& mat) {
Matrix<T> res(mat.getHeight(), mat.getWidth(), mat.getChannelCount(), mat.getImgBitDepth(), mat.getColorspace());
for (std::size_t hIndex = 0, resWIndex = 0; hIndex < mat.getHeight(), resWIndex < res.getWidth(); ++hIndex, ++resWIndex) {
for (std::size_t wIndex = 0, resHIndex = res.getHeight() - 1; wIndex < mat.getWidth(), resHIndex > 0; ++wIndex, --resHIndex) {
const std::size_t matIndex = (hIndex * mat.getWidth() + wIndex) * mat.getChannelCount();
const std::size_t resIndex = (resHIndex * res.getWidth() + resWIndex) * res.getChannelCount();
for (uint8_t chan = 0; chan < mat.getChannelCount(); ++chan)
res[resIndex + chan] = mat[matIndex + chan];
}
}
return res;
}
template <typename T>
Matrix <T> Image::rotateRight(const Matrix <T>& mat) {
Matrix<T> res(mat.getHeight(), mat.getWidth(), mat.getChannelCount(), mat.getImgBitDepth(), mat.getColorspace());
for (std::size_t hIndex = 0, resWIndex = res.getWidth(); hIndex < mat.getHeight(), resWIndex > 0; ++hIndex, --resWIndex) {
for (std::size_t wIndex = 0, resHIndex = 0; wIndex < mat.getWidth(), resHIndex < res.getHeight(); ++wIndex, ++resHIndex) {
const std::size_t matIndex = (hIndex * mat.getWidth() + wIndex) * mat.getChannelCount();
const std::size_t resIndex = (resHIndex * res.getWidth() + resWIndex) * res.getChannelCount();
for (uint8_t chan = 0; chan < mat.getChannelCount(); ++chan)
res[resIndex + chan] = mat[matIndex + chan];
}
}
return res;
}
template <typename T>
Matrix <T> Image::reverse(const Matrix <T>& mat) {
Matrix<T> res(mat.getWidth(), mat.getHeight(), mat.getChannelCount(), mat.getImgBitDepth(), mat.getColorspace());
for (std::size_t hIndex = 0, resHIndex = res.getHeight() - 1; hIndex < mat.getHeight(), resHIndex > 0; ++hIndex, --resHIndex) {
for (std::size_t wIndex = 0, resWIndex = res.getWidth(); wIndex < mat.getWidth(), resWIndex > 0; ++wIndex, --resWIndex) {
const std::size_t matIndex = (hIndex * mat.getWidth() + wIndex) * mat.getChannelCount();
const std::size_t resIndex = (resHIndex * res.getWidth() + resWIndex) * res.getChannelCount();
for (uint8_t chan = 0; chan < mat.getChannelCount(); ++chan)
res[resIndex + chan] = mat[matIndex + chan];
}
}
return res;
}
template <typename T>
Matrix<T> Image::horizontalFlip(const Matrix<T>& mat) {
Matrix<T> res(mat.getWidth(), mat.getHeight(), mat.getChannelCount(), mat.getImgBitDepth(), mat.getColorspace());
for (std::size_t hIndex = 0, resHIndex = 0; hIndex < mat.getHeight(), resHIndex < res.getHeight(); ++hIndex, ++resHIndex) {
for (std::size_t wIndex = 0, resWIndex = res.getWidth() - 1; wIndex < mat.getWidth(), resWIndex > 0; ++wIndex, --resWIndex) {
const std::size_t matIndex = (hIndex * mat.getWidth() + wIndex) * mat.getChannelCount();
const std::size_t resIndex = (resHIndex * res.getWidth() + resWIndex) * res.getChannelCount();
for (uint8_t chan = 0; chan < mat.getChannelCount(); ++chan)
res[resIndex + chan] = mat[matIndex + chan];
}
}
return res;
}
template <typename T>
Matrix<T> Image::verticalFlip(const Matrix<T>& mat) {
Matrix<T> res(mat.getWidth(), mat.getHeight(), mat.getChannelCount(), mat.getImgBitDepth(), mat.getColorspace());
for (std::size_t hIndex = 0, resHIndex = res.getHeight() - 1; hIndex < mat.getHeight(), resHIndex > 0; ++hIndex, --resHIndex) {
for (std::size_t wIndex = 0, resWIndex = 0; wIndex < mat.getWidth(), resWIndex < res.getWidth(); ++wIndex, ++resWIndex) {
const std::size_t matIndex = (hIndex * mat.getWidth() + wIndex) * mat.getChannelCount();
const std::size_t resIndex = (resHIndex * res.getWidth() + resWIndex) * res.getChannelCount();
for (uint8_t chan = 0; chan < mat.getChannelCount(); ++chan)
res[resIndex + chan] = mat[matIndex + chan];
}
}
return res;
}
template <typename T>
Matrix<T> Image::region(const Matrix<T>& mat, std::size_t widthBegin, std::size_t widthEnd,
std::size_t heightBegin, std::size_t heightEnd) {
assert(("Error: Beginning boundaries must be lower than ending ones", widthBegin < widthEnd && heightBegin < heightEnd));
Matrix<T> res(widthEnd - widthBegin, heightEnd - heightBegin, mat.getChannelCount(), mat.getImgBitDepth(), mat.getColorspace());
for (std::size_t hIndex = heightBegin, resHIndex = 0; hIndex < heightEnd, resHIndex < res.getHeight(); ++hIndex, ++resHIndex) {
for (std::size_t wIndex = widthBegin, resWIndex = 0; wIndex < heightEnd, resWIndex < res.getWidth(); ++wIndex, ++resWIndex) {
const std::size_t matIndex = (hIndex * mat.getWidth() + wIndex) * mat.getChannelCount();
const std::size_t resIndex = (resHIndex * res.getWidth() + resWIndex) * res.getChannelCount();
for (uint8_t chan = 0; chan < mat.getChannelCount(); ++chan)
res[resIndex + chan] = mat[matIndex + chan];
}
}
return res;
}
} // namespace Arcv
<commit_msg>[Fix] Right rotation & reversion now compile on Visual Studio<commit_after>#include <numeric>
#include <cassert>
namespace Arcv {
template <typename T>
Matrix<T> Image::threshold(Matrix<T> mat, T firstLowerBound, T firstUpperBound,
T secondLowerBound, T secondUpperBound,
T thirdLowerBound, T thirdUpperBound) {
assert(("Error: Input matrix should have 3 or 4 channels", mat.getChannelCount() == 3 || mat.getChannelCount() == 4));
Matrix<T> res(mat.getWidth(), mat.getHeight(), 1, mat.getImgBitDepth(), ARCV_COLORSPACE_GRAY);
std::size_t resIndex = 0;
for (auto elt = mat.getData().begin(); elt != mat.getData().end(); elt += mat.getChannelCount(), ++resIndex)
res[resIndex] = (*elt <= firstUpperBound && *elt >= firstLowerBound
&& *(elt + 1) <= secondUpperBound && *(elt + 1) >= secondLowerBound
&& *(elt + 2) <= thirdUpperBound && *(elt + 2) >= thirdLowerBound ? 255 : 0);
return res;
}
template <typename T>
Matrix <T> Image::rotateLeft(const Matrix <T>& mat) {
Matrix<T> res(mat.getHeight(), mat.getWidth(), mat.getChannelCount(), mat.getImgBitDepth(), mat.getColorspace());
for (std::size_t hIndex = 0, resWIndex = 0; hIndex < mat.getHeight(), resWIndex < res.getWidth(); ++hIndex, ++resWIndex) {
for (std::size_t wIndex = 0, resHIndex = res.getHeight() - 1; wIndex < mat.getWidth(), resHIndex > 0; ++wIndex, --resHIndex) {
const std::size_t matIndex = (hIndex * mat.getWidth() + wIndex) * mat.getChannelCount();
const std::size_t resIndex = (resHIndex * res.getWidth() + resWIndex) * res.getChannelCount();
for (uint8_t chan = 0; chan < mat.getChannelCount(); ++chan)
res[resIndex + chan] = mat[matIndex + chan];
}
}
return res;
}
template <typename T>
Matrix <T> Image::rotateRight(const Matrix <T>& mat) {
Matrix<T> res(mat.getHeight(), mat.getWidth(), mat.getChannelCount(), mat.getImgBitDepth(), mat.getColorspace());
for (std::size_t hIndex = 0, resWIndex = res.getWidth() - 1; hIndex < mat.getHeight(), resWIndex > 0; ++hIndex, --resWIndex) {
for (std::size_t wIndex = 0, resHIndex = 0; wIndex < mat.getWidth(), resHIndex < res.getHeight(); ++wIndex, ++resHIndex) {
const std::size_t matIndex = (hIndex * mat.getWidth() + wIndex) * mat.getChannelCount();
const std::size_t resIndex = (resHIndex * res.getWidth() + resWIndex) * res.getChannelCount();
for (uint8_t chan = 0; chan < mat.getChannelCount(); ++chan)
res[resIndex + chan] = mat[matIndex + chan];
}
}
return res;
}
template <typename T>
Matrix <T> Image::reverse(const Matrix <T>& mat) {
Matrix<T> res(mat.getWidth(), mat.getHeight(), mat.getChannelCount(), mat.getImgBitDepth(), mat.getColorspace());
for (std::size_t hIndex = 0, resHIndex = res.getHeight() - 1; hIndex < mat.getHeight(), resHIndex > 0; ++hIndex, --resHIndex) {
for (std::size_t wIndex = 0, resWIndex = res.getWidth() - 1; wIndex < mat.getWidth(), resWIndex > 0; ++wIndex, --resWIndex) {
const std::size_t matIndex = (hIndex * mat.getWidth() + wIndex) * mat.getChannelCount();
const std::size_t resIndex = (resHIndex * res.getWidth() + resWIndex) * res.getChannelCount();
for (uint8_t chan = 0; chan < mat.getChannelCount(); ++chan)
res[resIndex + chan] = mat[matIndex + chan];
}
}
return res;
}
template <typename T>
Matrix<T> Image::horizontalFlip(const Matrix<T>& mat) {
Matrix<T> res(mat.getWidth(), mat.getHeight(), mat.getChannelCount(), mat.getImgBitDepth(), mat.getColorspace());
for (std::size_t hIndex = 0, resHIndex = 0; hIndex < mat.getHeight(), resHIndex < res.getHeight(); ++hIndex, ++resHIndex) {
for (std::size_t wIndex = 0, resWIndex = res.getWidth() - 1; wIndex < mat.getWidth(), resWIndex > 0; ++wIndex, --resWIndex) {
const std::size_t matIndex = (hIndex * mat.getWidth() + wIndex) * mat.getChannelCount();
const std::size_t resIndex = (resHIndex * res.getWidth() + resWIndex) * res.getChannelCount();
for (uint8_t chan = 0; chan < mat.getChannelCount(); ++chan)
res[resIndex + chan] = mat[matIndex + chan];
}
}
return res;
}
template <typename T>
Matrix<T> Image::verticalFlip(const Matrix<T>& mat) {
Matrix<T> res(mat.getWidth(), mat.getHeight(), mat.getChannelCount(), mat.getImgBitDepth(), mat.getColorspace());
for (std::size_t hIndex = 0, resHIndex = res.getHeight() - 1; hIndex < mat.getHeight(), resHIndex > 0; ++hIndex, --resHIndex) {
for (std::size_t wIndex = 0, resWIndex = 0; wIndex < mat.getWidth(), resWIndex < res.getWidth(); ++wIndex, ++resWIndex) {
const std::size_t matIndex = (hIndex * mat.getWidth() + wIndex) * mat.getChannelCount();
const std::size_t resIndex = (resHIndex * res.getWidth() + resWIndex) * res.getChannelCount();
for (uint8_t chan = 0; chan < mat.getChannelCount(); ++chan)
res[resIndex + chan] = mat[matIndex + chan];
}
}
return res;
}
template <typename T>
Matrix<T> Image::region(const Matrix<T>& mat, std::size_t widthBegin, std::size_t widthEnd,
std::size_t heightBegin, std::size_t heightEnd) {
assert(("Error: Beginning boundaries must be lower than ending ones", widthBegin < widthEnd && heightBegin < heightEnd));
Matrix<T> res(widthEnd - widthBegin, heightEnd - heightBegin, mat.getChannelCount(), mat.getImgBitDepth(), mat.getColorspace());
for (std::size_t hIndex = heightBegin, resHIndex = 0; hIndex < heightEnd, resHIndex < res.getHeight(); ++hIndex, ++resHIndex) {
for (std::size_t wIndex = widthBegin, resWIndex = 0; wIndex < heightEnd, resWIndex < res.getWidth(); ++wIndex, ++resWIndex) {
const std::size_t matIndex = (hIndex * mat.getWidth() + wIndex) * mat.getChannelCount();
const std::size_t resIndex = (resHIndex * res.getWidth() + resWIndex) * res.getChannelCount();
for (uint8_t chan = 0; chan < mat.getChannelCount(); ++chan)
res[resIndex + chan] = mat[matIndex + chan];
}
}
return res;
}
} // namespace Arcv
<|endoftext|> |
<commit_before>// SimpleTextBlock.cpp
#include "SimpleTextBlock.h"
#include "VisualPainter.h"
#include "TextStyleRegistry.h"
#include "TextDocumentReader.h"
#include "TextStyleReader.h"
#include <algorithm>
SimpleTextBlock::SimpleTextBlock( SimpleLayoutDataPtr data, const TextStyleRegistry& styleRegistry )
: m_data( std::move( data ) )
, m_styleRegistry( styleRegistry )
{
}
void SimpleTextBlock::DrawBackground( VisualPainter& painter, RECT rect ) const
{
size_t firstLine = rect.top / m_styleRegistry.lineHeight;
rect.top = firstLine * m_styleRegistry.lineHeight;
for ( size_t line = firstLine; line < m_data->lines.size() && !IsRectEmpty( &rect ); ++line )
{
DrawLineBackground( line, painter, rect );
DrawLineSelection ( line, painter, rect );
rect.top += m_styleRegistry.lineHeight;
}
}
void SimpleTextBlock::DrawText( VisualPainter& painter, RECT rect ) const
{
size_t firstLine = rect.top / m_styleRegistry.lineHeight;
rect.top = firstLine * m_styleRegistry.lineHeight;
for ( size_t line = firstLine; line < m_data->lines.size() && !IsRectEmpty( &rect ); ++line )
{
DrawLineText( line, painter, rect );
rect.top += m_styleRegistry.lineHeight;
}
}
void SimpleTextBlock::DrawLineBackground( size_t line, VisualPainter& painter, RECT rect ) const
{
size_t pos = TextStart( line );
int xStart = 0;
ArrayOf<const TextStyleRun> styles = painter.styleReader.Styles( pos, TextEnd( line ) - pos );
for ( const TextStyleRun* it = styles.begin(); it != styles.end() && xStart < rect.right; ++it )
{
int xEnd = CPtoX( line, pos + it->count - 1, true );
DrawLineRect( painter, rect, xStart, xEnd, m_styleRegistry.Style( it->styleid ).bkColor );
pos += it->count;
xStart = xEnd;
}
}
void SimpleTextBlock::DrawLineSelection( size_t line, VisualPainter& painter, RECT rect ) const
{
if ( painter.selection.Intersects( TextStart( line ), TextEnd( line ) ) )
{
size_t start = std::max( painter.selection.Min(), TextStart( line ) );
size_t end = std::min( painter.selection.Max(), TextEnd ( line ) );
if ( start < end )
{
int xStart = CPtoX( line, start, false );
int xEnd = CPtoX( line, end - 1, true );
DrawLineRect( painter, rect, xStart, xEnd, m_styleRegistry.selectionColor );
}
}
if ( line == m_data->lines.size() - 1
&& painter.selection.Intersects( TextEnd( line ), m_data->length )
&& m_data->endsWithNewline )
{
int xStart = LineWidth( line );
int xEnd = LineWidth( line ) + m_styleRegistry.avgCharWidth;
DrawLineRect( painter, rect, xStart, xEnd, m_styleRegistry.selectionColor );
}
}
void SimpleTextBlock::DrawLineText( size_t line, VisualPainter& painter, RECT rect ) const
{
size_t pos = TextStart( line );
int xStart = 0;
ArrayOf<const TextStyleRun> styles = painter.styleReader.Styles( pos, TextEnd( line ) - pos );
for ( const TextStyleRun* it = styles.begin(); it != styles.end() && xStart < rect.right; ++it )
{
const TextStyle& style = m_styleRegistry.Style( it->styleid );
SelectObject( painter.hdc, m_styleRegistry.Font( style.fontid ).hfont );
SetTextColor( painter.hdc, style.textColor );
UTF16Ref text = painter.docReader.StrictRange( painter.textStart + pos, it->count );
ExtTextOutW( painter.hdc, xStart, rect.top, ETO_CLIPPED, &rect, text.begin(), it->count, NULL );
pos += it->count;
xStart = CPtoX( line, pos - 1, true );
}
}
void SimpleTextBlock::DrawLineRect( VisualPainter& painter, RECT rect, int xStart, int xEnd, uint32 color ) const
{
RECT drawRect = { std::max<int>( xStart, rect.left ),
rect.top,
std::min<int>( xEnd, rect.right ),
rect.top + m_styleRegistry.lineHeight };
if ( !IsRectEmpty( &drawRect ) )
painter.DrawRect( drawRect, color );
}
size_t SimpleTextBlock::LineCount() const
{
return m_data->lines.size();
}
size_t SimpleTextBlock::LineContaining( size_t pos ) const
{
size_t line = 0;
while ( line < m_data->lines.size() && TextEnd( line ) <= pos )
++line;
return line;
}
size_t SimpleTextBlock::LineStart( int y ) const
{
int line = y / m_styleRegistry.lineHeight;
Assert( line >= 0 && size_t( line ) < m_data->lines.size() );
return TextStart( line );
}
size_t SimpleTextBlock::LineEnd( int y ) const
{
int line = y / m_styleRegistry.lineHeight;
Assert( line >= 0 && size_t( line ) < m_data->lines.size() );
return TextEnd( line );
}
POINT SimpleTextBlock::PointFromChar( size_t pos, bool advancing ) const
{
POINT result;
bool trailingEdge = advancing;
if ( pos == 0 )
trailingEdge = false;
else if ( pos >= TextEnd( m_data->lines.size() - 1 ) )
trailingEdge = true;
if ( trailingEdge )
--pos;
size_t line = LineContaining( pos );
Assert( line < m_data->lines.size() );
result.x = CPtoX( line, pos, trailingEdge );
result.y = line * m_styleRegistry.lineHeight;
return result;
}
size_t SimpleTextBlock::CharFromPoint( POINT* point ) const
{
int line = point->y / m_styleRegistry.lineHeight;
if ( line < 0 || size_t( line ) >= m_data->lines.size() )
line = m_data->lines.size() - 1;
point->y = line * m_styleRegistry.lineHeight;
return XtoCP( line, &point->x );
}
size_t SimpleTextBlock::Length() const
{
return m_data->length;
}
int SimpleTextBlock::Height() const
{
return m_data->lines.size() * m_styleRegistry.lineHeight;
}
bool SimpleTextBlock::EndsWithNewline() const
{
return m_data->endsWithNewline;
}
ArrayOf<const SimpleTextRun> SimpleTextBlock::LineRuns( size_t line ) const
{
Assert( line < m_data->lines.size() );
const SimpleTextRun* runStart = &m_data->runs.front() + ( line > 0 ? m_data->lines[line - 1] : 0 );
return ArrayOf<const SimpleTextRun>( runStart, &m_data->runs.front() + m_data->lines[line] );
}
size_t SimpleTextBlock::TextStart( size_t line ) const
{
ArrayOf<const SimpleTextRun> runs = LineRuns( line );
return runs[0].textStart;
}
size_t SimpleTextBlock::TextEnd( size_t line ) const
{
ArrayOf<const SimpleTextRun> runs = LineRuns( line );
return runs[runs.size() - 1].textStart + runs[runs.size() - 1].textCount;
}
int SimpleTextBlock::LineWidth( size_t line ) const
{
ArrayOf<const SimpleTextRun> runs = LineRuns( line );
int width = 0;
for ( const SimpleTextRun* run = runs.begin(); run != runs.end(); ++run )
width += RunWidth( run );
return width;
}
int SimpleTextBlock::RunWidth( const SimpleTextRun* run ) const
{
return m_data->xOffsets[run->textStart + run->textCount - 1];
}
int SimpleTextBlock::CPtoX( size_t line, size_t cp, bool trailingEdge ) const
{
ArrayOf<const SimpleTextRun> runs = LineRuns( line );
int x = 0;
const SimpleTextRun* run = runs.begin();
while ( run != runs.end() && run->textStart + run->textCount <= cp )
{
x += RunWidth( run );
run++;
}
Assert( run != runs.end() );
Assert( cp < run->textStart + run->textCount );
if ( trailingEdge )
x += m_data->xOffsets[cp];
else if ( cp > run->textStart )
x += m_data->xOffsets[cp - 1];
return x;
}
size_t SimpleTextBlock::XtoCP( size_t line, LONG* x ) const
{
ArrayOf<const SimpleTextRun> runs = LineRuns( line );
int xStart = 0;
const SimpleTextRun* run = runs.begin();
while ( run != runs.end() && xStart + RunWidth( run ) <= *x )
{
xStart += RunWidth( run );
run++;
}
if ( run == runs.end() )
{
*x = LineWidth( line );
return TextEnd( line );
}
size_t cp = run->textStart;
int xOffset = 0;
while ( cp < run->textStart + run->textCount && xStart + xOffset + ( m_data->xOffsets[cp] - xOffset ) / 2 < *x )
{
xOffset = m_data->xOffsets[cp];
++cp;
}
*x = xStart + xOffset;
return cp;
}
<commit_msg>This should have been in the last change.<commit_after>// SimpleTextBlock.cpp
#include "SimpleTextBlock.h"
#include "VisualPainter.h"
#include "TextStyleRegistry.h"
#include "TextDocumentReader.h"
#include "TextStyleReader.h"
#include <algorithm>
SimpleTextBlock::SimpleTextBlock( SimpleLayoutDataPtr data, const TextStyleRegistry& styleRegistry )
: m_data( std::move( data ) )
, m_styleRegistry( styleRegistry )
{
}
void SimpleTextBlock::DrawBackground( VisualPainter& painter, RECT rect ) const
{
size_t firstLine = rect.top / m_styleRegistry.lineHeight;
rect.top = firstLine * m_styleRegistry.lineHeight;
for ( size_t line = firstLine; line < m_data->lines.size() && !IsRectEmpty( &rect ); ++line )
{
DrawLineBackground( line, painter, rect );
DrawLineSelection ( line, painter, rect );
rect.top += m_styleRegistry.lineHeight;
}
}
void SimpleTextBlock::DrawText( VisualPainter& painter, RECT rect ) const
{
size_t firstLine = rect.top / m_styleRegistry.lineHeight;
rect.top = firstLine * m_styleRegistry.lineHeight;
for ( size_t line = firstLine; line < m_data->lines.size() && !IsRectEmpty( &rect ); ++line )
{
DrawLineText( line, painter, rect );
rect.top += m_styleRegistry.lineHeight;
}
}
void SimpleTextBlock::DrawLineBackground( size_t line, VisualPainter& painter, RECT rect ) const
{
size_t pos = TextStart( line );
int xStart = 0;
ArrayOf<const TextStyleRun> styles = painter.styleReader.Styles( pos, TextEnd( line ) - pos );
for ( const TextStyleRun* it = styles.begin(); it != styles.end() && xStart < rect.right; ++it )
{
int xEnd = CPtoX( line, pos + it->count - 1, true );
DrawLineRect( painter, rect, xStart, xEnd, m_styleRegistry.Style( it->styleid ).bkColor );
pos += it->count;
xStart = xEnd;
}
}
void SimpleTextBlock::DrawLineSelection( size_t line, VisualPainter& painter, RECT rect ) const
{
if ( painter.selection.Intersects( TextStart( line ), TextEnd( line ) ) )
{
size_t start = std::max( painter.selection.Min(), TextStart( line ) );
size_t end = std::min( painter.selection.Max(), TextEnd ( line ) );
int xStart = CPtoX( line, start, false );
int xEnd = CPtoX( line, end - 1, true );
DrawLineRect( painter, rect, xStart, xEnd, m_styleRegistry.selectionColor );
}
if ( line == m_data->lines.size() - 1
&& painter.selection.Intersects( TextEnd( line ), m_data->length )
&& m_data->endsWithNewline )
{
int xStart = LineWidth( line );
int xEnd = LineWidth( line ) + m_styleRegistry.avgCharWidth;
DrawLineRect( painter, rect, xStart, xEnd, m_styleRegistry.selectionColor );
}
}
void SimpleTextBlock::DrawLineText( size_t line, VisualPainter& painter, RECT rect ) const
{
ArrayOf<const SimpleTextRun> runs = LineRuns( line );
ArrayOf<const TextStyleRun> styles = painter.styleReader.Styles( TextStart( line ), TextEnd( line ) - TextStart( line ) );
int xRunStart = 0;
for ( const SimpleTextRun* run = runs.begin(); run != runs.end() && xRunStart < rect.right; ++run )
{
UTF16Ref text = painter.docReader.StrictRange( painter.textStart + run->textStart, run->textCount );
SelectObject( painter.hdc, m_styleRegistry.Font( run->fontid ).hfont );
ArrayOf<const TextStyleRun> runStyles = RunStyles( *run, styles );
for ( const TextStyleRun* style = runStyles.begin(); style != runStyles.end(); ++style )
{
size_t overlapStart = std::max( style->start, run->textStart );
size_t overlapEnd = std::min( style->start + style->count, run->textStart + run->textCount );
int xStart = xRunStart + RunCPtoX( *run, overlapStart, false );
if ( xStart >= rect.right )
break;
SetTextColor( painter.hdc, m_styleRegistry.Style( style->styleid ).textColor );
ExtTextOutW( painter.hdc,
xStart,
rect.top,
ETO_CLIPPED,
&rect,
text.begin() + ( overlapStart - run->textStart ),
overlapEnd - overlapStart,
NULL );
}
xRunStart += RunWidth( run );
}
}
ArrayOf<const TextStyleRun> SimpleTextBlock::RunStyles( const SimpleTextRun& run, ArrayOf<const TextStyleRun> styles ) const
{
struct StyleRunEqual
{
bool operator()( const TextStyleRun& a, const TextStyleRun& b ) const { return a.start + a.count < b.start; }
bool operator()( const TextStyleRun& a, const SimpleTextRun& b ) const { return a.start + a.count <= b.textStart; }
bool operator()( const SimpleTextRun& a, const TextStyleRun& b ) const { return a.textStart + a.textCount <= b.start; }
};
std::pair<const TextStyleRun*, const TextStyleRun*> range = std::equal_range( styles.begin(), styles.end(), run, StyleRunEqual() );
return ArrayOf<const TextStyleRun>( range.first, range.second );
}
void SimpleTextBlock::DrawLineRect( VisualPainter& painter, RECT rect, int xStart, int xEnd, uint32 color ) const
{
RECT drawRect = { std::max<int>( xStart, rect.left ),
rect.top,
std::min<int>( xEnd, rect.right ),
rect.top + m_styleRegistry.lineHeight };
if ( !IsRectEmpty( &drawRect ) )
painter.DrawRect( drawRect, color );
}
size_t SimpleTextBlock::LineCount() const
{
return m_data->lines.size();
}
size_t SimpleTextBlock::LineContaining( size_t pos ) const
{
size_t line = 0;
while ( line < m_data->lines.size() && TextEnd( line ) <= pos )
++line;
return line;
}
size_t SimpleTextBlock::LineStart( int y ) const
{
int line = y / m_styleRegistry.lineHeight;
Assert( line >= 0 && size_t( line ) < m_data->lines.size() );
return TextStart( line );
}
size_t SimpleTextBlock::LineEnd( int y ) const
{
int line = y / m_styleRegistry.lineHeight;
Assert( line >= 0 && size_t( line ) < m_data->lines.size() );
return TextEnd( line );
}
POINT SimpleTextBlock::PointFromChar( size_t pos, bool advancing ) const
{
POINT result;
bool trailingEdge = advancing;
if ( pos == 0 )
trailingEdge = false;
else if ( pos >= TextEnd( m_data->lines.size() - 1 ) )
trailingEdge = true;
if ( trailingEdge )
--pos;
size_t line = LineContaining( pos );
Assert( line < m_data->lines.size() );
result.x = CPtoX( line, pos, trailingEdge );
result.y = line * m_styleRegistry.lineHeight;
return result;
}
size_t SimpleTextBlock::CharFromPoint( POINT* point ) const
{
int line = point->y / m_styleRegistry.lineHeight;
if ( line < 0 || size_t( line ) >= m_data->lines.size() )
line = m_data->lines.size() - 1;
point->y = line * m_styleRegistry.lineHeight;
return XtoCP( line, &point->x );
}
size_t SimpleTextBlock::Length() const
{
return m_data->length;
}
int SimpleTextBlock::Height() const
{
return m_data->lines.size() * m_styleRegistry.lineHeight;
}
bool SimpleTextBlock::EndsWithNewline() const
{
return m_data->endsWithNewline;
}
ArrayOf<const SimpleTextRun> SimpleTextBlock::LineRuns( size_t line ) const
{
Assert( line < m_data->lines.size() );
const SimpleTextRun* runStart = &m_data->runs[line == 0 ? 0 : m_data->lines[line - 1]];
return ArrayOf<const SimpleTextRun>( runStart, &m_data->runs.front() + m_data->lines[line] );
}
size_t SimpleTextBlock::TextStart( size_t line ) const
{
ArrayOf<const SimpleTextRun> runs = LineRuns( line );
return runs[0].textStart;
}
size_t SimpleTextBlock::TextEnd( size_t line ) const
{
ArrayOf<const SimpleTextRun> runs = LineRuns( line );
return runs[runs.size() - 1].textStart + runs[runs.size() - 1].textCount;
}
int SimpleTextBlock::LineWidth( size_t line ) const
{
ArrayOf<const SimpleTextRun> runs = LineRuns( line );
int width = 0;
for ( const SimpleTextRun* run = runs.begin(); run != runs.end(); ++run )
width += RunWidth( run );
return width;
}
int SimpleTextBlock::RunWidth( const SimpleTextRun* run ) const
{
return m_data->xOffsets[run->textStart + run->textCount - 1];
}
int SimpleTextBlock::CPtoX( size_t line, size_t cp, bool trailingEdge ) const
{
ArrayOf<const SimpleTextRun> runs = LineRuns( line );
int x = 0;
const SimpleTextRun* run = runs.begin();
while ( run != runs.end() && run->textStart + run->textCount <= cp )
{
x += RunWidth( run );
run++;
}
Assert( run != runs.end() );
return x + RunCPtoX( *run, cp, trailingEdge );
}
int SimpleTextBlock::RunCPtoX( const SimpleTextRun& run, size_t cp, bool trailingEdge ) const
{
Assert( cp >= run.textStart );
Assert( cp < run.textStart + run.textCount );
if ( trailingEdge )
return m_data->xOffsets[cp];
if ( cp == run.textStart )
return 0;
return m_data->xOffsets[cp - 1];
}
size_t SimpleTextBlock::XtoCP( size_t line, LONG* x ) const
{
ArrayOf<const SimpleTextRun> runs = LineRuns( line );
int xStart = 0;
const SimpleTextRun* run = runs.begin();
while ( run != runs.end() && xStart + RunWidth( run ) <= *x )
{
xStart += RunWidth( run );
run++;
}
if ( run == runs.end() )
{
*x = LineWidth( line );
return TextEnd( line );
}
size_t cp = run->textStart;
int xOffset = 0;
while ( cp < run->textStart + run->textCount && xStart + xOffset + ( m_data->xOffsets[cp] - xOffset ) / 2 < *x )
{
xOffset = m_data->xOffsets[cp];
++cp;
}
*x = xStart + xOffset;
return cp;
}
<|endoftext|> |
<commit_before>#ifndef VIENNAGRID_STORAGE_RANGE_HPP
#define VIENNAGRID_STORAGE_RANGE_HPP
#include "viennagrid/forwards.hpp"
namespace viennagrid
{
namespace storage
{
template<typename container_type>
class container_range_wrapper
{
friend class container_range_wrapper<const container_type>;
public:
container_range_wrapper(container_type & _container) : container(_container) {}
typedef typename container_type::size_type size_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::pointer pointer;
typedef typename container_type::const_pointer const_pointer;
typedef typename container_type::iterator iterator;
typedef typename container_type::const_iterator const_iterator;
typedef typename container_type::reverse_iterator reverse_iterator;
typedef typename container_type::const_reverse_iterator const_reverse_iterator;
iterator begin() { return container.begin(); }
const_iterator begin() const { return container.begin(); }
iterator end() { return container.end(); }
const_iterator end() const { return container.end(); }
reverse_iterator rbegin() { return container.rbegin(); }
const_reverse_iterator rbegin() const { return container.rbegin(); }
reverse_iterator rend() { return container.rend(); }
const_reverse_iterator rend() const { return container.rend(); }
reference front() { return container.front(); }
const_reference front() const { return container.front(); }
reference back() { return container.back(); }
const_reference back() const { return container.back(); }
reference operator[] (size_type index) { return container[index]; }
const_reference operator[] (size_type index) const { return container[index]; }
bool empty() const { return container.empty(); }
size_type size() const { return container.size(); }
typedef typename container_type::hook_type hook_type;
typedef typename container_type::hook_iterator hook_iterator;
hook_iterator hook_begin() { return container.hook_begin(); }
hook_iterator hook_end() { return container.hook_end(); }
typedef typename container_type::const_hook_type const_hook_type;
typedef typename container_type::const_hook_iterator const_hook_iterator;
const_hook_iterator hook_begin() const { return container.hook_begin(); }
const_hook_iterator hook_end() const { return container.hook_end(); }
hook_type hook_at(std::size_t pos)
{
return *viennagrid::advance(hook_begin(), pos);
// hook_iterator it = hook_begin();
// std::advance( it, pos );
// return *it;
}
const_hook_type hook_at(std::size_t pos) const
{
return *viennagrid::advance(hook_begin(), pos);
// const_hook_iterator it = hook_begin();
// std::advance( it, pos );
// return *it;
}
private:
container_type & container;
};
template<typename container_type>
class container_range_wrapper<const container_type>
{
public:
container_range_wrapper(const container_type & _container) : container(_container) {}
container_range_wrapper(const container_range_wrapper<container_type> & rhs) : container(rhs.container) {}
typedef typename container_type::size_type size_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::const_reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::const_pointer pointer;
typedef typename container_type::const_pointer const_pointer;
typedef typename container_type::const_iterator iterator;
typedef typename container_type::const_iterator const_iterator;
typedef typename container_type::const_reverse_iterator reverse_iterator;
typedef typename container_type::const_reverse_iterator const_reverse_iterator;
iterator begin() { return container.begin(); }
const_iterator begin() const { return container.begin(); }
iterator end() { return container.end(); }
const_iterator end() const { return container.end(); }
reverse_iterator rbegin() { return container.rbegin(); }
const_reverse_iterator rbegin() const { return container.rbegin(); }
reverse_iterator rend() { return container.rend(); }
const_reverse_iterator rend() const { return container.rend(); }
reference front() { return container.front(); }
const_reference front() const { return container.front(); }
reference back() { return container.back(); }
const_reference back() const { return container.back(); }
reference operator[] (size_type index) { return container[index]; }
const_reference operator[] (size_type index) const { return container[index]; }
bool empty() const { return container.empty(); }
size_type size() const { return container.size(); }
typedef typename container_type::const_hook_type hook_type;
typedef typename container_type::const_hook_iterator hook_iterator;
hook_iterator hook_begin() { return container.hook_begin(); }
hook_iterator hook_end() { return container.hook_end(); }
typedef typename container_type::const_hook_type const_hook_type;
typedef typename container_type::const_hook_iterator const_hook_iterator;
const_hook_iterator hook_begin() const { return container.hook_begin(); }
const_hook_iterator hook_end() const { return container.hook_end(); }
hook_type hook_at(std::size_t pos)
{
return *viennagrid::advance(hook_begin(), pos);
// hook_iterator it = hook_begin();
// std::advance( it, pos );
// return *it;
}
const_hook_type hook_at(std::size_t pos) const
{
return *viennagrid::advance(hook_begin(), pos);
// const_hook_iterator it = hook_begin();
// std::advance( it, pos );
// return *it;
}
private:
const container_type & container;
};
template<typename iterator_type>
class forward_iterator_range
{
public:
forward_iterator_range(iterator_type _first, iterator_type _last) : first(_first), last(_last) {}
typedef typename iterator_type::T value_type;
typedef typename iterator_type::Reference reference;
typedef const typename iterator_type::Reference const_reference;
typedef typename iterator_type::Pointer pointer;
typedef const typename iterator_type::Pointer const_pointer;
typedef iterator_type iterator;
typedef const iterator_type const_iterator;
iterator begin() { return first; }
const_iterator begin() const { return first; }
iterator end() { return last; }
const_iterator end() const { return last; }
reference front() { return *first; }
const_reference front() const { return *first; }
reference back() { iterator_type tmp = last; return *(--tmp); }
const_reference back() const { iterator_type tmp = last; return *(--tmp); }
bool empty() const { return first == last; }
private:
iterator_type first;
iterator_type last;
};
}
}
#endif
<commit_msg>range uses pointer instead of reference<commit_after>#ifndef VIENNAGRID_STORAGE_RANGE_HPP
#define VIENNAGRID_STORAGE_RANGE_HPP
#include "viennagrid/forwards.hpp"
namespace viennagrid
{
namespace storage
{
template<typename container_type>
class container_range_wrapper
{
friend class container_range_wrapper<const container_type>;
public:
container_range_wrapper(container_type & _container) : container(&_container) {}
typedef typename container_type::size_type size_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::pointer pointer;
typedef typename container_type::const_pointer const_pointer;
typedef typename container_type::iterator iterator;
typedef typename container_type::const_iterator const_iterator;
typedef typename container_type::reverse_iterator reverse_iterator;
typedef typename container_type::const_reverse_iterator const_reverse_iterator;
iterator begin() { return container->begin(); }
const_iterator begin() const { return container->begin(); }
iterator end() { return container->end(); }
const_iterator end() const { return container->end(); }
reverse_iterator rbegin() { return container->rbegin(); }
const_reverse_iterator rbegin() const { return container->rbegin(); }
reverse_iterator rend() { return container->rend(); }
const_reverse_iterator rend() const { return container->rend(); }
reference front() { return container->front(); }
const_reference front() const { return container->front(); }
reference back() { return container->back(); }
const_reference back() const { return container->back(); }
reference operator[] (size_type index) { return (*container)[index]; }
const_reference operator[] (size_type index) const { return (*container)[index]; }
bool empty() const { return container->empty(); }
size_type size() const { return container->size(); }
typedef typename container_type::hook_type hook_type;
typedef typename container_type::hook_iterator hook_iterator;
hook_iterator hook_begin() { return container->hook_begin(); }
hook_iterator hook_end() { return container->hook_end(); }
typedef typename container_type::const_hook_type const_hook_type;
typedef typename container_type::const_hook_iterator const_hook_iterator;
const_hook_iterator hook_begin() const { return container->hook_begin(); }
const_hook_iterator hook_end() const { return container->hook_end(); }
hook_type hook_at(std::size_t pos)
{
return *viennagrid::advance(hook_begin(), pos);
// hook_iterator it = hook_begin();
// std::advance( it, pos );
// return *it;
}
const_hook_type hook_at(std::size_t pos) const
{
return *viennagrid::advance(hook_begin(), pos);
// const_hook_iterator it = hook_begin();
// std::advance( it, pos );
// return *it;
}
private:
container_type * container;
};
template<typename container_type>
class container_range_wrapper<const container_type>
{
public:
container_range_wrapper(const container_type & _container) : container(&_container) {}
container_range_wrapper(const container_range_wrapper<container_type> & rhs) : container(rhs.container) {}
typedef typename container_type::size_type size_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::const_reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::const_pointer pointer;
typedef typename container_type::const_pointer const_pointer;
typedef typename container_type::const_iterator iterator;
typedef typename container_type::const_iterator const_iterator;
typedef typename container_type::const_reverse_iterator reverse_iterator;
typedef typename container_type::const_reverse_iterator const_reverse_iterator;
iterator begin() { return container->begin(); }
const_iterator begin() const { return container->begin(); }
iterator end() { return container->end(); }
const_iterator end() const { return container->end(); }
reverse_iterator rbegin() { return container->rbegin(); }
const_reverse_iterator rbegin() const { return container->rbegin(); }
reverse_iterator rend() { return container->rend(); }
const_reverse_iterator rend() const { return container->rend(); }
reference front() { return container->front(); }
const_reference front() const { return container->front(); }
reference back() { return container->back(); }
const_reference back() const { return container->back(); }
reference operator[] (size_type index) { return (*container)[index]; }
const_reference operator[] (size_type index) const { return (*container)[index]; }
bool empty() const { return container->empty(); }
size_type size() const { return container->size(); }
typedef typename container_type::const_hook_type hook_type;
typedef typename container_type::const_hook_iterator hook_iterator;
hook_iterator hook_begin() { return container->hook_begin(); }
hook_iterator hook_end() { return container->hook_end(); }
typedef typename container_type::const_hook_type const_hook_type;
typedef typename container_type::const_hook_iterator const_hook_iterator;
const_hook_iterator hook_begin() const { return container->hook_begin(); }
const_hook_iterator hook_end() const { return container->hook_end(); }
hook_type hook_at(std::size_t pos)
{
return *viennagrid::advance(hook_begin(), pos);
// hook_iterator it = hook_begin();
// std::advance( it, pos );
// return *it;
}
const_hook_type hook_at(std::size_t pos) const
{
return *viennagrid::advance(hook_begin(), pos);
// const_hook_iterator it = hook_begin();
// std::advance( it, pos );
// return *it;
}
private:
const container_type * container;
};
template<typename iterator_type>
class forward_iterator_range
{
public:
forward_iterator_range(iterator_type _first, iterator_type _last) : first(_first), last(_last) {}
typedef typename iterator_type::T value_type;
typedef typename iterator_type::Reference reference;
typedef const typename iterator_type::Reference const_reference;
typedef typename iterator_type::Pointer pointer;
typedef const typename iterator_type::Pointer const_pointer;
typedef iterator_type iterator;
typedef const iterator_type const_iterator;
iterator begin() { return first; }
const_iterator begin() const { return first; }
iterator end() { return last; }
const_iterator end() const { return last; }
reference front() { return *first; }
const_reference front() const { return *first; }
reference back() { iterator_type tmp = last; return *(--tmp); }
const_reference back() const { iterator_type tmp = last; return *(--tmp); }
bool empty() const { return first == last; }
private:
iterator_type first;
iterator_type last;
};
}
}
#endif
<|endoftext|> |
<commit_before>#include <sys/types.h>
#include <string>
class MultipartParser {
public:
typedef void (*Callback)(const char *buffer, size_t start, size_t end, void *userData);
private:
static const char CR = 13;
static const char LF = 10;
static const char SPACE = 32;
static const char HYPHEN = 45;
static const char COLON = 58;
static const char A = 97;
static const char Z = 122;
static const size_t UNMARKED = (size_t) -1;
enum State {
ERROR,
START,
START_BOUNDARY,
HEADER_FIELD_START,
HEADER_FIELD,
HEADER_VALUE_START,
HEADER_VALUE,
HEADER_VALUE_ALMOST_DONE,
HEADERS_ALMOST_DONE,
PART_DATA_START,
PART_DATA,
PART_END,
END
};
enum Flags {
PART_BOUNDARY = 1,
LAST_BOUNDARY = 2
};
std::string boundary;
char *lookbehind;
State state;
int flags;
size_t index;
size_t headerFieldMark;
size_t headerValueMark;
size_t partDataMark;
void callback(Callback cb, const char *buffer = NULL, size_t start = UNMARKED, size_t end = UNMARKED) {
if (start != UNMARKED && start == end) {
return;
}
if (cb != NULL) {
cb(buffer, start, end, userData);
}
}
void dataCallback(Callback cb, size_t &mark, const char *buffer, size_t i, size_t bufferLen, bool clear) {
if (mark == UNMARKED) {
return;
}
if (!clear) {
callback(cb, buffer, mark, bufferLen);
} else {
callback(cb, buffer, mark, i);
mark = UNMARKED;
}
}
char lower(char c) const {
return c | 0x20;
}
bool isBoundaryChar(char c) const {
const char *current = boundary.c_str();
const char *end = current + boundary.size();
while (current < end) {
if (*current == c) {
return true;
}
current++;
}
return false;
}
public:
Callback onPartBegin;
Callback onHeaderField;
Callback onHeaderValue;
Callback onPartData;
Callback onPartEnd;
Callback onEnd;
void *userData;
MultipartParser() {
lookbehind = NULL;
reset();
}
MultipartParser(const std::string &boundary) {
lookbehind = NULL;
setBoundary(boundary);
}
~MultipartParser() {
delete[] lookbehind;
}
void reset() {
delete[] lookbehind;
state = ERROR;
lookbehind = NULL;
flags = 0;
index = 0;
headerFieldMark = UNMARKED;
headerValueMark = UNMARKED;
partDataMark = UNMARKED;
onPartBegin = NULL;
onHeaderField = NULL;
onHeaderValue = NULL;
onPartData = NULL;
onPartEnd = NULL;
onEnd = NULL;
userData = NULL;
}
void setBoundary(const std::string &boundary) {
reset();
this->boundary = "\r\n--" + boundary;
lookbehind = new char[this->boundary.size() + 8];
state = START;
}
size_t feed(const char *buffer, size_t len) {
State state = this->state;
int flags = this->flags;
size_t prevIndex = this->index;
size_t index = this->index;
size_t boundarySize = boundary.size();
size_t boundaryEnd = boundarySize - 1;
size_t i;
char c, cl;
for (i = 0; i < len; i++) {
c = buffer[i];
switch (state) {
case ERROR:
return i;
case START:
index = 0;
state = START_BOUNDARY;
case START_BOUNDARY:
if (index == boundarySize - 2) {
if (c != CR) {
return i;
}
index++;
break;
} else if (index - 1 == boundarySize - 2) {
if (c != LF) {
return i;
}
index = 0;
callback(onPartBegin);
state = HEADER_FIELD_START;
break;
}
if (c != boundary[index + 2]) {
return i;
}
index++;
break;
case HEADER_FIELD_START:
state = HEADER_FIELD;
headerFieldMark = i;
case HEADER_FIELD:
if (c == CR) {
headerFieldMark = UNMARKED;
state = HEADERS_ALMOST_DONE;
break;
}
if (c == HYPHEN) {
break;
}
if (c == COLON) {
dataCallback(onHeaderField, headerFieldMark, buffer, i, len, true);
state = HEADER_VALUE_START;
break;
}
cl = lower(c);
if (cl < A || cl > Z) {
return i;
}
break;
case HEADER_VALUE_START:
if (c == SPACE) {
break;
}
headerValueMark = i;
state = HEADER_VALUE;
case HEADER_VALUE:
if (c == CR) {
dataCallback(onHeaderValue, headerValueMark, buffer, i, len, true);
state = HEADER_VALUE_ALMOST_DONE;
}
break;
case HEADER_VALUE_ALMOST_DONE:
if (c != LF) {
return i;
}
state = PART_DATA_START;
break;
case PART_DATA_START:
state = PART_DATA;
partDataMark = i;
case PART_DATA:
prevIndex = index;
if (index == 0) {
// boyer-moore derrived algorithm to safely skip non-boundary data
while (i + boundary.size() <= len) {
if (isBoundaryChar(buffer[i + boundaryEnd])) {
break;
}
i += boundary.size();
}
c = buffer[i];
}
if (index < boundary.size()) {
if (boundary[index] == c) {
if (index == 0) {
dataCallback(onPartData, partDataMark, buffer, i, len, true);
}
index++;
} else {
index = 0;
}
} else if (index == boundary.size()) {
index++;
if (c == CR) {
// CR = part boundary
flags |= PART_BOUNDARY;
} else if (c == HYPHEN) {
// HYPHEN = end boundary
flags |= LAST_BOUNDARY;
} else {
index = 0;
}
} else if (index - 1 == boundary.size()) {
if (flags & PART_BOUNDARY) {
index = 0;
if (c == LF) {
// unset the PART_BOUNDARY flag
flags &= ~PART_BOUNDARY;
callback(onPartEnd);
callback(onPartBegin);
state = HEADER_FIELD_START;
break;
}
} else if (flags & LAST_BOUNDARY) {
if (c == HYPHEN) {
index++;
} else {
index = 0;
}
} else {
index = 0;
}
} else if (index - 2 == boundary.size()) {
if (c == CR) {
index++;
} else {
index = 0;
}
} else if (index - boundary.size() == 3) {
index = 0;
if (c == LF) {
callback(onPartEnd);
callback(onEnd);
state = END;
break;
}
}
if (index > 0) {
// when matching a possible boundary, keep a lookbehind reference
// in case it turns out to be a false lead
lookbehind[index - 1] = c;
} else if (prevIndex > 0) {
// if our boundary turned out to be rubbish, the captured lookbehind
// belongs to partData
callback(onPartData, lookbehind, 0, prevIndex);
prevIndex = 0;
partDataMark = i;
}
break;
default:
return i;
}
}
dataCallback(onHeaderField, headerFieldMark, buffer, i, len, false);
dataCallback(onHeaderValue, headerValueMark, buffer, i, len, false);
dataCallback(onPartData, partDataMark, buffer, i, len, false);
this->index = index;
this->state = state;
this->flags = flags;
return len;
}
};
#include <stdio.h>
using namespace std;
static void
onPartBegin(const char *buffer, size_t start, size_t end, void *userData) {
printf("onPartBegin\n");
}
static void
onHeaderField(const char *buffer, size_t start, size_t end, void *userData) {
printf("onHeaderField: (%s)\n", string(buffer + start, end - start).c_str());
}
static void
onHeaderValue(const char *buffer, size_t start, size_t end, void *userData) {
printf("onHeaderValue: (%s)\n", string(buffer + start, end - start).c_str());
}
static void
onPartData(const char *buffer, size_t start, size_t end, void *userData) {
printf("onPartData: (%s)\n", string(buffer + start, end - start).c_str());
}
static void
onPartEnd(const char *buffer, size_t start, size_t end, void *userData) {
printf("onPartEnd\n");
}
static void
onEnd(const char *buffer, size_t start, size_t end, void *userData) {
printf("onEnd\n");
}
int
main() {
MultipartParser parser("abcd");
parser.onPartBegin = onPartBegin;
parser.onHeaderField = onHeaderField;
parser.onHeaderValue = onHeaderValue;
parser.onPartData = onPartData;
parser.onPartEnd = onPartEnd;
parser.onEnd = onEnd;
while (!feof(stdin)) {
char buf[1024 * 16];
size_t len = fread(buf, 1, sizeof(buf), stdin);
size_t fed = 0;
do {
size_t ret = parser.feed(buf + fed, len - fed);
fed += ret;
printf("accepted %d bytes\n", (int) ret);
} while (fed < len);
}
return 0;
}
<commit_msg>Add some error handling.<commit_after>#include <sys/types.h>
#include <string>
class MultipartParser {
public:
typedef void (*Callback)(const char *buffer, size_t start, size_t end, void *userData);
private:
static const char CR = 13;
static const char LF = 10;
static const char SPACE = 32;
static const char HYPHEN = 45;
static const char COLON = 58;
static const char A = 97;
static const char Z = 122;
static const size_t UNMARKED = (size_t) -1;
enum State {
ERROR,
START,
START_BOUNDARY,
HEADER_FIELD_START,
HEADER_FIELD,
HEADER_VALUE_START,
HEADER_VALUE,
HEADER_VALUE_ALMOST_DONE,
HEADERS_ALMOST_DONE,
PART_DATA_START,
PART_DATA,
PART_END,
END
};
enum Flags {
PART_BOUNDARY = 1,
LAST_BOUNDARY = 2
};
std::string boundary;
char *lookbehind;
State state;
int flags;
size_t index;
size_t headerFieldMark;
size_t headerValueMark;
size_t partDataMark;
void callback(Callback cb, const char *buffer = NULL, size_t start = UNMARKED, size_t end = UNMARKED) {
if (start != UNMARKED && start == end) {
return;
}
if (cb != NULL) {
cb(buffer, start, end, userData);
}
}
void dataCallback(Callback cb, size_t &mark, const char *buffer, size_t i, size_t bufferLen, bool clear) {
if (mark == UNMARKED) {
return;
}
if (!clear) {
callback(cb, buffer, mark, bufferLen);
} else {
callback(cb, buffer, mark, i);
mark = UNMARKED;
}
}
char lower(char c) const {
return c | 0x20;
}
bool isBoundaryChar(char c) const {
const char *current = boundary.c_str();
const char *end = current + boundary.size();
while (current < end) {
if (*current == c) {
return true;
}
current++;
}
return false;
}
void setError(const char *message) {
state = ERROR;
}
public:
Callback onPartBegin;
Callback onHeaderField;
Callback onHeaderValue;
Callback onPartData;
Callback onPartEnd;
Callback onEnd;
void *userData;
MultipartParser() {
lookbehind = NULL;
reset();
}
MultipartParser(const std::string &boundary) {
lookbehind = NULL;
setBoundary(boundary);
}
~MultipartParser() {
delete[] lookbehind;
}
void reset() {
delete[] lookbehind;
state = ERROR;
lookbehind = NULL;
flags = 0;
index = 0;
headerFieldMark = UNMARKED;
headerValueMark = UNMARKED;
partDataMark = UNMARKED;
onPartBegin = NULL;
onHeaderField = NULL;
onHeaderValue = NULL;
onPartData = NULL;
onPartEnd = NULL;
onEnd = NULL;
userData = NULL;
}
void setBoundary(const std::string &boundary) {
reset();
this->boundary = "\r\n--" + boundary;
lookbehind = new char[this->boundary.size() + 8];
state = START;
}
size_t feed(const char *buffer, size_t len) {
State state = this->state;
int flags = this->flags;
size_t prevIndex = this->index;
size_t index = this->index;
size_t boundarySize = boundary.size();
size_t boundaryEnd = boundarySize - 1;
size_t i;
char c, cl;
for (i = 0; i < len; i++) {
c = buffer[i];
switch (state) {
case ERROR:
return i;
case START:
index = 0;
state = START_BOUNDARY;
case START_BOUNDARY:
if (index == boundarySize - 2) {
if (c != CR) {
return i;
}
index++;
break;
} else if (index - 1 == boundarySize - 2) {
if (c != LF) {
return i;
}
index = 0;
callback(onPartBegin);
state = HEADER_FIELD_START;
break;
}
if (c != boundary[index + 2]) {
return i;
}
index++;
break;
case HEADER_FIELD_START:
state = HEADER_FIELD;
headerFieldMark = i;
case HEADER_FIELD:
if (c == CR) {
headerFieldMark = UNMARKED;
state = HEADERS_ALMOST_DONE;
break;
}
if (c == HYPHEN) {
break;
}
if (c == COLON) {
dataCallback(onHeaderField, headerFieldMark, buffer, i, len, true);
state = HEADER_VALUE_START;
break;
}
cl = lower(c);
if (cl < A || cl > Z) {
setError("Malformed header name.");
return i;
}
break;
case HEADER_VALUE_START:
if (c == SPACE) {
break;
}
headerValueMark = i;
state = HEADER_VALUE;
case HEADER_VALUE:
if (c == CR) {
dataCallback(onHeaderValue, headerValueMark, buffer, i, len, true);
state = HEADER_VALUE_ALMOST_DONE;
}
break;
case HEADER_VALUE_ALMOST_DONE:
if (c != LF) {
setError("Malformed header value: LF expected after CR");
return i;
}
state = PART_DATA_START;
break;
case PART_DATA_START:
state = PART_DATA;
partDataMark = i;
case PART_DATA:
prevIndex = index;
if (index == 0) {
// boyer-moore derrived algorithm to safely skip non-boundary data
while (i + boundary.size() <= len) {
if (isBoundaryChar(buffer[i + boundaryEnd])) {
break;
}
i += boundary.size();
}
c = buffer[i];
}
if (index < boundary.size()) {
if (boundary[index] == c) {
if (index == 0) {
dataCallback(onPartData, partDataMark, buffer, i, len, true);
}
index++;
} else {
index = 0;
}
} else if (index == boundary.size()) {
index++;
if (c == CR) {
// CR = part boundary
flags |= PART_BOUNDARY;
} else if (c == HYPHEN) {
// HYPHEN = end boundary
flags |= LAST_BOUNDARY;
} else {
index = 0;
}
} else if (index - 1 == boundary.size()) {
if (flags & PART_BOUNDARY) {
index = 0;
if (c == LF) {
// unset the PART_BOUNDARY flag
flags &= ~PART_BOUNDARY;
callback(onPartEnd);
callback(onPartBegin);
state = HEADER_FIELD_START;
break;
}
} else if (flags & LAST_BOUNDARY) {
if (c == HYPHEN) {
index++;
} else {
index = 0;
}
} else {
index = 0;
}
} else if (index - 2 == boundary.size()) {
if (c == CR) {
index++;
} else {
index = 0;
}
} else if (index - boundary.size() == 3) {
index = 0;
if (c == LF) {
callback(onPartEnd);
callback(onEnd);
state = END;
break;
}
}
if (index > 0) {
// when matching a possible boundary, keep a lookbehind reference
// in case it turns out to be a false lead
lookbehind[index - 1] = c;
} else if (prevIndex > 0) {
// if our boundary turned out to be rubbish, the captured lookbehind
// belongs to partData
callback(onPartData, lookbehind, 0, prevIndex);
prevIndex = 0;
partDataMark = i;
}
break;
default:
return i;
}
}
dataCallback(onHeaderField, headerFieldMark, buffer, i, len, false);
dataCallback(onHeaderValue, headerValueMark, buffer, i, len, false);
dataCallback(onPartData, partDataMark, buffer, i, len, false);
this->index = index;
this->state = state;
this->flags = flags;
return len;
}
bool succeeded() const {
return state == END;
}
bool hasError() const {
return state == ERROR;
}
bool stopped() const {
return state == ERROR || state == END;
}
};
#include <stdio.h>
using namespace std;
static void
onPartBegin(const char *buffer, size_t start, size_t end, void *userData) {
printf("onPartBegin\n");
}
static void
onHeaderField(const char *buffer, size_t start, size_t end, void *userData) {
printf("onHeaderField: (%s)\n", string(buffer + start, end - start).c_str());
}
static void
onHeaderValue(const char *buffer, size_t start, size_t end, void *userData) {
printf("onHeaderValue: (%s)\n", string(buffer + start, end - start).c_str());
}
static void
onPartData(const char *buffer, size_t start, size_t end, void *userData) {
printf("onPartData: (%s)\n", string(buffer + start, end - start).c_str());
}
static void
onPartEnd(const char *buffer, size_t start, size_t end, void *userData) {
printf("onPartEnd\n");
}
static void
onEnd(const char *buffer, size_t start, size_t end, void *userData) {
printf("onEnd\n");
}
int
main() {
MultipartParser parser("abcd");
parser.onPartBegin = onPartBegin;
parser.onHeaderField = onHeaderField;
parser.onHeaderValue = onHeaderValue;
parser.onPartData = onPartData;
parser.onPartEnd = onPartEnd;
parser.onEnd = onEnd;
while (!feof(stdin)) {
char buf[1024 * 16];
size_t len = fread(buf, 1, sizeof(buf), stdin);
size_t fed = 0;
do {
size_t ret = parser.feed(buf + fed, len - fed);
fed += ret;
printf("accepted %d bytes\n", (int) ret);
} while (fed < len && !parser.stopped());
}
return 0;
}
<|endoftext|> |
<commit_before>#ifndef GP_TRAITS_NODE_TRAITS
#define GP_TRAITS_NODE_TRAITS
#include <memory>
#include <type_traits>
#include <gp/node/node_interface.hpp>
namespace gp::traits {
template <typename node>
struct node_traits;
template <typename node>
struct is_node_type: public std::false_type{};
template <typename node>
constexpr bool is_node_type_v = is_node_type<node>::value;
template <typename node_ptr>
struct is_node_ptr_type: public std::false_type{};
template <typename node_ptr>
constexpr bool is_node_ptr_type_v = is_node_ptr_type<node_ptr>::value;
template <>
struct node_traits<node::NodeInterface> {
private:
using adapt_type = node::NodeInterface;
public://concepts
using node_instance_type = adapt_type::node_instance_type;
//methods for children
static std::size_t get_child_num(const adapt_type& node_) {return node_.getChildNum();}
static bool has_child(const adapt_type& node_, std::size_t n) {return node_.hasChild(n);}
static adapt_type& get_child(adapt_type& node_, std::size_t n) {return node_.getChildNode(n);}
static const adapt_type& get_child(const adapt_type& node_, std::size_t n) {return node_.getChildNode(n);}
static void set_child(adapt_type& node_, std::size_t n, node_instance_type child) {node_.setChild(n, std::move(child));}
//methods for parent
static bool has_parent(const adapt_type& node_) {return node_.hasParent();}
static adapt_type& get_parent(adapt_type& node_) {return node_.getParent();}
static const adapt_type& get_parent(const adapt_type& node_) {return node_.getParent();}
};
template <>
struct is_node_type<node::NodeInterface>: public std::true_type{};
template <>
struct is_node_ptr_type<node::NodeInterface::node_instance_type>: public std::true_type{};
template <>
struct is_node_ptr_type<node::NodeInterface*>: public std::true_type{};
template <typename typed_node>
struct typed_node_traits;
template <typename typed_node>
struct is_typed_node_type: public std::false_type{};
template <typename typed_node>
constexpr bool is_typed_node_type_v = is_typed_node_type<typed_node>::value;
template <typename typed_node_ptr>
struct is_typed_node_ptr_type: public std::false_type{};
template <typename typed_node_ptr>
constexpr bool is_typed_node_ptr_type_v = is_typed_node_ptr_type<typed_node_ptr>::value;
template <>
struct typed_node_traits<node::NodeInterface>: private node_traits<node::NodeInterface> {
private:
using adapt_type = node::NodeInterface;
public://concepts
using node_instance_type = node_traits<adapt_type>::node_instance_type;
using node_traits<adapt_type>::get_child_num;
using node_traits<adapt_type>::has_child;
using node_traits<adapt_type>::get_child;
using node_traits<adapt_type>::set_child;
using node_traits<adapt_type>::has_parent;
using node_traits<adapt_type>::get_parent;
//type of type information
using type_info = typename adapt_type::type_info;
//methods for type information
static const type_info& get_return_type(const adapt_type& node_) {return node_.getReturnType();}
static const type_info& get_child_return_type(const adapt_type& node_, std::size_t n) {return node_.getChildReturnType(n);}
};
template <>
struct is_typed_node_type<node::NodeInterface>: public std::true_type{};
template <>
struct is_typed_node_ptr_type<node::NodeInterface::node_instance_type>: public std::true_type{};
template <>
struct is_typed_node_ptr_type<node::NodeInterface*>: public std::true_type{};
template <typename output_node>
struct output_node_traits;
template <typename output_node>
struct is_output_node_type: public std::false_type{};
template <typename output_node>
constexpr bool is_output_node_type_v = is_output_node_type<output_node>::value;
template <typename output_node_ptr>
struct is_output_node_ptr_type: public std::false_type{};
template <typename output_node_ptr>
constexpr bool is_output_node_ptr_type_v = is_output_node_ptr_type<output_node_ptr>::value;
template <>
struct output_node_traits<node::NodeInterface>: private node_traits<node::NodeInterface> {
private:
using adapt_type = node::NodeInterface;
public:
using node_traits<adapt_type>::has_child;
using node_traits<adapt_type>::get_child;
using node_traits<adapt_type>::get_child_num;
using node_traits<adapt_type>::has_parent;
using node_traits<adapt_type>::get_parent;
//methods for output
static std::string get_node_name(const adapt_type& node_) {return node_.getNodeName();}
};
template <>
struct is_output_node_type<node::NodeInterface>: public std::true_type{};
template <>
struct is_output_node_ptr_type<node::NodeInterface::node_instance_type>: public std::true_type{};
template <>
struct is_output_node_ptr_type<node::NodeInterface*>: public std::true_type{};
template <typename node>
struct input_node_traits;
template <typename input_node>
struct is_input_node_type: public std::false_type{};
template <typename input_node>
constexpr bool is_input_node_type_v = is_input_node_type<input_node>::value;
template <typename input_node_ptr>
struct is_input_node_ptr_type: public std::false_type{};
template <typename input_node_ptr>
constexpr bool is_input_node_ptr_type_v = is_input_node_ptr_type<input_node_ptr>::value;
template <>
struct input_node_traits<node::NodeInterface>: private typed_node_traits<node::NodeInterface> {
private:
using adapt_type = node::NodeInterface;
public:
using node_instance_type = typename typed_node_traits<adapt_type>::node_instance_type;
using type_info = typename typed_node_traits<adapt_type>::type_info;
using tree_property = tree::TreeProperty;
using typed_node_traits<adapt_type>::get_child_num;
using typed_node_traits<adapt_type>::has_child;
using typed_node_traits<adapt_type>::get_child;
using typed_node_traits<adapt_type>::set_child;
using typed_node_traits<adapt_type>::has_parent;
using typed_node_traits<adapt_type>::get_parent;
using typed_node_traits<adapt_type>::get_return_type;
using typed_node_traits<adapt_type>::get_child_return_type;
static bool is_valid_child(const adapt_type& node, std::size_t n, const adapt_type& child, const tree_property& treeProperty) {
if(!node.getChildReturnType(n).isAnyType() && node.getChildReturnType(n) != child.getReturnType())return false;
if(child.getNodeType() == node::NodeType::Argument) {
auto argument_idx = std::any_cast<adapt_type::variable_index_type>(child.getNodePropertyByAny());
if(std::size(treeProperty.argumentTypes) <= argument_idx) return false;
return treeProperty.argumentTypes[argument_idx]->removeReferenceType().removeLeftHandValueType() == child.getReturnType().removeReferenceType().removeLeftHandValueType();
} else if(child.getNodeType() == node::NodeType::LocalVariable){
auto localVariableIdx = std::any_cast<adapt_type::variable_index_type>(child.getNodePropertyByAny());
if(std::size(treeProperty.localVariableTypes) <= localVariableIdx)return false;
return treeProperty.localVariableTypes[localVariableIdx]->removeReferenceType().removeLeftHandValueType() == child.getReturnType().removeReferenceType().removeLeftHandValueType();
} else {
return true;
}
}
};
template <>
struct is_input_node_type<node::NodeInterface>: public std::true_type{};
template <>
struct is_input_node_ptr_type<node::NodeInterface::node_instance_type>: public std::true_type{};
template <>
struct is_input_node_ptr_type<node::NodeInterface*>: public std::true_type{};
}
#endif
<commit_msg>implement auto detection of adaptable node ptr type in compile time<commit_after>#ifndef GP_TRAITS_NODE_TRAITS
#define GP_TRAITS_NODE_TRAITS
#include <memory>
#include <type_traits>
#include <gp/node/node_interface.hpp>
namespace gp::traits {
namespace detail {
template <template <typename> class IsTrait, typename Enable, typename T>
struct is_adaptable_ptr_type_impl: public std::false_type{};
template <template <typename> class IsTrait, typename T>
struct is_adaptable_ptr_type_impl<
IsTrait,
std::void_t<
decltype(*std::declval<T>()),
std::enable_if_t<IsTrait<std::decay_t<decltype(*std::declval<T>())>>::value>
>,
T
>: public std::true_type {};
template <template <typename> class IsTrait, typename T>
using is_adaptable_ptr_type = is_adaptable_ptr_type_impl<IsTrait, void, T>;
}
template <typename node>
struct node_traits;
template <typename node>
struct is_node_type: public std::false_type{};
template <typename node>
constexpr bool is_node_type_v = is_node_type<node>::value;
template <typename node_ptr>
using is_node_ptr_type = detail::is_adaptable_ptr_type<is_node_type, node_ptr>;
template <typename node_ptr>
constexpr bool is_node_ptr_type_v = is_node_ptr_type<node_ptr>::value;
template <>
struct node_traits<node::NodeInterface> {
private:
using adapt_type = node::NodeInterface;
public://concepts
using node_instance_type = adapt_type::node_instance_type;
//methods for children
static std::size_t get_child_num(const adapt_type& node_) {return node_.getChildNum();}
static bool has_child(const adapt_type& node_, std::size_t n) {return node_.hasChild(n);}
static adapt_type& get_child(adapt_type& node_, std::size_t n) {return node_.getChildNode(n);}
static const adapt_type& get_child(const adapt_type& node_, std::size_t n) {return node_.getChildNode(n);}
static void set_child(adapt_type& node_, std::size_t n, node_instance_type child) {node_.setChild(n, std::move(child));}
//methods for parent
static bool has_parent(const adapt_type& node_) {return node_.hasParent();}
static adapt_type& get_parent(adapt_type& node_) {return node_.getParent();}
static const adapt_type& get_parent(const adapt_type& node_) {return node_.getParent();}
};
template <>
struct is_node_type<node::NodeInterface>: public std::true_type{};
template <typename typed_node>
struct typed_node_traits;
template <typename typed_node>
struct is_typed_node_type: public std::false_type{};
template <typename typed_node>
constexpr bool is_typed_node_type_v = is_typed_node_type<typed_node>::value;
template <typename typed_node_ptr>
using is_typed_node_ptr_type = detail::is_adaptable_ptr_type<is_typed_node_type, typed_node_ptr>;
template <typename typed_node_ptr>
constexpr bool is_typed_node_ptr_type_v = is_typed_node_ptr_type<typed_node_ptr>::value;
template <>
struct typed_node_traits<node::NodeInterface>: private node_traits<node::NodeInterface> {
private:
using adapt_type = node::NodeInterface;
public://concepts
using node_instance_type = node_traits<adapt_type>::node_instance_type;
using node_traits<adapt_type>::get_child_num;
using node_traits<adapt_type>::has_child;
using node_traits<adapt_type>::get_child;
using node_traits<adapt_type>::set_child;
using node_traits<adapt_type>::has_parent;
using node_traits<adapt_type>::get_parent;
//type of type information
using type_info = typename adapt_type::type_info;
//methods for type information
static const type_info& get_return_type(const adapt_type& node_) {return node_.getReturnType();}
static const type_info& get_child_return_type(const adapt_type& node_, std::size_t n) {return node_.getChildReturnType(n);}
};
template <>
struct is_typed_node_type<node::NodeInterface>: public std::true_type{};
template <typename output_node>
struct output_node_traits;
template <typename output_node>
struct is_output_node_type: public std::false_type{};
template <typename output_node>
constexpr bool is_output_node_type_v = is_output_node_type<output_node>::value;
template <typename output_node_ptr>
using is_output_node_ptr_type = detail::is_adaptable_ptr_type<is_output_node_type, output_node_ptr>;
template <typename output_node_ptr>
constexpr bool is_output_node_ptr_type_v = is_output_node_ptr_type<output_node_ptr>::value;
template <>
struct output_node_traits<node::NodeInterface>: private node_traits<node::NodeInterface> {
private:
using adapt_type = node::NodeInterface;
public:
using node_traits<adapt_type>::has_child;
using node_traits<adapt_type>::get_child;
using node_traits<adapt_type>::get_child_num;
using node_traits<adapt_type>::has_parent;
using node_traits<adapt_type>::get_parent;
//methods for output
static std::string get_node_name(const adapt_type& node_) {return node_.getNodeName();}
};
template <>
struct is_output_node_type<node::NodeInterface>: public std::true_type{};
template <typename node>
struct input_node_traits;
template <typename input_node>
struct is_input_node_type: public std::false_type{};
template <typename input_node>
constexpr bool is_input_node_type_v = is_input_node_type<input_node>::value;
template <typename input_node_ptr>
using is_input_node_ptr_type = detail::is_adaptable_ptr_type<is_input_node_type, input_node_ptr>;
template <typename input_node_ptr>
constexpr bool is_input_node_ptr_type_v = is_input_node_ptr_type<input_node_ptr>::value;
template <>
struct input_node_traits<node::NodeInterface>: private typed_node_traits<node::NodeInterface> {
private:
using adapt_type = node::NodeInterface;
public:
using node_instance_type = typename typed_node_traits<adapt_type>::node_instance_type;
using type_info = typename typed_node_traits<adapt_type>::type_info;
using tree_property = tree::TreeProperty;
using typed_node_traits<adapt_type>::get_child_num;
using typed_node_traits<adapt_type>::has_child;
using typed_node_traits<adapt_type>::get_child;
using typed_node_traits<adapt_type>::set_child;
using typed_node_traits<adapt_type>::has_parent;
using typed_node_traits<adapt_type>::get_parent;
using typed_node_traits<adapt_type>::get_return_type;
using typed_node_traits<adapt_type>::get_child_return_type;
static bool is_valid_child(const adapt_type& node, std::size_t n, const adapt_type& child, const tree_property& treeProperty) {
if(!node.getChildReturnType(n).isAnyType() && node.getChildReturnType(n) != child.getReturnType())return false;
if(child.getNodeType() == node::NodeType::Argument) {
auto argument_idx = std::any_cast<adapt_type::variable_index_type>(child.getNodePropertyByAny());
if(std::size(treeProperty.argumentTypes) <= argument_idx) return false;
return treeProperty.argumentTypes[argument_idx]->removeReferenceType().removeLeftHandValueType() == child.getReturnType().removeReferenceType().removeLeftHandValueType();
} else if(child.getNodeType() == node::NodeType::LocalVariable){
auto localVariableIdx = std::any_cast<adapt_type::variable_index_type>(child.getNodePropertyByAny());
if(std::size(treeProperty.localVariableTypes) <= localVariableIdx)return false;
return treeProperty.localVariableTypes[localVariableIdx]->removeReferenceType().removeLeftHandValueType() == child.getReturnType().removeReferenceType().removeLeftHandValueType();
} else {
return true;
}
}
};
template <>
struct is_input_node_type<node::NodeInterface>: public std::true_type{};
}
#endif
<|endoftext|> |
<commit_before>/******************************************************************************
* $Id$
*
* Project: libLAS - http://liblas.org - A BSD library for LAS format data.
* Purpose: LAS Dimension implementation for C++ libLAS
* Author: Howard Butler, hobu.inc@gmail.com
*
******************************************************************************
* Copyright (c) 2010, Howard Butler
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Martin Isenburg or Iowa Department
* of Natural Resources 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.
****************************************************************************/
#ifndef LIBPC_DIMENSIONLAYOUT_HPP_INCLUDED
#define LIBPC_DIMENSIONLAYOUT_HPP_INCLUDED
#include <libpc/libpc.hpp>
#include <libpc/Dimension.hpp>
namespace libpc
{
class LIBPC_DLL DimensionLayout
{
public:
DimensionLayout(const Dimension&);
DimensionLayout& operator=(DimensionLayout const& rhs);
DimensionLayout(DimensionLayout const& other);
bool operator==(const DimensionLayout& other) const;
bool operator!=(const DimensionLayout& other) const;
const Dimension& getDimension() const
{
return m_dimension;
}
/// The byte location to start reading/writing
/// point data from in a composited schema. liblas::Schema
/// will set these values for you when liblas::Dimension are
/// added to the liblas::Schema.
inline std::size_t getByteOffset() const
{
return m_byteOffset;
}
inline void setByteOffset(std::size_t v)
{
m_byteOffset = v;
}
/// The index position of the index. In a standard ePointFormat0
/// data record, the X dimension would have a position of 0, while
/// the Y dimension would have a position of 1, for example.
inline std::size_t getPosition() const
{
return m_position;
}
inline void setPosition(std::size_t v)
{
m_position = v;
}
private:
Dimension m_dimension;
std::size_t m_byteOffset;
std::size_t m_position;
};
LIBPC_DLL std::ostream& operator<<(std::ostream& os, libpc::DimensionLayout const& d);
} // namespace libpc
#endif // LIBPC_DIMENSIONLAYOUT_HPP_INCLUDED
<commit_msg>add operator < and > for sorting<commit_after>/******************************************************************************
* $Id$
*
* Project: libLAS - http://liblas.org - A BSD library for LAS format data.
* Purpose: LAS Dimension implementation for C++ libLAS
* Author: Howard Butler, hobu.inc@gmail.com
*
******************************************************************************
* Copyright (c) 2010, Howard Butler
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Martin Isenburg or Iowa Department
* of Natural Resources 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.
****************************************************************************/
#ifndef LIBPC_DIMENSIONLAYOUT_HPP_INCLUDED
#define LIBPC_DIMENSIONLAYOUT_HPP_INCLUDED
#include <libpc/libpc.hpp>
#include <libpc/Dimension.hpp>
namespace libpc
{
class LIBPC_DLL DimensionLayout
{
public:
DimensionLayout(const Dimension&);
DimensionLayout& operator=(DimensionLayout const& rhs);
DimensionLayout(DimensionLayout const& other);
bool operator==(const DimensionLayout& other) const;
bool operator!=(const DimensionLayout& other) const;
const Dimension& getDimension() const
{
return m_dimension;
}
/// The byte location to start reading/writing
/// point data from in a composited schema. liblas::Schema
/// will set these values for you when liblas::Dimension are
/// added to the liblas::Schema.
inline std::size_t getByteOffset() const
{
return m_byteOffset;
}
inline void setByteOffset(std::size_t v)
{
m_byteOffset = v;
}
/// The index position of the index. In a standard ePointFormat0
/// data record, the X dimension would have a position of 0, while
/// the Y dimension would have a position of 1, for example.
inline std::size_t getPosition() const
{
return m_position;
}
inline void setPosition(std::size_t v)
{
m_position = v;
}
inline bool operator < (DimensionLayout const& dim) const
{
return m_position < dim.m_position;
}
inline bool operator > (DimensionLayout const& dim) const
{
return m_position > dim.m_position;
}
private:
Dimension m_dimension;
std::size_t m_byteOffset;
std::size_t m_position;
};
LIBPC_DLL std::ostream& operator<<(std::ostream& os, libpc::DimensionLayout const& d);
} // namespace libpc
#endif // LIBPC_DIMENSIONLAYOUT_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*
Copyright (c) 2006, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of 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.
*/
#ifndef TORRENT_EXTENSIONS_HPP_INCLUDED
#define TORRENT_EXTENSIONS_HPP_INCLUDED
#ifndef TORRENT_DISABLE_EXTENSIONS
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/weak_ptr.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <vector>
#include "libtorrent/config.hpp"
#include "libtorrent/buffer.hpp"
namespace libtorrent
{
namespace aux { struct session_impl; }
struct peer_plugin;
class bt_peer_connection;
struct peer_request;
class peer_connection;
class entry;
struct lazy_entry;
struct disk_buffer_holder;
struct bitfield;
class alert;
struct torrent_plugin;
struct TORRENT_EXPORT plugin
{
virtual ~plugin() {}
virtual boost::shared_ptr<torrent_plugin> new_torrent(torrent* t, void* user)
{ return boost::shared_ptr<torrent_plugin>(); }
// called when plugin is added to a session
virtual void added(boost::weak_ptr<aux::session_impl> s) {}
// called when an alert is posted
// alerts that are filtered are not
// posted
virtual void on_alert(alert const* a) {}
// called once per second
virtual void on_tick() {}
// called when saving settings state
virtual void save_state(entry& ent) const {}
// called when loading settings state
virtual void load_state(lazy_entry const& ent) {}
};
struct TORRENT_EXPORT torrent_plugin
{
virtual ~torrent_plugin() {}
// throwing an exception closes the connection
// returning a 0 pointer is valid and will not add
// the peer_plugin to the peer_connection
virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection*)
{ return boost::shared_ptr<peer_plugin>(); }
virtual void on_piece_pass(int index) {}
virtual void on_piece_failed(int index) {}
// called aproximately once every second
virtual void tick() {}
// if true is returned, it means the handler handled the event,
// and no other plugins will have their handlers called, and the
// default behavior will be skipped
virtual bool on_pause() { return false; }
virtual bool on_resume() { return false; }
// this is called when the initial checking of
// files is completed.
virtual void on_files_checked() {}
// called when the torrent changes state
// the state is one of torrent_status::state_t
// enum members
virtual void on_state(int s) {}
};
struct TORRENT_EXPORT peer_plugin
{
virtual ~peer_plugin() {}
virtual char const* type() const { return ""; }
// can add entries to the extension handshake
// this is not called for web seeds
virtual void add_handshake(entry&) {}
// throwing an exception from any of the handlers (except add_handshake)
// closes the connection
// this is called when the initial BT handshake is received. Returning false
// means that the other end doesn't support this extension and will remove
// it from the list of plugins.
// this is not called for web seeds
virtual bool on_handshake(char const* reserved_bits) { return true; }
// called when the extension handshake from the other end is received
// if this returns false, it means that this extension isn't
// supported by this peer. It will result in this peer_plugin
// being removed from the peer_connection and destructed.
// this is not called for web seeds
virtual bool on_extension_handshake(lazy_entry const& h) { return true; }
// returning true from any of the message handlers
// indicates that the plugin has handeled the message.
// it will break the plugin chain traversing and not let
// anyone else handle the message, including the default
// handler.
virtual bool on_choke()
{ return false; }
virtual bool on_unchoke()
{ return false; }
virtual bool on_interested()
{ return false; }
virtual bool on_not_interested()
{ return false; }
virtual bool on_have(int index)
{ return false; }
virtual bool on_bitfield(bitfield const& bitfield)
{ return false; }
virtual bool on_have_all()
{ return false; }
virtual bool on_have_none()
{ return false; }
virtual bool on_allowed_fast(int index)
{ return false; }
virtual bool on_request(peer_request const& req)
{ return false; }
virtual bool on_piece(peer_request const& piece, disk_buffer_holder& data)
{ return false; }
virtual bool on_cancel(peer_request const& req)
{ return false; }
virtual bool on_reject(peer_request const& req)
{ return false; }
virtual bool on_suggest(int index)
{ return false; }
// called when an extended message is received. If returning true,
// the message is not processed by any other plugin and if false
// is returned the next plugin in the chain will receive it to
// be able to handle it
// this is not called for web seeds
virtual bool on_extended(int length
, int msg, buffer::const_interval body)
{ return false; }
// this is not called for web seeds
virtual bool on_unknown_message(int length, int msg
, buffer::const_interval body)
{ return false; }
// called when a piece that this peer participated in either
// fails or passes the hash_check
virtual void on_piece_pass(int index) {}
virtual void on_piece_failed(int index) {}
// called aproximately once every second
virtual void tick() {}
// called each time a request message is to be sent. If true
// is returned, the original request message won't be sent and
// no other plugin will have this function called.
virtual bool write_request(peer_request const& r) { return false; }
};
}
#endif
#endif // TORRENT_EXTENSIONS_HPP_INCLUDED
<commit_msg>fix build<commit_after>/*
Copyright (c) 2006, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of 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.
*/
#ifndef TORRENT_EXTENSIONS_HPP_INCLUDED
#define TORRENT_EXTENSIONS_HPP_INCLUDED
#ifndef TORRENT_DISABLE_EXTENSIONS
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/weak_ptr.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <vector>
#include "libtorrent/config.hpp"
#include "libtorrent/buffer.hpp"
namespace libtorrent
{
namespace aux { struct session_impl; }
struct peer_plugin;
class bt_peer_connection;
struct peer_request;
class peer_connection;
class entry;
struct lazy_entry;
struct disk_buffer_holder;
struct bitfield;
class alert;
struct torrent_plugin;
class torrent;
struct TORRENT_EXPORT plugin
{
virtual ~plugin() {}
virtual boost::shared_ptr<torrent_plugin> new_torrent(torrent* t, void* user)
{ return boost::shared_ptr<torrent_plugin>(); }
// called when plugin is added to a session
virtual void added(boost::weak_ptr<aux::session_impl> s) {}
// called when an alert is posted
// alerts that are filtered are not
// posted
virtual void on_alert(alert const* a) {}
// called once per second
virtual void on_tick() {}
// called when saving settings state
virtual void save_state(entry& ent) const {}
// called when loading settings state
virtual void load_state(lazy_entry const& ent) {}
};
struct TORRENT_EXPORT torrent_plugin
{
virtual ~torrent_plugin() {}
// throwing an exception closes the connection
// returning a 0 pointer is valid and will not add
// the peer_plugin to the peer_connection
virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection*)
{ return boost::shared_ptr<peer_plugin>(); }
virtual void on_piece_pass(int index) {}
virtual void on_piece_failed(int index) {}
// called aproximately once every second
virtual void tick() {}
// if true is returned, it means the handler handled the event,
// and no other plugins will have their handlers called, and the
// default behavior will be skipped
virtual bool on_pause() { return false; }
virtual bool on_resume() { return false; }
// this is called when the initial checking of
// files is completed.
virtual void on_files_checked() {}
// called when the torrent changes state
// the state is one of torrent_status::state_t
// enum members
virtual void on_state(int s) {}
};
struct TORRENT_EXPORT peer_plugin
{
virtual ~peer_plugin() {}
virtual char const* type() const { return ""; }
// can add entries to the extension handshake
// this is not called for web seeds
virtual void add_handshake(entry&) {}
// throwing an exception from any of the handlers (except add_handshake)
// closes the connection
// this is called when the initial BT handshake is received. Returning false
// means that the other end doesn't support this extension and will remove
// it from the list of plugins.
// this is not called for web seeds
virtual bool on_handshake(char const* reserved_bits) { return true; }
// called when the extension handshake from the other end is received
// if this returns false, it means that this extension isn't
// supported by this peer. It will result in this peer_plugin
// being removed from the peer_connection and destructed.
// this is not called for web seeds
virtual bool on_extension_handshake(lazy_entry const& h) { return true; }
// returning true from any of the message handlers
// indicates that the plugin has handeled the message.
// it will break the plugin chain traversing and not let
// anyone else handle the message, including the default
// handler.
virtual bool on_choke()
{ return false; }
virtual bool on_unchoke()
{ return false; }
virtual bool on_interested()
{ return false; }
virtual bool on_not_interested()
{ return false; }
virtual bool on_have(int index)
{ return false; }
virtual bool on_bitfield(bitfield const& bitfield)
{ return false; }
virtual bool on_have_all()
{ return false; }
virtual bool on_have_none()
{ return false; }
virtual bool on_allowed_fast(int index)
{ return false; }
virtual bool on_request(peer_request const& req)
{ return false; }
virtual bool on_piece(peer_request const& piece, disk_buffer_holder& data)
{ return false; }
virtual bool on_cancel(peer_request const& req)
{ return false; }
virtual bool on_reject(peer_request const& req)
{ return false; }
virtual bool on_suggest(int index)
{ return false; }
// called when an extended message is received. If returning true,
// the message is not processed by any other plugin and if false
// is returned the next plugin in the chain will receive it to
// be able to handle it
// this is not called for web seeds
virtual bool on_extended(int length
, int msg, buffer::const_interval body)
{ return false; }
// this is not called for web seeds
virtual bool on_unknown_message(int length, int msg
, buffer::const_interval body)
{ return false; }
// called when a piece that this peer participated in either
// fails or passes the hash_check
virtual void on_piece_pass(int index) {}
virtual void on_piece_failed(int index) {}
// called aproximately once every second
virtual void tick() {}
// called each time a request message is to be sent. If true
// is returned, the original request message won't be sent and
// no other plugin will have this function called.
virtual bool write_request(peer_request const& r) { return false; }
};
}
#endif
#endif // TORRENT_EXTENSIONS_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015-2016, Technische Universität Dresden, Germany
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef INCLUDE_NITRO_LOG_SINK_STDERR_HPP
#define INCLUDE_NITRO_LOG_SINK_STDERR_HPP
#include <iostream>
#include <string>
namespace nitro
{
namespace log
{
namespace sink
{
class stderr
{
public:
void sink(std::string formatted_record)
{
std::cerr << formatted_record << std::endl;
}
};
}
}
} // namespace nitro::log::sink
#endif // INCLUDE_NITRO_LOG_SINK_STDERR_HPP
<commit_msg>remove std::endl for std::err output.<commit_after>/*
* Copyright (c) 2015-2016, Technische Universität Dresden, Germany
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef INCLUDE_NITRO_LOG_SINK_STDERR_HPP
#define INCLUDE_NITRO_LOG_SINK_STDERR_HPP
#include <iostream>
#include <string>
namespace nitro
{
namespace log
{
namespace sink
{
class stderr
{
public:
void sink(std::string formatted_record)
{
std::cerr << formatted_record;
}
};
}
}
} // namespace nitro::log::sink
#endif // INCLUDE_NITRO_LOG_SINK_STDERR_HPP
<|endoftext|> |
<commit_before>/* molecule.cc
* Copyright 2014 Cubane Canada, Inc.
*
* Released under the MIT license -- see MIT-LICENSE for details
*/
#include <node.h>
#include <v8.h>
#include <uv.h>
#include <nan.h>
#include <cstring>
#include "./using_v8.h"
#include "./molecule.h"
#include "./get_inchi_worker.h"
/**
@module Internal
@class Molecule_CC
*/
/* local (non-API) functions */
void populate_input(Handle<Value> val, Molecule* in);
static void populate_ret(Handle<Object> ret,
const inchi_Output& out, int result);
void addstring(Handle<Object> ret, const char * name, const char * value);
/**
* Create an Molecule structure from a partially or fully specified
* JavaScript object
*
* @method Create
* @param {Handle<Object>} val Object handle that parallels an inchi_Input
*/
Molecule * Molecule::Create(Handle<Value> val) {
// TODO(SOM): validation
// create an empty Molecule
Molecule * input = new Molecule;
// populate it
populate_input(val, input);
// return it
return input;
}
void add_atom(Molecule* in, Handle<Object> a) {
InchiAtom atom = InchiAtom::makeFromObject(a);
int index = in->addAtom(atom);
Handle<Array> neighbor =
Handle<Array>::Cast(a->Get(NanSymbol("neighbor")));
int bonds = neighbor->Length();
for (int i = 0; i < bonds; ++i) {
int bonded = neighbor->Get(i)->ToNumber()->Value();
in->addBond(InchiBond(index, bonded));
}
}
void populate_input(Handle<Value> val, Molecule* in) {
// TODO(SOM): support validation, possibly return error code
// expect args[0] to be an Object, call it 'mol'
// expect mol.atom to be an Array
// expect mol.options to be a string
// expect mol.stereo0D to be an Array
if (!val->IsObject()) {
return;
}
Handle<Object> mol = val->ToObject();
if (!mol->Has(NanSymbol("atom")) || !mol->Get(NanSymbol("atom"))->IsArray()) {
return;
}
Handle<Array> atom = Handle<Array>::Cast(mol->Get(NanSymbol("atom")));
int atoms = atom->Length();
for (int i = 0; i < atoms; i += 1) {
add_atom(in, atom->Get(i)->ToObject());
}
}
void addstring(Handle<Object> ret, const char * name, const char * in) {
const char * value = (in ? in : "");
ret->Set(NanSymbol(name), String::New(value));
}
static void populate_ret(Handle<Object> ret,
const inchi_Output& out, int result) {
addstring(ret, "inchi", out.szInChI);
addstring(ret, "auxinfo", out.szAuxInfo);
addstring(ret, "message", out.szMessage);
addstring(ret, "log", out.szLog);
ret->Set(NanSymbol("code"), Number::New(result));
}
Handle<Object> GetResult(GetINCHIData * data) {
Local<Object> ret = Object::New();
populate_ret(ret, data->out_, data->result_);
addstring(ret, "inchikey", data->inchikey);
return ret;
}
<commit_msg>inchilib: simplify complex cast expr<commit_after>/* molecule.cc
* Copyright 2014 Cubane Canada, Inc.
*
* Released under the MIT license -- see MIT-LICENSE for details
*/
#include <node.h>
#include <v8.h>
#include <uv.h>
#include <nan.h>
#include <cstring>
#include "./using_v8.h"
#include "./molecule.h"
#include "./get_inchi_worker.h"
/**
@module Internal
@class Molecule_CC
*/
/* local (non-API) functions */
void populate_input(Handle<Value> val, Molecule* in);
static void populate_ret(Handle<Object> ret,
const inchi_Output& out, int result);
void addstring(Handle<Object> ret, const char * name, const char * value);
/**
* Create an Molecule structure from a partially or fully specified
* JavaScript object
*
* @method Create
* @param {Handle<Object>} val Object handle that parallels an inchi_Input
*/
Molecule * Molecule::Create(Handle<Value> val) {
// TODO(SOM): validation
// create an empty Molecule
Molecule * input = new Molecule;
// populate it
populate_input(val, input);
// return it
return input;
}
void add_atom(Molecule* in, Handle<Object> a) {
InchiAtom atom = InchiAtom::makeFromObject(a);
int index = in->addAtom(atom);
Handle<Array> neighbor =
Handle<Array>::Cast(a->Get(NanSymbol("neighbor")));
int bonds = neighbor->Length();
for (int i = 0; i < bonds; ++i) {
int bonded = neighbor->Get(i)->ToNumber()->Value();
in->addBond(InchiBond(index, bonded));
}
}
void populate_input(Handle<Value> val, Molecule* in) {
// TODO(SOM): support validation, possibly return error code
// expect args[0] to be an Object, call it 'mol'
// expect mol.atom to be an Array
// expect mol.options to be a string
// expect mol.stereo0D to be an Array
if (!val->IsObject()) {
return;
}
Handle<Object> mol = val->ToObject();
if (!mol->Has(NanSymbol("atom")) || !mol->Get(NanSymbol("atom"))->IsArray()) {
return;
}
Handle<Array> atom = mol->Get(NanSymbol("atom")).As<Array>();
int atoms = atom->Length();
for (int i = 0; i < atoms; i += 1) {
add_atom(in, atom->Get(i)->ToObject());
}
}
void addstring(Handle<Object> ret, const char * name, const char * in) {
const char * value = (in ? in : "");
ret->Set(NanSymbol(name), String::New(value));
}
static void populate_ret(Handle<Object> ret,
const inchi_Output& out, int result) {
addstring(ret, "inchi", out.szInChI);
addstring(ret, "auxinfo", out.szAuxInfo);
addstring(ret, "message", out.szMessage);
addstring(ret, "log", out.szLog);
ret->Set(NanSymbol("code"), Number::New(result));
}
Handle<Object> GetResult(GetINCHIData * data) {
Local<Object> ret = Object::New();
populate_ret(ret, data->out_, data->result_);
addstring(ret, "inchikey", data->inchikey);
return ret;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "HTTPRequestMessage.h"
#include <algorithm>
#include "url/URI.h"
#include "http/HTTPUtil.h"
namespace {
// methodNames must be in sync with method codes in HttpRequestMessage
const char* methodNames[] = {
"OPTIONS",
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
"TRACE",
"CONNECT"
};
const char** methodNamesEnd = methodNames + (sizeof methodNames / sizeof methodNames[0]);
}
namespace org { namespace w3c { namespace dom { namespace bootstrap {
using namespace http;
int HttpRequestMessage::getMethodCode() const
{
return std::find(methodNames, methodNamesEnd, method) - methodNames;
}
void HttpRequestMessage::open(const std::string& method, const std::u16string& url)
{
this->method = method;
toUpperCase(this->method);
this->url = URL(url);
}
void HttpRequestMessage::setHeader(const std::string& header, const std::string& value)
{
headers.set(header, value);
}
void HttpRequestMessage::clear()
{
version = 11;
headers.clear();
}
std::string HttpRequestMessage::toString()
{
URI uri(url);
std::string s;
if (version == 9) {
s += "GET " + uri.getPathname() + " \r\n";
return s;
}
s += method + ' ' + uri.getPathname() + " HTTP/";
switch (version) {
case 11:
s += "1.1";
headers.set("Host", uri.getHostname() + ":" + uri.getPort()); // TODO: port can be omitted.
break;
default:
s += "1.0";
break;
}
s += "\r\n";
s += headers.toString();
return s;
}
}}}} // org::w3c::dom::bootstrap
<commit_msg>(HttpRequestMessage::toString) : Fix bugs.<commit_after>/*
* Copyright 2011 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "HTTPRequestMessage.h"
#include <algorithm>
#include "url/URI.h"
#include "http/HTTPUtil.h"
namespace {
// methodNames must be in sync with method codes in HttpRequestMessage
const char* methodNames[] = {
"OPTIONS",
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
"TRACE",
"CONNECT"
};
const char** methodNamesEnd = methodNames + (sizeof methodNames / sizeof methodNames[0]);
}
namespace org { namespace w3c { namespace dom { namespace bootstrap {
using namespace http;
int HttpRequestMessage::getMethodCode() const
{
return std::find(methodNames, methodNamesEnd, method) - methodNames;
}
void HttpRequestMessage::open(const std::string& method, const std::u16string& url)
{
this->method = method;
toUpperCase(this->method);
this->url = URL(url);
}
void HttpRequestMessage::setHeader(const std::string& header, const std::string& value)
{
headers.set(header, value);
}
void HttpRequestMessage::clear()
{
version = 11;
headers.clear();
}
std::string HttpRequestMessage::toString()
{
URI uri(url);
std::string s;
if (version == 9) {
s += "GET " + uri.getPathname() + uri.getSearch() + " \r\n";
return s;
}
s += method + ' ' + uri.getPathname() + uri.getSearch() + " HTTP/";
switch (version) {
case 11:
s += "1.1";
headers.set("Host", uri.getHost());
break;
default:
s += "1.0";
break;
}
s += "\r\n";
s += headers.toString();
return s;
}
}}}} // org::w3c::dom::bootstrap
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <Modules/Visualization/ShowMesh.h>
#include <Core/Datatypes/Mesh/Mesh.h>
#include <Core/Datatypes/Mesh/MeshFacade.h>
#include <Core/Datatypes/Geometry.h>
#include <boost/foreach.hpp>
using namespace SCIRun::Modules::Visualization;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
ShowMeshModule::ShowMeshModule() : Module(ModuleLookupInfo("ShowMesh", "Visualization", "SCIRun"))
{
get_state()->setValue(ShowEdges, true);
get_state()->setValue(ShowFaces, true);
}
void ShowMeshModule::execute()
{
auto mesh = getRequiredInput(Mesh);
MeshFacadeHandle facade(mesh->getFacade());
bool showEdges = get_state()->getValue(ShowEdges).getBool();
bool showFaces = get_state()->getValue(ShowFaces).getBool();
bool zTestOn = get_state()->getValue(ZTestOn).getBool();
GeometryHandle geom(new GeometryObject(mesh));
geom->objectName = get_id();
/// \todo Split the mesh into chunks of about ~32,000 vertices. May be able to
/// eek out better coherency and use a 16 bit index buffer instead of
/// a 32 bit index buffer.
// We are going to get no lighting in this first pass. The unfortunate reality
// is that I cannot get access to face normals in vertex shaders based off of
// the winding orders of the incoming geometry.
// Allocate memory for vertex buffer (*NOT* the index buffer, which is a
// a function of the number of faces). Only allocating enough memory to hold
// points associated with the faces.
// Edges *and* faces should use the same vbo!
std::shared_ptr<std::vector<uint8_t>> rawVBO(new std::vector<uint8_t>());
size_t vboSize = sizeof(float) * 3 * facade->numNodes();
rawVBO->resize(vboSize); // linear complexity.
float* vbo = reinterpret_cast<float*>(&(*rawVBO)[0]); // Remember, standard guarantees that vectors are contiguous in memory.
// Add shared VBO to the geometry object.
std::string primVBOName = "primaryVBO";
std::vector<std::string> attribs; ///< \todo Switch to initializer lists when msvc supports it.
attribs.push_back("aPos"); ///< \todo Find a good place to pull these names from.
geom->mVBOs.emplace_back(GeometryObject::SpireVBO(primVBOName, attribs, rawVBO));
// Build index buffer. Based off of the node indices that came out of old
// SCIRun, TnL cache coherency will be poor. Maybe room for improvement later.
size_t i = 0;
BOOST_FOREACH(const NodeInfo& node, facade->nodes())
{
vbo[i+0] = node.point().x(); vbo[i+1] = node.point().y(); vbo[i+2] = node.point().z();
i+=3;
}
// Build the faces.
size_t iboFacesSize = sizeof(uint32_t) * facade->numFaces() * 6;
uint32_t* iboFaces = nullptr;
if (showFaces)
{
std::shared_ptr<std::vector<uint8_t>> rawIBO(new std::vector<uint8_t>());
//rawIBO->reserve(iboFacesSize);
rawIBO->resize(iboFacesSize); // Linear in complexity... If we need more performance,
// use malloc to generate buffer and then vector::assign.
iboFaces = reinterpret_cast<uint32_t*>(&(*rawIBO)[0]);
i = 0;
BOOST_FOREACH(const FaceInfo& face, facade->faces())
{
// There should *only* be four indicies.
VirtualMesh::Node::array_type nodes = face.nodeIndices();
assert(nodes.size() == 4);
// Winding order looks good from tests.
// Render two triangles.
iboFaces[i ] = nodes[0]; iboFaces[i+1] = nodes[1]; iboFaces[i+2] = nodes[2];
iboFaces[i+3] = nodes[0]; iboFaces[i+4] = nodes[2]; iboFaces[i+5] = nodes[3];
i += 6;
}
// Add IBO for the faces.
std::string facesIBOName = "facesIBO";
geom->mIBOs.emplace_back(GeometryObject::SpireIBO(facesIBOName, sizeof(uint32_t), rawIBO));
// Build pass for the faces.
/// \todo Find an appropriate place to put program names like UniformColor.
GeometryObject::SpirePass pass =
GeometryObject::SpirePass("facesPass", primVBOName,
facesIBOName, "UniformColor",
Spire::StuInterface::TRIANGLES);
pass.addUniform("uColor", Spire::V4(1.0f, 1.0f, 1.0f, 1.0f));
geom->mPasses.emplace_back(pass);
}
// Build the edges
size_t iboEdgesSize = sizeof(uint32_t) * facade->numEdges() * 2;
uint32_t* iboEdges = nullptr;
if (showEdges)
{
std::shared_ptr<std::vector<uint8_t>> rawIBO(new std::vector<uint8_t>());
//rawIBO->reserve(iboEdgesSize);
rawIBO->resize(iboEdgesSize); // Linear in complexity... If we need more performance,
// use malloc to generate buffer and then vector::assign.
iboEdges = reinterpret_cast<uint32_t*>(&(*rawIBO)[0]);
i = 0;
BOOST_FOREACH(const EdgeInfo& edge, facade->edges())
{
// There should *only* be two indicies (linestrip would be better...)
VirtualMesh::Node::array_type nodes = edge.nodeIndices();
assert(nodes.size() == 2);
// Winding order looks good from tests.
// Render two triangles.
iboEdges[i] = nodes[0]; iboEdges[i+1] = nodes[1];
i += 2;
}
// Add IBO for the faces.
std::string edgesIBOName = "edgesIBO";
geom->mIBOs.emplace_back(GeometryObject::SpireIBO(edgesIBOName, sizeof(uint32_t), rawIBO));
// Build pass for the faces.
/// \todo Find an appropriate place to put program names like UniformColor.
GeometryObject::SpirePass pass =
GeometryObject::SpirePass("edgesPass", primVBOName,
edgesIBOName, "UniformColor",
Spire::StuInterface::LINES);
// Add appropriate uniforms to the pass (in this case, uColor).
pass.addUniform("uColor", Spire::V4(0.6f, 0.6f, 0.6f, 1.0f));
geom->mPasses.emplace_back(pass);
}
//mStuInterface->addPassUniform(obj1, pass1, "uColor", V4(1.0f, 0.0f, 0.0f, 1.0f));
sendOutput(SceneGraph, geom);
}
AlgorithmParameterName ShowMeshModule::ShowEdges("Show edges");
AlgorithmParameterName ShowMeshModule::ShowFaces("Show faces");
AlgorithmParameterName ShowMeshModule::ZTestOn("Z Test");
<commit_msg>Edges are now rendered before faces.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <Modules/Visualization/ShowMesh.h>
#include <Core/Datatypes/Mesh/Mesh.h>
#include <Core/Datatypes/Mesh/MeshFacade.h>
#include <Core/Datatypes/Geometry.h>
#include <boost/foreach.hpp>
using namespace SCIRun::Modules::Visualization;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
ShowMeshModule::ShowMeshModule() : Module(ModuleLookupInfo("ShowMesh", "Visualization", "SCIRun"))
{
get_state()->setValue(ShowEdges, true);
get_state()->setValue(ShowFaces, true);
}
void ShowMeshModule::execute()
{
auto mesh = getRequiredInput(Mesh);
MeshFacadeHandle facade(mesh->getFacade());
bool showEdges = get_state()->getValue(ShowEdges).getBool();
bool showFaces = get_state()->getValue(ShowFaces).getBool();
bool zTestOn = get_state()->getValue(ZTestOn).getBool();
GeometryHandle geom(new GeometryObject(mesh));
geom->objectName = get_id();
/// \todo Split the mesh into chunks of about ~32,000 vertices. May be able to
/// eek out better coherency and use a 16 bit index buffer instead of
/// a 32 bit index buffer.
// We are going to get no lighting in this first pass. The unfortunate reality
// is that I cannot get access to face normals in vertex shaders based off of
// the winding orders of the incoming geometry.
// Allocate memory for vertex buffer (*NOT* the index buffer, which is a
// a function of the number of faces). Only allocating enough memory to hold
// points associated with the faces.
// Edges *and* faces should use the same vbo!
std::shared_ptr<std::vector<uint8_t>> rawVBO(new std::vector<uint8_t>());
size_t vboSize = sizeof(float) * 3 * facade->numNodes();
rawVBO->resize(vboSize); // linear complexity.
float* vbo = reinterpret_cast<float*>(&(*rawVBO)[0]); // Remember, standard guarantees that vectors are contiguous in memory.
// Add shared VBO to the geometry object.
std::string primVBOName = "primaryVBO";
std::vector<std::string> attribs; ///< \todo Switch to initializer lists when msvc supports it.
attribs.push_back("aPos"); ///< \todo Find a good place to pull these names from.
geom->mVBOs.emplace_back(GeometryObject::SpireVBO(primVBOName, attribs, rawVBO));
// Build index buffer. Based off of the node indices that came out of old
// SCIRun, TnL cache coherency will be poor. Maybe room for improvement later.
size_t i = 0;
BOOST_FOREACH(const NodeInfo& node, facade->nodes())
{
vbo[i+0] = node.point().x(); vbo[i+1] = node.point().y(); vbo[i+2] = node.point().z();
i+=3;
}
// Build the edges
size_t iboEdgesSize = sizeof(uint32_t) * facade->numEdges() * 2;
uint32_t* iboEdges = nullptr;
if (showEdges)
{
std::shared_ptr<std::vector<uint8_t>> rawIBO(new std::vector<uint8_t>());
//rawIBO->reserve(iboEdgesSize);
rawIBO->resize(iboEdgesSize); // Linear in complexity... If we need more performance,
// use malloc to generate buffer and then vector::assign.
iboEdges = reinterpret_cast<uint32_t*>(&(*rawIBO)[0]);
i = 0;
BOOST_FOREACH(const EdgeInfo& edge, facade->edges())
{
// There should *only* be two indicies (linestrip would be better...)
VirtualMesh::Node::array_type nodes = edge.nodeIndices();
assert(nodes.size() == 2);
// Winding order looks good from tests.
// Render two triangles.
iboEdges[i] = nodes[0]; iboEdges[i+1] = nodes[1];
i += 2;
}
// Add IBO for the faces.
std::string edgesIBOName = "edgesIBO";
geom->mIBOs.emplace_back(GeometryObject::SpireIBO(edgesIBOName, sizeof(uint32_t), rawIBO));
// Build pass for the faces.
/// \todo Find an appropriate place to put program names like UniformColor.
GeometryObject::SpirePass pass =
GeometryObject::SpirePass("edgesPass", primVBOName,
edgesIBOName, "UniformColor",
Spire::StuInterface::LINES);
// Add appropriate uniforms to the pass (in this case, uColor).
pass.addUniform("uColor", Spire::V4(0.6f, 0.6f, 0.6f, 1.0f));
geom->mPasses.emplace_back(pass);
}
//mStuInterface->addPassUniform(obj1, pass1, "uColor", V4(1.0f, 0.0f, 0.0f, 1.0f));
// Build the faces.
size_t iboFacesSize = sizeof(uint32_t) * facade->numFaces() * 6;
uint32_t* iboFaces = nullptr;
if (showFaces)
{
std::shared_ptr<std::vector<uint8_t>> rawIBO(new std::vector<uint8_t>());
//rawIBO->reserve(iboFacesSize);
rawIBO->resize(iboFacesSize); // Linear in complexity... If we need more performance,
// use malloc to generate buffer and then vector::assign.
iboFaces = reinterpret_cast<uint32_t*>(&(*rawIBO)[0]);
i = 0;
BOOST_FOREACH(const FaceInfo& face, facade->faces())
{
// There should *only* be four indicies.
VirtualMesh::Node::array_type nodes = face.nodeIndices();
assert(nodes.size() == 4);
// Winding order looks good from tests.
// Render two triangles.
iboFaces[i ] = nodes[0]; iboFaces[i+1] = nodes[1]; iboFaces[i+2] = nodes[2];
iboFaces[i+3] = nodes[0]; iboFaces[i+4] = nodes[2]; iboFaces[i+5] = nodes[3];
i += 6;
}
// Add IBO for the faces.
std::string facesIBOName = "facesIBO";
geom->mIBOs.emplace_back(GeometryObject::SpireIBO(facesIBOName, sizeof(uint32_t), rawIBO));
// Build pass for the faces.
/// \todo Find an appropriate place to put program names like UniformColor.
GeometryObject::SpirePass pass =
GeometryObject::SpirePass("facesPass", primVBOName,
facesIBOName, "UniformColor",
Spire::StuInterface::TRIANGLES);
pass.addUniform("uColor", Spire::V4(1.0f, 1.0f, 1.0f, 1.0f));
geom->mPasses.emplace_back(pass);
}
sendOutput(SceneGraph, geom);
}
AlgorithmParameterName ShowMeshModule::ShowEdges("Show edges");
AlgorithmParameterName ShowMeshModule::ShowFaces("Show faces");
AlgorithmParameterName ShowMeshModule::ZTestOn("Z Test");
<|endoftext|> |
<commit_before>#include "Database.h"
#include "Console.h"
#include "MainFrame.h"
#include "SDLDialog.h"
#include <SDL/SDL_gfxPrimitives.h>
#include <algorithm>
#include <fstream>
#include <boost/lexical_cast.hpp>
using namespace std;
Database::Database() {
}
Database::~Database() {
clear();
}
Database::Database(const Database &db) {
for(size_t i = 0; i < db.table.size(); i ++) {
Column *column = newColumn(db.table[i].first.c_str());
for(size_t j = 0; j < db.table[i].second->getSize(); j ++)
column->push_back(db.table[i].second->at(j));
}
}
void Database::operator= (const Database &db) {
for(size_t i = 0; i < db.table.size(); i ++) {
Column *column = newColumn(db.table[i].first.c_str());
for(size_t j = 0; j < db.table[i].second->getSize(); j ++)
column->push_back(db.table[i].second->at(j));
}
}
void Database::clear() {
for(size_t i = 0; i < table.size(); i ++)
delete table[i].second;
table.clear();
}
Column* Database::newColumn(const char name[]) {
table.push_back(make_pair(name, new Column()));
return table.back().second;
}
void Database::addColumn(const char name[], Column *column) {
table.push_back(make_pair(name, column));
}
Database Database::random(int n) const {
int minC = table[0].second->getSize();
for(size_t i = 0; i < table.size(); i ++)
if(table[i].second->getSize() < minC)
minC = table[i].second->getSize();
srand(time(0));
vector<int> nums;
for(int i = 0; i < n; i ++) {
bool duplicate = false;
int tmp = 0;
do {
duplicate = false;
tmp = rand() % minC;
for(size_t j = 0; j < nums.size(); j ++)
if(tmp == nums[j])
duplicate = true;
} while(duplicate);
nums.push_back(tmp);
}
Database result;
for(size_t i = 0; i < table.size(); i ++) {
Column *tmp = result.newColumn(table[i].first.c_str());
for(int j = 0; j < nums.size(); j ++)
tmp->push_back(table[i].second->at(nums[j]));
}
return result;
}
void Database::print() const {
for(size_t i = 0; i < table.size(); i ++) {
Console::GetSingleton() << wxString(table[i].first.c_str(), wxConvUTF8) << wxT(": ");
table[i].second->print();
}
}
void Database::save(const string &filename) const {
if(filename.substr(filename.find_last_of('.')) == ".xlsx")
saveExcel(filename);
}
void Database::load(const string &filename) {
if(filename.substr(filename.find_last_of('.')) == ".xlsx")
loadExcel(filename);
}
void Database::drawPie(int width, int height) const {
SDLDialog *dlg = new SDLDialog(MainFrame::GetSingletonPtr(), width, height);
int sum = 0;
for(int i = 0; i < table[0].second->getSize(); i ++)
sum += boost::lexical_cast<int>(table[0].second->at(i));
float start = 0;
for(int i = 0; i < table[0].second->getSize(); i ++) {
float data = boost::lexical_cast<int>(table[0].second->at(i));
float end = start + (data * 360 / sum);
filledPieRGBA(dlg->getSurface(), width/2, height/2, min(width, height)/2 - 50, start, end, rand()%255, rand()%255, rand()%255, 255);
start = end;
}
dlg->Show();
}
void Database::saveExcel(const string &filename) const {
// TODO: Write save code here
}
void Database::loadExcel(const string &filename) {
// TODO: Write load code here
}
<commit_msg>Loading Excel text format<commit_after>#include "Database.h"
#include "Console.h"
#include "MainFrame.h"
#include "SDLDialog.h"
#include <SDL/SDL_gfxPrimitives.h>
#include <algorithm>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
Database::Database() {
}
Database::~Database() {
clear();
}
Database::Database(const Database &db) {
for(size_t i = 0; i < db.table.size(); i ++) {
Column *column = newColumn(db.table[i].first.c_str());
for(size_t j = 0; j < db.table[i].second->getSize(); j ++)
column->push_back(db.table[i].second->at(j));
}
}
void Database::operator= (const Database &db) {
for(size_t i = 0; i < db.table.size(); i ++) {
Column *column = newColumn(db.table[i].first.c_str());
for(size_t j = 0; j < db.table[i].second->getSize(); j ++)
column->push_back(db.table[i].second->at(j));
}
}
void Database::clear() {
for(size_t i = 0; i < table.size(); i ++)
delete table[i].second;
table.clear();
}
Column* Database::newColumn(const char name[]) {
table.push_back(make_pair(name, new Column()));
return table.back().second;
}
void Database::addColumn(const char name[], Column *column) {
table.push_back(make_pair(name, column));
}
Database Database::random(int n) const {
int minC = table[0].second->getSize();
for(size_t i = 0; i < table.size(); i ++)
if(table[i].second->getSize() < minC)
minC = table[i].second->getSize();
srand(time(0));
vector<int> nums;
for(int i = 0; i < n; i ++) {
bool duplicate = false;
int tmp = 0;
do {
duplicate = false;
tmp = rand() % minC;
for(size_t j = 0; j < nums.size(); j ++)
if(tmp == nums[j])
duplicate = true;
} while(duplicate);
nums.push_back(tmp);
}
Database result;
for(size_t i = 0; i < table.size(); i ++) {
Column *tmp = result.newColumn(table[i].first.c_str());
for(int j = 0; j < nums.size(); j ++)
tmp->push_back(table[i].second->at(nums[j]));
}
return result;
}
void Database::print() const {
for(size_t i = 0; i < table.size(); i ++) {
Console::GetSingleton() << wxString(table[i].first.c_str(), wxConvUTF8) << wxT(": ");
table[i].second->print();
}
}
void Database::save(const string &filename) const {
if(filename.substr(filename.find_last_of('.')) == ".xlsx")
saveExcel(filename);
}
void Database::load(const string &filename) {
if(filename.substr(filename.find_last_of('.')) == ".xlsx")
loadExcel(filename);
}
void Database::drawPie(int width, int height) const {
SDLDialog *dlg = new SDLDialog(MainFrame::GetSingletonPtr(), width, height);
int sum = 0;
for(int i = 0; i < table[0].second->getSize(); i ++)
sum += boost::lexical_cast<int>(table[0].second->at(i));
float start = 0;
for(int i = 0; i < table[0].second->getSize(); i ++) {
float data = boost::lexical_cast<int>(table[0].second->at(i));
float end = start + (data * 360 / sum);
filledPieRGBA(dlg->getSurface(), width/2, height/2, min(width, height)/2 - 50, start, end, rand()%255, rand()%255, rand()%255, 255);
start = end;
}
dlg->Show();
}
void Database::saveExcel(const string &filename) const {
// TODO: Write save code here
}
void Database::loadExcel(const string &filename) {
ifstream input(filename.c_str(), ios::in);
if(!input)
return;
this->clear();
string line;
getline(input, line);
stringstream ss(line);
string section;
while(ss >> section)
this->newColumn(section.c_str());
while(getline(input, line)) {
ss = stringstream(line);
for(int i = 0; i < table.size(); i ++) {
getline(ss, section, '\t');
boost::algorithm::trim(section);
if(section.length())
table[i].second->push_back(section);
}
}
}
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include "sniffer.h"
#include "analyzer.h"
const size_t sniffer::MIN_SIZE = 1024 * 1024;
const size_t sniffer::MAX_SIZE = 1024 * 1024 * 1024;
const size_t sniffer::DEFAULT_SIZE = 100 * 1024 * 1024;
const char* sniffer::CONNECTIONS_FILENAME = "connections.txt";
const char* sniffer::PIPE_FILENAME = "/tmp/gsniffer.pipe";
sniffer::sniffer()
{
*_M_interface = 0;
_M_fd = -1;
_M_buf = MAP_FAILED;
_M_size = 0;
_M_frames = NULL;
_M_number_frames = 0;
_M_idx = 0;
_M_pipe = -1;
_M_running = false;
_M_handle_alarm = false;
}
sniffer::~sniffer()
{
if (_M_buf != MAP_FAILED) {
munmap(_M_buf, _M_size);
}
if (_M_fd != -1) {
close(_M_fd);
}
if (_M_frames) {
free(_M_frames);
}
if (_M_pipe != -1) {
close(_M_pipe);
}
unlink(PIPE_FILENAME);
}
bool sniffer::create(const char* interface, size_t size)
{
// Sanity check.
if ((size < MIN_SIZE) || (size > MAX_SIZE)) {
return false;
}
size_t len;
if ((len = strlen(interface)) >= sizeof(_M_interface)) {
return false;
}
// Create named pipe.
umask(0);
if ((mkfifo(PIPE_FILENAME, 0666) < 0) && (errno != EEXIST)) {
return false;
}
// Open named pipe.
if ((_M_pipe = open(PIPE_FILENAME, O_RDWR | O_NONBLOCK)) < 0) {
return false;
}
// Save interface.
memcpy(_M_interface, interface, len + 1);
// Create socket.
if ((_M_fd = socket(AF_PACKET, SOCK_DGRAM, 0)) < 0) {
return false;
}
// Get interface index.
struct ifreq ifr;
memcpy(ifr.ifr_name, interface, len + 1);
if (ioctl(_M_fd, SIOCGIFINDEX, &ifr) < 0) {
return false;
}
// Bind.
struct sockaddr_ll addr;
memset(&addr, 0, sizeof(struct sockaddr_ll));
addr.sll_family = AF_PACKET;
addr.sll_protocol = htons(ETH_P_ALL);
addr.sll_ifindex = ifr.ifr_ifindex;
addr.sll_pkttype = PACKET_HOST | PACKET_OUTGOING;
if (bind(_M_fd, (const struct sockaddr*) &addr, sizeof(struct sockaddr_ll)) < 0) {
return false;
}
// Calculate frame size.
size_t frame_size = TPACKET_ALIGN(TPACKET_HDRLEN) + TPACKET_ALIGN(ETH_DATA_LEN);
size_t n;
for (n = 8; n < frame_size; n *= 2);
frame_size = n;
// Calculate block size.
size_t block_size = getpagesize();
for (; block_size < frame_size; block_size *= 2);
// Calculate number of blocks and number of frames.
size_t block_count = size / block_size;
_M_size = block_count * block_size;
_M_number_frames = _M_size / frame_size;
struct tpacket_req req;
req.tp_block_size = block_size;
req.tp_block_nr = block_count;
req.tp_frame_size = frame_size;
req.tp_frame_nr = _M_number_frames;
// Setup PACKET_MMAP.
if (setsockopt(_M_fd, SOL_PACKET, PACKET_RX_RING, &req, sizeof(struct tpacket_req)) < 0) {
return false;
}
if ((_M_buf = mmap(NULL, _M_size, PROT_READ | PROT_WRITE, MAP_SHARED, _M_fd, 0)) == MAP_FAILED) {
return false;
}
if ((_M_frames = (unsigned char**) malloc(_M_number_frames * sizeof(unsigned char*))) == NULL) {
return false;
}
for (size_t i = 0; i < _M_number_frames; i++) {
_M_frames[i] = (unsigned char*) _M_buf + (i * frame_size);
}
return _M_connections.create();
}
void sniffer::start()
{
_M_running = true;
struct tpacket_hdr* hdr = (struct tpacket_hdr*) _M_frames[_M_idx];
struct pollfd fds[2];
fds[0].fd = _M_fd;
fds[0].events = POLLIN;
fds[1].fd = _M_pipe;
fds[1].events = POLLIN;
do {
// If there is a new frame...
while (hdr->tp_status != TP_STATUS_KERNEL) {
// IP protocol?
const struct sockaddr_ll* addr = (const struct sockaddr_ll*) ((const unsigned char*) hdr + TPACKET_ALIGN(sizeof(struct tpacket_hdr)));
if (addr->sll_protocol == ntohs(ETH_P_IP)) {
if (!process_ip_packet((unsigned char*) hdr + hdr->tp_net, hdr->tp_len, hdr->tp_sec)) {
// Not enough memory.
_M_running = false;
return;
}
}
// Mark frame as free.
hdr->tp_status = TP_STATUS_KERNEL;
_M_idx = (_M_idx == _M_number_frames - 1) ? 0 : _M_idx + 1;
hdr = (struct tpacket_hdr*) _M_frames[_M_idx];
}
if (_M_handle_alarm) {
_M_connections.delete_expired(time(NULL));
_M_handle_alarm = false;
}
do {
fds[0].revents = 0;
fds[1].revents = 0;
poll(fds, 2, -1);
// If we have received data from the pipe...
if (fds[1].revents & POLLIN) {
char c;
while (read(_M_pipe, &c, 1) == 1) {
if (c == 1) {
_M_connections.save(CONNECTIONS_FILENAME, true);
}
}
}
} while ((_M_running) && (fds[0].revents == 0));
} while (_M_running);
#if DEBUG
struct tpacket_stats stats;
socklen_t optlen = sizeof(struct tpacket_stats);
if (getsockopt(_M_fd, SOL_PACKET, PACKET_STATISTICS, &stats, &optlen) == 0) {
printf("Received %u packets, dropped %u.\n", stats.tp_packets, stats.tp_drops);
}
#endif // DEBUG
}
bool sniffer::process_ip_packet(const unsigned char* pkt, size_t len, unsigned t)
{
if (len < sizeof(struct iphdr)) {
return true;
}
const struct iphdr* ip_header = (const struct iphdr*) pkt;
size_t iphdrlen = ip_header->ihl * 4;
if (len < iphdrlen) {
return true;
}
#if DEBUG
const unsigned char* saddr = (const unsigned char*) &ip_header->saddr;
const unsigned char* daddr = (const unsigned char*) &ip_header->daddr;
#endif // DEBUG
// TCP?
if (ip_header->protocol == 0x06) {
if (len < iphdrlen + sizeof(struct tcphdr)) {
return true;
}
const struct tcphdr* tcp_header = (const struct tcphdr*) (pkt + iphdrlen);
size_t tcphdrlen = tcp_header->doff * 4;
int payload;
if ((payload = len - (iphdrlen + tcphdrlen)) < 0) {
return true;
}
#if DEBUG
unsigned short srcport = ntohs(tcp_header->source);
unsigned short destport = ntohs(tcp_header->dest);
printf("[TCP] %u.%u.%u.%u:%u -> %u.%u.%u.%u:%u\n", saddr[0], saddr[1], saddr[2], saddr[3], srcport, daddr[0], daddr[1], daddr[2], daddr[3], destport);
#endif // DEBUG
bool first_payload;
if (!_M_connections.add(ip_header, tcp_header, payload, t, first_payload)) {
return false;
}
if (!first_payload) {
return true;
}
return analyzer::process(tcp_header, pkt + iphdrlen + tcphdrlen, payload);
} else if (ip_header->protocol == 0x11) {
// UDP.
if (len < iphdrlen + sizeof(struct udphdr)) {
return true;
}
#if DEBUG
const struct udphdr* udp_header = (const struct udphdr*) (pkt + iphdrlen);
unsigned short srcport = ntohs(udp_header->source);
unsigned short destport = ntohs(udp_header->dest);
printf("[UDP] %u.%u.%u.%u:%u -> %u.%u.%u.%u:%u\n", saddr[0], saddr[1], saddr[2], saddr[3], srcport, daddr[0], daddr[1], daddr[2], daddr[3], destport);
#endif // DEBUG
}
#if DEBUG
_M_connections.print();
#endif // DEBUG
return true;
}
<commit_msg>The pipe is opened now in blocking mode. If read() from the pipe returns 0, the pipe is closed and opened again.<commit_after>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include "sniffer.h"
#include "analyzer.h"
const size_t sniffer::MIN_SIZE = 1024 * 1024;
const size_t sniffer::MAX_SIZE = 1024 * 1024 * 1024;
const size_t sniffer::DEFAULT_SIZE = 100 * 1024 * 1024;
const char* sniffer::CONNECTIONS_FILENAME = "connections.txt";
const char* sniffer::PIPE_FILENAME = "/tmp/gsniffer.pipe";
sniffer::sniffer()
{
*_M_interface = 0;
_M_fd = -1;
_M_buf = MAP_FAILED;
_M_size = 0;
_M_frames = NULL;
_M_number_frames = 0;
_M_idx = 0;
_M_pipe = -1;
_M_running = false;
_M_handle_alarm = false;
}
sniffer::~sniffer()
{
if (_M_buf != MAP_FAILED) {
munmap(_M_buf, _M_size);
}
if (_M_fd != -1) {
close(_M_fd);
}
if (_M_frames) {
free(_M_frames);
}
if (_M_pipe != -1) {
close(_M_pipe);
}
unlink(PIPE_FILENAME);
}
bool sniffer::create(const char* interface, size_t size)
{
// Sanity check.
if ((size < MIN_SIZE) || (size > MAX_SIZE)) {
return false;
}
size_t len;
if ((len = strlen(interface)) >= sizeof(_M_interface)) {
return false;
}
// Create named pipe.
umask(0);
if ((mkfifo(PIPE_FILENAME, 0666) < 0) && (errno != EEXIST)) {
return false;
}
// Open named pipe.
if ((_M_pipe = open(PIPE_FILENAME, O_RDWR)) < 0) {
return false;
}
// Save interface.
memcpy(_M_interface, interface, len + 1);
// Create socket.
if ((_M_fd = socket(AF_PACKET, SOCK_DGRAM, 0)) < 0) {
return false;
}
// Get interface index.
struct ifreq ifr;
memcpy(ifr.ifr_name, interface, len + 1);
if (ioctl(_M_fd, SIOCGIFINDEX, &ifr) < 0) {
return false;
}
// Bind.
struct sockaddr_ll addr;
memset(&addr, 0, sizeof(struct sockaddr_ll));
addr.sll_family = AF_PACKET;
addr.sll_protocol = htons(ETH_P_ALL);
addr.sll_ifindex = ifr.ifr_ifindex;
addr.sll_pkttype = PACKET_HOST | PACKET_OUTGOING;
if (bind(_M_fd, (const struct sockaddr*) &addr, sizeof(struct sockaddr_ll)) < 0) {
return false;
}
// Calculate frame size.
size_t frame_size = TPACKET_ALIGN(TPACKET_HDRLEN) + TPACKET_ALIGN(ETH_DATA_LEN);
size_t n;
for (n = 8; n < frame_size; n *= 2);
frame_size = n;
// Calculate block size.
size_t block_size = getpagesize();
for (; block_size < frame_size; block_size *= 2);
// Calculate number of blocks and number of frames.
size_t block_count = size / block_size;
_M_size = block_count * block_size;
_M_number_frames = _M_size / frame_size;
struct tpacket_req req;
req.tp_block_size = block_size;
req.tp_block_nr = block_count;
req.tp_frame_size = frame_size;
req.tp_frame_nr = _M_number_frames;
// Setup PACKET_MMAP.
if (setsockopt(_M_fd, SOL_PACKET, PACKET_RX_RING, &req, sizeof(struct tpacket_req)) < 0) {
return false;
}
if ((_M_buf = mmap(NULL, _M_size, PROT_READ | PROT_WRITE, MAP_SHARED, _M_fd, 0)) == MAP_FAILED) {
return false;
}
if ((_M_frames = (unsigned char**) malloc(_M_number_frames * sizeof(unsigned char*))) == NULL) {
return false;
}
for (size_t i = 0; i < _M_number_frames; i++) {
_M_frames[i] = (unsigned char*) _M_buf + (i * frame_size);
}
return _M_connections.create();
}
void sniffer::start()
{
_M_running = true;
struct tpacket_hdr* hdr = (struct tpacket_hdr*) _M_frames[_M_idx];
struct pollfd fds[2];
fds[0].fd = _M_fd;
fds[0].events = POLLIN;
fds[1].fd = _M_pipe;
fds[1].events = POLLIN;
do {
// If there is a new frame...
while (hdr->tp_status != TP_STATUS_KERNEL) {
// IP protocol?
const struct sockaddr_ll* addr = (const struct sockaddr_ll*) ((const unsigned char*) hdr + TPACKET_ALIGN(sizeof(struct tpacket_hdr)));
if (addr->sll_protocol == ntohs(ETH_P_IP)) {
if (!process_ip_packet((unsigned char*) hdr + hdr->tp_net, hdr->tp_len, hdr->tp_sec)) {
// Not enough memory.
_M_running = false;
return;
}
}
// Mark frame as free.
hdr->tp_status = TP_STATUS_KERNEL;
_M_idx = (_M_idx == _M_number_frames - 1) ? 0 : _M_idx + 1;
hdr = (struct tpacket_hdr*) _M_frames[_M_idx];
}
if (_M_handle_alarm) {
_M_connections.delete_expired(time(NULL));
_M_handle_alarm = false;
}
do {
fds[0].revents = 0;
fds[1].revents = 0;
poll(fds, 2, -1);
// If we have received data from the pipe...
if (fds[1].revents & POLLIN) {
char c;
ssize_t ret;
if ((ret = read(_M_pipe, &c, 1)) == 0) {
close(_M_pipe);
if ((_M_pipe = open(PIPE_FILENAME, O_RDWR)) < 0) {
_M_running = false;
}
} else if (ret == 1) {
if (c == 1) {
_M_connections.save(CONNECTIONS_FILENAME, true);
}
}
}
} while ((_M_running) && (fds[0].revents == 0));
} while (_M_running);
#if DEBUG
struct tpacket_stats stats;
socklen_t optlen = sizeof(struct tpacket_stats);
if (getsockopt(_M_fd, SOL_PACKET, PACKET_STATISTICS, &stats, &optlen) == 0) {
printf("Received %u packets, dropped %u.\n", stats.tp_packets, stats.tp_drops);
}
#endif // DEBUG
}
bool sniffer::process_ip_packet(const unsigned char* pkt, size_t len, unsigned t)
{
if (len < sizeof(struct iphdr)) {
return true;
}
const struct iphdr* ip_header = (const struct iphdr*) pkt;
size_t iphdrlen = ip_header->ihl * 4;
if (len < iphdrlen) {
return true;
}
#if DEBUG
const unsigned char* saddr = (const unsigned char*) &ip_header->saddr;
const unsigned char* daddr = (const unsigned char*) &ip_header->daddr;
#endif // DEBUG
// TCP?
if (ip_header->protocol == 0x06) {
if (len < iphdrlen + sizeof(struct tcphdr)) {
return true;
}
const struct tcphdr* tcp_header = (const struct tcphdr*) (pkt + iphdrlen);
size_t tcphdrlen = tcp_header->doff * 4;
int payload;
if ((payload = len - (iphdrlen + tcphdrlen)) < 0) {
return true;
}
#if DEBUG
unsigned short srcport = ntohs(tcp_header->source);
unsigned short destport = ntohs(tcp_header->dest);
printf("[TCP] %u.%u.%u.%u:%u -> %u.%u.%u.%u:%u\n", saddr[0], saddr[1], saddr[2], saddr[3], srcport, daddr[0], daddr[1], daddr[2], daddr[3], destport);
#endif // DEBUG
bool first_payload;
if (!_M_connections.add(ip_header, tcp_header, payload, t, first_payload)) {
return false;
}
if (!first_payload) {
return true;
}
return analyzer::process(tcp_header, pkt + iphdrlen + tcphdrlen, payload);
} else if (ip_header->protocol == 0x11) {
// UDP.
if (len < iphdrlen + sizeof(struct udphdr)) {
return true;
}
#if DEBUG
const struct udphdr* udp_header = (const struct udphdr*) (pkt + iphdrlen);
unsigned short srcport = ntohs(udp_header->source);
unsigned short destport = ntohs(udp_header->dest);
printf("[UDP] %u.%u.%u.%u:%u -> %u.%u.%u.%u:%u\n", saddr[0], saddr[1], saddr[2], saddr[3], srcport, daddr[0], daddr[1], daddr[2], daddr[3], destport);
#endif // DEBUG
}
#if DEBUG
_M_connections.print();
#endif // DEBUG
return true;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* 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 "mediawindowbase_impl.hxx"
#include <avmedia/mediaitem.hxx>
#include "mediamisc.hxx"
#include "mediawindow.hrc"
#include <tools/urlobj.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/media/XManager.hpp>
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HDL_
#include <com/sun/star/lang/XComponent.hdl>
#endif
#define MEDIA_TIMER_TIMEOUT 100
using namespace ::com::sun::star;
namespace avmedia { namespace priv {
// -----------------------
// - MediaWindowBaseImpl -
// -----------------------
struct ServiceManager
{
const char* pServiceName;
sal_Bool bIsJavaBased;
};
// ---------------------------------------------------------------------
MediaWindowBaseImpl::MediaWindowBaseImpl( MediaWindow* pMediaWindow ) :
mpMediaWindow( pMediaWindow ),
mbIsMediaWindowJavaBased( sal_False )
{
}
// ---------------------------------------------------------------------
MediaWindowBaseImpl::~MediaWindowBaseImpl()
{
uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
}
// -------------------------------------------------------------------------
uno::Reference< media::XPlayer > MediaWindowBaseImpl::createPlayer( const ::rtl::OUString& rURL, sal_Bool& rbJavaBased )
{
uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
uno::Reference< media::XPlayer > xPlayer;
rbJavaBased = sal_False;
if( xFactory.is() )
{
static const ServiceManager aServiceManagers[] =
{
{ "AVMEDIA_MANAGER_SERVICE_NAME", AVMEDIA_MANAGER_SERVICE_IS_JAVABASED },
{ "AVMEDIA_MANAGER_SERVICE_NAME_FALLBACK1", AVMEDIA_MANAGER_SERVICE_IS_JAVABASED_FALLBACK1 }
};
uno::Reference< media::XManager > xManager;
for( sal_uInt32 i = 0; ( i < ( sizeof( aServiceManagers ) / sizeof( ServiceManager ) ) ) && !xManager.is(); ++i )
{
const String aServiceName( aServiceManagers[ i ].pServiceName, RTL_TEXTENCODING_ASCII_US );
if( aServiceName.Len() )
{
try
{
xManager = uno::Reference< media::XManager >( xFactory->createInstance( aServiceName ),
uno::UNO_QUERY );
if( xManager.is() )
{
xPlayer = uno::Reference< media::XPlayer >( xManager->createPlayer( rURL ),
uno::UNO_QUERY );
}
}
catch( ... )
{
}
}
if( !xPlayer.is() )
{
xManager.clear();
}
else
{
rbJavaBased = aServiceManagers[ i ].bIsJavaBased;
}
}
}
return xPlayer;
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setURL( const ::rtl::OUString& rURL )
{
if( rURL != getURL() )
{
INetURLObject aURL( maFileURL = rURL );
if( mxPlayer.is() )
mxPlayer->stop();
if( mxPlayerWindow.is() )
{
mxPlayerWindow->setVisible( false );
mxPlayerWindow.clear();
}
mxPlayer.clear();
if( aURL.GetProtocol() != INET_PROT_NOT_VALID )
maFileURL = aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS );
mxPlayer = createPlayer( maFileURL, mbIsMediaWindowJavaBased );
onURLChanged();
}
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::onURLChanged()
{
}
// ---------------------------------------------------------------------
const ::rtl::OUString& MediaWindowBaseImpl::getURL() const
{
return maFileURL;
}
// ---------------------------------------------------------------------
bool MediaWindowBaseImpl::isValid() const
{
return( getPlayer().is() );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::stopPlayingInternal( bool bStop )
{
if( isPlaying() )
{
bStop ? mxPlayer->stop() : mxPlayer->start();
}
}
// ---------------------------------------------------------------------
MediaWindow* MediaWindowBaseImpl::getMediaWindow() const
{
return mpMediaWindow;
}
// ---------------------------------------------------------------------
uno::Reference< media::XPlayer > MediaWindowBaseImpl::getPlayer() const
{
return mxPlayer;
}
// ---------------------------------------------------------------------
uno::Reference< media::XPlayerWindow > MediaWindowBaseImpl::getPlayerWindow() const
{
return mxPlayerWindow;
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setPlayerWindow( const uno::Reference< media::XPlayerWindow >& rxPlayerWindow )
{
mxPlayerWindow = rxPlayerWindow;
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::cleanUp()
{
if( mxPlayer.is() )
{
mxPlayer->stop();
uno::Reference< lang::XComponent > xComponent( mxPlayer, uno::UNO_QUERY );
if( xComponent.is() )
xComponent->dispose();
mxPlayer.clear();
}
mpMediaWindow = NULL;
}
// ---------------------------------------------------------------------
bool MediaWindowBaseImpl::hasPreferredSize() const
{
return( mxPlayerWindow.is() );
}
// ---------------------------------------------------------------------
Size MediaWindowBaseImpl::getPreferredSize() const
{
Size aRet;
if( mxPlayer.is() )
{
awt::Size aPrefSize( mxPlayer->getPreferredPlayerWindowSize() );
aRet.Width() = aPrefSize.Width;
aRet.Height() = aPrefSize.Height;
}
return aRet;
}
// ---------------------------------------------------------------------
bool MediaWindowBaseImpl::setZoom( ::com::sun::star::media::ZoomLevel eLevel )
{
return( mxPlayerWindow.is() ? mxPlayerWindow->setZoomLevel( eLevel ) : false );
}
// -------------------------------------------------------------------------
::com::sun::star::media::ZoomLevel MediaWindowBaseImpl::getZoom() const
{
return( mxPlayerWindow.is() ? mxPlayerWindow->getZoomLevel() : ::com::sun::star::media::ZoomLevel_NOT_AVAILABLE );
}
// ---------------------------------------------------------------------
bool MediaWindowBaseImpl::start()
{
return( mxPlayer.is() ? ( mxPlayer->start(), true ) : false );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::stop()
{
if( mxPlayer.is() )
mxPlayer->stop();
}
// ---------------------------------------------------------------------
bool MediaWindowBaseImpl::isPlaying() const
{
return( mxPlayer.is() && mxPlayer->isPlaying() );
}
// ---------------------------------------------------------------------
double MediaWindowBaseImpl::getDuration() const
{
return( mxPlayer.is() ? mxPlayer->getDuration() : 0.0 );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setMediaTime( double fTime )
{
if( mxPlayer.is() )
mxPlayer->setMediaTime( fTime );
}
// ---------------------------------------------------------------------
double MediaWindowBaseImpl::getMediaTime() const
{
return( mxPlayer.is() ? mxPlayer->getMediaTime() : 0.0 );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setStopTime( double fTime )
{
if( mxPlayer.is() )
mxPlayer->setStopTime( fTime );
}
// ---------------------------------------------------------------------
double MediaWindowBaseImpl::getStopTime() const
{
return( mxPlayer.is() ? mxPlayer->getStopTime() : 0.0 );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setRate( double fRate )
{
if( mxPlayer.is() )
mxPlayer->setRate( fRate );
}
// ---------------------------------------------------------------------
double MediaWindowBaseImpl::getRate() const
{
return( mxPlayer.is() ? mxPlayer->getRate() : 0.0 );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setPlaybackLoop( bool bSet )
{
if( mxPlayer.is() )
mxPlayer->setPlaybackLoop( bSet );
}
// ---------------------------------------------------------------------
bool MediaWindowBaseImpl::isPlaybackLoop() const
{
return( mxPlayer.is() ? mxPlayer->isPlaybackLoop() : false );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setMute( bool bSet )
{
if( mxPlayer.is() )
mxPlayer->setMute( bSet );
}
// ---------------------------------------------------------------------
bool MediaWindowBaseImpl::isMute() const
{
return( mxPlayer.is() ? mxPlayer->isMute() : false );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setVolumeDB( sal_Int16 nVolumeDB )
{
if( mxPlayer.is() )
mxPlayer->setVolumeDB( nVolumeDB );
}
// ---------------------------------------------------------------------
sal_Int16 MediaWindowBaseImpl::getVolumeDB() const
{
return( mxPlayer.is() ? mxPlayer->getVolumeDB() : 0 );
}
// -------------------------------------------------------------------------
void MediaWindowBaseImpl::updateMediaItem( MediaItem& rItem ) const
{
if( isPlaying() )
rItem.setState( ( getRate() > 1.0 ) ? MEDIASTATE_PLAYFFW : MEDIASTATE_PLAY );
else
rItem.setState( ( 0.0 == getMediaTime() ) ? MEDIASTATE_STOP : MEDIASTATE_PAUSE );
rItem.setDuration( getDuration() );
rItem.setTime( getMediaTime() );
rItem.setLoop( isPlaybackLoop() );
rItem.setMute( isMute() );
rItem.setVolumeDB( getVolumeDB() );
rItem.setZoom( getZoom() );
rItem.setURL( getURL() );
}
// -------------------------------------------------------------------------
void MediaWindowBaseImpl::executeMediaItem( const MediaItem& rItem )
{
const sal_uInt32 nMaskSet = rItem.getMaskSet();
// set URL first
if( nMaskSet & AVMEDIA_SETMASK_URL )
setURL( rItem.getURL() );
// set different states next
if( nMaskSet & AVMEDIA_SETMASK_TIME )
setMediaTime( ::std::min( rItem.getTime(), getDuration() ) );
if( nMaskSet & AVMEDIA_SETMASK_LOOP )
setPlaybackLoop( rItem.isLoop() );
if( nMaskSet & AVMEDIA_SETMASK_MUTE )
setMute( rItem.isMute() );
if( nMaskSet & AVMEDIA_SETMASK_VOLUMEDB )
setVolumeDB( rItem.getVolumeDB() );
if( nMaskSet & AVMEDIA_SETMASK_ZOOM )
setZoom( rItem.getZoom() );
// set play state at last
if( nMaskSet & AVMEDIA_SETMASK_STATE )
{
switch( rItem.getState() )
{
case( MEDIASTATE_PLAY ):
case( MEDIASTATE_PLAYFFW ):
{
/*
const double fNewRate = ( ( MEDIASTATE_PLAYFFW == rItem.getState() ) ? AVMEDIA_FFW_PLAYRATE : 1.0 );
if( getRate() != fNewRate )
setRate( fNewRate );
*/
if( !isPlaying() )
start();
}
break;
case( MEDIASTATE_PAUSE ):
{
if( isPlaying() )
stop();
}
break;
case( MEDIASTATE_STOP ):
{
if( isPlaying() )
{
setMediaTime( 0.0 );
stop();
setMediaTime( 0.0 );
}
}
break;
}
}
}
} // namespace priv
} // namespace avemdia
<commit_msg>avmedia101: code cleanup<commit_after>/*************************************************************************
*
* 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 "mediawindowbase_impl.hxx"
#include <avmedia/mediaitem.hxx>
#include "mediamisc.hxx"
#include "mediawindow.hrc"
#include <tools/urlobj.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/media/XManager.hpp>
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HDL_
#include <com/sun/star/lang/XComponent.hdl>
#endif
#define MEDIA_TIMER_TIMEOUT 100
using namespace ::com::sun::star;
namespace avmedia { namespace priv {
// -----------------------
// - MediaWindowBaseImpl -
// -----------------------
struct ServiceManager
{
const char* pServiceName;
sal_Bool bIsJavaBased;
};
// ---------------------------------------------------------------------
MediaWindowBaseImpl::MediaWindowBaseImpl( MediaWindow* pMediaWindow ) :
mpMediaWindow( pMediaWindow ),
mbIsMediaWindowJavaBased( sal_False )
{
}
// ---------------------------------------------------------------------
MediaWindowBaseImpl::~MediaWindowBaseImpl()
{
uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
}
// -------------------------------------------------------------------------
uno::Reference< media::XPlayer > MediaWindowBaseImpl::createPlayer( const ::rtl::OUString& rURL, sal_Bool& rbJavaBased )
{
uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
uno::Reference< media::XPlayer > xPlayer;
rbJavaBased = sal_False;
if( xFactory.is() )
{
static const ServiceManager aServiceManagers[] =
{
{ AVMEDIA_MANAGER_SERVICE_NAME, AVMEDIA_MANAGER_SERVICE_IS_JAVABASED },
{ AVMEDIA_MANAGER_SERVICE_NAME_FALLBACK1, AVMEDIA_MANAGER_SERVICE_IS_JAVABASED_FALLBACK1 }
};
for( sal_uInt32 i = 0; !xPlayer.is() && ( i < ( sizeof( aServiceManagers ) / sizeof( ServiceManager ) ) ); ++i )
{
const String aServiceName( aServiceManagers[ i ].pServiceName, RTL_TEXTENCODING_ASCII_US );
if( aServiceName.Len() )
{
OSL_TRACE( "Trying to create media manager service %s", aServiceManagers[ i ].pServiceName );
try
{
uno::Reference< media::XManager > xManager( xFactory->createInstance( aServiceName ), uno::UNO_QUERY );
if( xManager.is() )
{
xPlayer = uno::Reference< media::XPlayer >( xManager->createPlayer( rURL ), uno::UNO_QUERY );
}
}
catch( ... )
{
}
}
if( xPlayer.is() )
{
rbJavaBased = aServiceManagers[ i ].bIsJavaBased;
}
}
}
return xPlayer;
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setURL( const ::rtl::OUString& rURL )
{
if( rURL != getURL() )
{
INetURLObject aURL( maFileURL = rURL );
if( mxPlayer.is() )
mxPlayer->stop();
if( mxPlayerWindow.is() )
{
mxPlayerWindow->setVisible( false );
mxPlayerWindow.clear();
}
mxPlayer.clear();
if( aURL.GetProtocol() != INET_PROT_NOT_VALID )
maFileURL = aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS );
mxPlayer = createPlayer( maFileURL, mbIsMediaWindowJavaBased );
onURLChanged();
}
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::onURLChanged()
{
}
// ---------------------------------------------------------------------
const ::rtl::OUString& MediaWindowBaseImpl::getURL() const
{
return maFileURL;
}
// ---------------------------------------------------------------------
bool MediaWindowBaseImpl::isValid() const
{
return( getPlayer().is() );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::stopPlayingInternal( bool bStop )
{
if( isPlaying() )
{
bStop ? mxPlayer->stop() : mxPlayer->start();
}
}
// ---------------------------------------------------------------------
MediaWindow* MediaWindowBaseImpl::getMediaWindow() const
{
return mpMediaWindow;
}
// ---------------------------------------------------------------------
uno::Reference< media::XPlayer > MediaWindowBaseImpl::getPlayer() const
{
return mxPlayer;
}
// ---------------------------------------------------------------------
uno::Reference< media::XPlayerWindow > MediaWindowBaseImpl::getPlayerWindow() const
{
return mxPlayerWindow;
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setPlayerWindow( const uno::Reference< media::XPlayerWindow >& rxPlayerWindow )
{
mxPlayerWindow = rxPlayerWindow;
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::cleanUp()
{
if( mxPlayer.is() )
{
mxPlayer->stop();
uno::Reference< lang::XComponent > xComponent( mxPlayer, uno::UNO_QUERY );
if( xComponent.is() )
xComponent->dispose();
mxPlayer.clear();
}
mpMediaWindow = NULL;
}
// ---------------------------------------------------------------------
bool MediaWindowBaseImpl::hasPreferredSize() const
{
return( mxPlayerWindow.is() );
}
// ---------------------------------------------------------------------
Size MediaWindowBaseImpl::getPreferredSize() const
{
Size aRet;
if( mxPlayer.is() )
{
awt::Size aPrefSize( mxPlayer->getPreferredPlayerWindowSize() );
aRet.Width() = aPrefSize.Width;
aRet.Height() = aPrefSize.Height;
}
return aRet;
}
// ---------------------------------------------------------------------
bool MediaWindowBaseImpl::setZoom( ::com::sun::star::media::ZoomLevel eLevel )
{
return( mxPlayerWindow.is() ? mxPlayerWindow->setZoomLevel( eLevel ) : false );
}
// -------------------------------------------------------------------------
::com::sun::star::media::ZoomLevel MediaWindowBaseImpl::getZoom() const
{
return( mxPlayerWindow.is() ? mxPlayerWindow->getZoomLevel() : ::com::sun::star::media::ZoomLevel_NOT_AVAILABLE );
}
// ---------------------------------------------------------------------
bool MediaWindowBaseImpl::start()
{
return( mxPlayer.is() ? ( mxPlayer->start(), true ) : false );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::stop()
{
if( mxPlayer.is() )
mxPlayer->stop();
}
// ---------------------------------------------------------------------
bool MediaWindowBaseImpl::isPlaying() const
{
return( mxPlayer.is() && mxPlayer->isPlaying() );
}
// ---------------------------------------------------------------------
double MediaWindowBaseImpl::getDuration() const
{
return( mxPlayer.is() ? mxPlayer->getDuration() : 0.0 );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setMediaTime( double fTime )
{
if( mxPlayer.is() )
mxPlayer->setMediaTime( fTime );
}
// ---------------------------------------------------------------------
double MediaWindowBaseImpl::getMediaTime() const
{
return( mxPlayer.is() ? mxPlayer->getMediaTime() : 0.0 );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setStopTime( double fTime )
{
if( mxPlayer.is() )
mxPlayer->setStopTime( fTime );
}
// ---------------------------------------------------------------------
double MediaWindowBaseImpl::getStopTime() const
{
return( mxPlayer.is() ? mxPlayer->getStopTime() : 0.0 );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setRate( double fRate )
{
if( mxPlayer.is() )
mxPlayer->setRate( fRate );
}
// ---------------------------------------------------------------------
double MediaWindowBaseImpl::getRate() const
{
return( mxPlayer.is() ? mxPlayer->getRate() : 0.0 );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setPlaybackLoop( bool bSet )
{
if( mxPlayer.is() )
mxPlayer->setPlaybackLoop( bSet );
}
// ---------------------------------------------------------------------
bool MediaWindowBaseImpl::isPlaybackLoop() const
{
return( mxPlayer.is() ? mxPlayer->isPlaybackLoop() : false );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setMute( bool bSet )
{
if( mxPlayer.is() )
mxPlayer->setMute( bSet );
}
// ---------------------------------------------------------------------
bool MediaWindowBaseImpl::isMute() const
{
return( mxPlayer.is() ? mxPlayer->isMute() : false );
}
// ---------------------------------------------------------------------
void MediaWindowBaseImpl::setVolumeDB( sal_Int16 nVolumeDB )
{
if( mxPlayer.is() )
mxPlayer->setVolumeDB( nVolumeDB );
}
// ---------------------------------------------------------------------
sal_Int16 MediaWindowBaseImpl::getVolumeDB() const
{
return( mxPlayer.is() ? mxPlayer->getVolumeDB() : 0 );
}
// -------------------------------------------------------------------------
void MediaWindowBaseImpl::updateMediaItem( MediaItem& rItem ) const
{
if( isPlaying() )
rItem.setState( ( getRate() > 1.0 ) ? MEDIASTATE_PLAYFFW : MEDIASTATE_PLAY );
else
rItem.setState( ( 0.0 == getMediaTime() ) ? MEDIASTATE_STOP : MEDIASTATE_PAUSE );
rItem.setDuration( getDuration() );
rItem.setTime( getMediaTime() );
rItem.setLoop( isPlaybackLoop() );
rItem.setMute( isMute() );
rItem.setVolumeDB( getVolumeDB() );
rItem.setZoom( getZoom() );
rItem.setURL( getURL() );
}
// -------------------------------------------------------------------------
void MediaWindowBaseImpl::executeMediaItem( const MediaItem& rItem )
{
const sal_uInt32 nMaskSet = rItem.getMaskSet();
// set URL first
if( nMaskSet & AVMEDIA_SETMASK_URL )
setURL( rItem.getURL() );
// set different states next
if( nMaskSet & AVMEDIA_SETMASK_TIME )
setMediaTime( ::std::min( rItem.getTime(), getDuration() ) );
if( nMaskSet & AVMEDIA_SETMASK_LOOP )
setPlaybackLoop( rItem.isLoop() );
if( nMaskSet & AVMEDIA_SETMASK_MUTE )
setMute( rItem.isMute() );
if( nMaskSet & AVMEDIA_SETMASK_VOLUMEDB )
setVolumeDB( rItem.getVolumeDB() );
if( nMaskSet & AVMEDIA_SETMASK_ZOOM )
setZoom( rItem.getZoom() );
// set play state at last
if( nMaskSet & AVMEDIA_SETMASK_STATE )
{
switch( rItem.getState() )
{
case( MEDIASTATE_PLAY ):
case( MEDIASTATE_PLAYFFW ):
{
/*
const double fNewRate = ( ( MEDIASTATE_PLAYFFW == rItem.getState() ) ? AVMEDIA_FFW_PLAYRATE : 1.0 );
if( getRate() != fNewRate )
setRate( fNewRate );
*/
if( !isPlaying() )
start();
}
break;
case( MEDIASTATE_PAUSE ):
{
if( isPlaying() )
stop();
}
break;
case( MEDIASTATE_STOP ):
{
if( isPlaying() )
{
setMediaTime( 0.0 );
stop();
setMediaTime( 0.0 );
}
}
break;
}
}
}
} // namespace priv
} // namespace avemdia
<|endoftext|> |
<commit_before>#pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
/** @file Translates between various similiar objects */
#include "StringUtils.hpp"
#include "RinexObsID.hpp"
#include "RinexConverters.hpp"
using namespace std;
namespace gpstk
{
short snr2ssi(float x)
{
// These values were obtained from the comments in a RINEX obs file that was
// generated from a TurboBinary file recorded on an AOA Benchmark receiver
if (x>316) return 9;
if (x>100) return 8;
if (x>31.6) return 7;
if (x>10) return 6;
if (x>3.2) return 5;
if (x>0) return 4;
return 0;
}
RinexObsData::RinexObsTypeMap makeRinexObsTypeMap(const MDPObsEpoch& moe) throw()
{
gpstk::RinexObsData::RinexObsTypeMap rotm;
MDPObsEpoch::ObsMap ol=moe.obs;
MDPObsEpoch::ObsMap::const_iterator j;
// The C1 Rinex obs is easy
j = ol.find(MDPObsEpoch::ObsKey(ccL1,rcCA));
if (j!=ol.end())
{
rotm[gpstk::RinexObsHeader::C1].data = j->second.pseudorange;
rotm[gpstk::RinexObsHeader::C1].lli = j->second.lockCount ? 0 : 1;
rotm[gpstk::RinexObsHeader::C1].ssi = snr2ssi(j->second.snr);
rotm[gpstk::RinexObsHeader::L1].data = j->second.phase;
rotm[gpstk::RinexObsHeader::L1].lli = j->second.lockCount ? 0 : 1;
rotm[gpstk::RinexObsHeader::L1].ssi = snr2ssi(j->second.snr);
rotm[gpstk::RinexObsHeader::D1].data = j->second.doppler;
rotm[gpstk::RinexObsHeader::D1].lli = j->second.lockCount ? 0 : 1;
rotm[gpstk::RinexObsHeader::D1].ssi = snr2ssi(j->second.snr);
rotm[gpstk::RinexObsHeader::S1].data = j->second.snr;
}
// Now get the P1, L1, D1, S1 obs
j = ol.find(MDPObsEpoch::ObsKey(ccL1, rcYcode));
if (j == ol.end())
j = ol.find(MDPObsEpoch::ObsKey(ccL1, rcPcode));
if (j == ol.end())
j = ol.find(MDPObsEpoch::ObsKey(ccL1, rcCodeless));
if (j != ol.end())
{
rotm[gpstk::RinexObsHeader::P1].data = j->second.pseudorange;
rotm[gpstk::RinexObsHeader::P1].lli = j->second.lockCount ? 0 : 1;
rotm[gpstk::RinexObsHeader::P1].ssi = snr2ssi(j->second.snr);
rotm[gpstk::RinexObsHeader::L1].data = j->second.phase;
rotm[gpstk::RinexObsHeader::L1].lli = j->second.lockCount ? 0 : 1;
rotm[gpstk::RinexObsHeader::L1].ssi = snr2ssi(j->second.snr);
rotm[gpstk::RinexObsHeader::D1].data = j->second.doppler;
rotm[gpstk::RinexObsHeader::D1].lli = j->second.lockCount ? 0 : 1;
rotm[gpstk::RinexObsHeader::D1].ssi = snr2ssi(j->second.snr);
rotm[gpstk::RinexObsHeader::S1].data = j->second.snr;
}
// Now get the P2, L2, D2, S2 obs
j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcYcode));
if (j == ol.end())
j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcPcode));
if (j == ol.end())
j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCodeless));
if (j != ol.end())
{
rotm[gpstk::RinexObsHeader::P2].data = j->second.pseudorange;
rotm[gpstk::RinexObsHeader::P2].lli = j->second.lockCount ? 0 : 1;
rotm[gpstk::RinexObsHeader::P2].ssi = snr2ssi(j->second.snr);
rotm[gpstk::RinexObsHeader::L2].data = j->second.phase;
rotm[gpstk::RinexObsHeader::L2].lli = j->second.lockCount ? 0 : 1;
rotm[gpstk::RinexObsHeader::L2].ssi = snr2ssi(j->second.snr);
rotm[gpstk::RinexObsHeader::D2].data = j->second.doppler;
rotm[gpstk::RinexObsHeader::D2].lli = j->second.lockCount ? 0 : 1;
rotm[gpstk::RinexObsHeader::D2].ssi = snr2ssi(j->second.snr);
rotm[gpstk::RinexObsHeader::S2].data = j->second.snr;
}
// Now get the C2
j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCM));
if (j == ol.end())
j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCL));
if (j == ol.end())
j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCMCL));
if (j != ol.end())
{
rotm[gpstk::RinexObsHeader::C2].data = j->second.pseudorange;
rotm[gpstk::RinexObsHeader::C2].lli = j->second.lockCount ? 0 : 1;
rotm[gpstk::RinexObsHeader::C2].ssi = snr2ssi(j->second.snr);
}
return rotm;
}
RinexObsData makeRinexObsData(const gpstk::MDPEpoch& mdp)
{
RinexObsData rod;
rod.clockOffset=0;
rod.numSvs = mdp.size();
rod.epochFlag = 0;
rod.time = mdp.begin()->second.time;
for (MDPEpoch::const_iterator i=mdp.begin(); i!=mdp.end(); i++)
{
const MDPObsEpoch& moe = i->second;
gpstk::SatID svid(moe.prn, gpstk::SatID::systemGPS);
rod.obs[svid] = makeRinexObsTypeMap(moe);
}
return rod;
}
// Try to convert the given pages into an EngAlmanc object. Returns true
// upon success. This routine is tuned for two different types of nav data.
//
// The first is for a receiver that outputs all 4/5 subframes from a given
// code/carrier. Basically it looks for a 12.5 minute cycle that starts
// with page 1 from subframe 4. It makes sure that there hasn't been a
// cutover during it by checking that all sv pages (i.e. svid 1-32) have
// the same toa as the last page 25 (svid 51). This mode is the default and
// is set with the requireFull parameter.
//
// The second is for a receiver that only puts out a set of 4/5 subframes
// that "should" be a complete almanac. Note that it doesn't output pages
// for SVs that are set to the default data.
//
// The only receiver that this has been tested on is the Ashtech Z(Y)12.
//
// In the IS-GPS-200D, see pages 72-79, 82, 105
bool makeEngAlmanac(EngAlmanac& alm,
const AlmanacPages& pages,
bool requireFull) throw()
{
AlmanacPages::const_iterator sf4p1 = pages.find(SubframePage(4, 1));
AlmanacPages::const_iterator sf4p18 = pages.find(SubframePage(4, 18));
AlmanacPages::const_iterator sf4p25 = pages.find(SubframePage(4, 25));
AlmanacPages::const_iterator sf5p25 = pages.find(SubframePage(5, 25));
// These pages are required for a reasonable alm
if (sf4p18==pages.end() || sf4p25==pages.end() || sf5p25==pages.end())
return false;
long sf4p1sow=0;
if (requireFull)
{
if (sf4p1==pages.end())
return false;
else
sf4p1sow = sf4p1->second.getHOWTime();
}
int week=sf4p18->second.time.GPSfullweek();
for (int p=1; p<=25; p++)
{
for (int sf=4; sf<=5; sf++)
{
AlmanacPages::const_iterator i = pages.find(SubframePage(sf, p));
if (i == pages.end())
{
if (requireFull)
return false;
else
continue;
}
// All pages have to be contingious for the full alm mode.
if (requireFull)
{
long sow = i->second.getHOWTime();
if (sow != sf4p1sow + (sf-4)*6 + (p-1)*30)
return false;
}
long sfa[10];
long long_sfa[10];
i->second.fillArray(sfa);
copy( &sfa[0], &sfa[10], long_sfa);
if (!alm.addSubframe(long_sfa, week))
return false;
}
}
return true;
}
// Try to convert the given pages into an EngEphemeris object. Returns true
// upon success.
bool makeEngEphemeris(EngEphemeris& eph, const EphemerisPages& pages)
{
EphemerisPages::const_iterator sf[4];
sf[1] = pages.find(1);
if (sf[1] == pages.end())
return false;
sf[2] = pages.find(2);
if (sf[2] == pages.end())
return false;
sf[3] = pages.find(3);
if (sf[3] == pages.end())
return false;
long t1 = sf[1]->second.getHOWTime();
long t2 = sf[2]->second.getHOWTime();
long t3 = sf[3]->second.getHOWTime();
if (t2 != t1+6 || t3 != t1+12)
return false;
int prn = sf[1]->second.prn;
int week = sf[1]->second.time.GPSfullweek();
long sfa[10];
long long_sfa[10];
for (int i=1; i<=3; i++)
{
sf[i]->second.fillArray(sfa);
for( int j = 0; j < 10; j++ )
long_sfa[j] = static_cast<long>( sfa[j] );
if (!eph.addSubframe(long_sfa, week, prn, 0))
return false;
}
if (eph.isData(1) && eph.isData(2) && eph.isData(3))
return true;
return false;
}
} // end of namespace gpstk
<commit_msg>lli/ssi code cleanup<commit_after>#pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
/** @file Translates between various similiar objects */
#include "StringUtils.hpp"
#include "RinexObsID.hpp"
#include "RinexConverters.hpp"
using namespace std;
namespace gpstk
{
short snr2ssi(float x)
{
// These values were obtained from the comments in a RINEX obs file that was
// generated from a TurboBinary file recorded on an AOA Benchmark receiver
if (x>316) return 9;
if (x>100) return 8;
if (x>31.6) return 7;
if (x>10) return 6;
if (x>3.2) return 5;
if (x>0) return 4;
return 0;
}
RinexObsData::RinexObsTypeMap makeRinexObsTypeMap(const MDPObsEpoch& moe) throw()
{
gpstk::RinexObsData::RinexObsTypeMap rotm;
MDPObsEpoch::ObsMap ol=moe.obs;
MDPObsEpoch::ObsMap::const_iterator j;
// The C1 Rinex obs is easy
j = ol.find(MDPObsEpoch::ObsKey(ccL1,rcCA));
if (j!=ol.end())
{
short lli = j->second.lockCount ? 0 : 1;
short ssi = snr2ssi(j->second.snr);
rotm[gpstk::RinexObsHeader::C1].data = j->second.pseudorange;
rotm[gpstk::RinexObsHeader::C1].lli = lli;
rotm[gpstk::RinexObsHeader::C1].ssi = ssi;
rotm[gpstk::RinexObsHeader::L1].data = j->second.phase;
rotm[gpstk::RinexObsHeader::L1].lli = lli;
rotm[gpstk::RinexObsHeader::L1].ssi = ssi;
rotm[gpstk::RinexObsHeader::D1].data = j->second.doppler;
rotm[gpstk::RinexObsHeader::D1].lli = lli;
rotm[gpstk::RinexObsHeader::D1].ssi = ssi;
rotm[gpstk::RinexObsHeader::S1].data = j->second.snr;
}
// Now get the P1, L1, D1, S1 obs
j = ol.find(MDPObsEpoch::ObsKey(ccL1, rcYcode));
if (j == ol.end())
j = ol.find(MDPObsEpoch::ObsKey(ccL1, rcPcode));
if (j == ol.end())
j = ol.find(MDPObsEpoch::ObsKey(ccL1, rcCodeless));
if (j != ol.end())
{
short lli = j->second.lockCount ? 0 : 1;
short ssi = snr2ssi(j->second.snr);
rotm[gpstk::RinexObsHeader::P1].data = j->second.pseudorange;
rotm[gpstk::RinexObsHeader::P1].lli = lli;
rotm[gpstk::RinexObsHeader::P1].ssi = ssi;
rotm[gpstk::RinexObsHeader::L1].data = j->second.phase;
rotm[gpstk::RinexObsHeader::L1].lli = lli;
rotm[gpstk::RinexObsHeader::L1].ssi = ssi;
rotm[gpstk::RinexObsHeader::D1].data = j->second.doppler;
rotm[gpstk::RinexObsHeader::D1].lli = lli;
rotm[gpstk::RinexObsHeader::D1].ssi = ssi;
rotm[gpstk::RinexObsHeader::S1].data = j->second.snr;
}
// Now get the P2, L2, D2, S2 obs
j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcYcode));
if (j == ol.end())
j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcPcode));
if (j == ol.end())
j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCodeless));
if (j != ol.end())
{
short lli = j->second.lockCount ? 0 : 1;
short ssi = snr2ssi(j->second.snr);
rotm[gpstk::RinexObsHeader::P2].data = j->second.pseudorange;
rotm[gpstk::RinexObsHeader::P2].lli = lli;
rotm[gpstk::RinexObsHeader::P2].ssi = ssi;
rotm[gpstk::RinexObsHeader::L2].data = j->second.phase;
rotm[gpstk::RinexObsHeader::L2].lli = lli;
rotm[gpstk::RinexObsHeader::L2].ssi = ssi;
rotm[gpstk::RinexObsHeader::D2].data = j->second.doppler;
rotm[gpstk::RinexObsHeader::D2].lli = lli;
rotm[gpstk::RinexObsHeader::D2].ssi = ssi;
rotm[gpstk::RinexObsHeader::S2].data = j->second.snr;
}
// Now get the C2
j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCM));
if (j == ol.end())
j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCL));
if (j == ol.end())
j = ol.find(MDPObsEpoch::ObsKey(ccL2, rcCMCL));
if (j != ol.end())
{
short lli = j->second.lockCount ? 0 : 1;
short ssi = snr2ssi(j->second.snr);
rotm[gpstk::RinexObsHeader::C2].data = j->second.pseudorange;
rotm[gpstk::RinexObsHeader::C2].lli = lli;
rotm[gpstk::RinexObsHeader::C2].ssi = ssi;
}
return rotm;
}
RinexObsData makeRinexObsData(const gpstk::MDPEpoch& mdp)
{
RinexObsData rod;
rod.clockOffset=0;
rod.numSvs = mdp.size();
rod.epochFlag = 0;
rod.time = mdp.begin()->second.time;
for (MDPEpoch::const_iterator i=mdp.begin(); i!=mdp.end(); i++)
{
const MDPObsEpoch& moe = i->second;
gpstk::SatID svid(moe.prn, gpstk::SatID::systemGPS);
rod.obs[svid] = makeRinexObsTypeMap(moe);
}
return rod;
}
// Try to convert the given pages into an EngAlmanc object. Returns true
// upon success. This routine is tuned for two different types of nav data.
//
// The first is for a receiver that outputs all 4/5 subframes from a given
// code/carrier. Basically it looks for a 12.5 minute cycle that starts
// with page 1 from subframe 4. It makes sure that there hasn't been a
// cutover during it by checking that all sv pages (i.e. svid 1-32) have
// the same toa as the last page 25 (svid 51). This mode is the default and
// is set with the requireFull parameter.
//
// The second is for a receiver that only puts out a set of 4/5 subframes
// that "should" be a complete almanac. Note that it doesn't output pages
// for SVs that are set to the default data.
//
// The only receiver that this has been tested on is the Ashtech Z(Y)12.
//
// In the IS-GPS-200D, see pages 72-79, 82, 105
bool makeEngAlmanac(EngAlmanac& alm,
const AlmanacPages& pages,
bool requireFull) throw()
{
AlmanacPages::const_iterator sf4p1 = pages.find(SubframePage(4, 1));
AlmanacPages::const_iterator sf4p18 = pages.find(SubframePage(4, 18));
AlmanacPages::const_iterator sf4p25 = pages.find(SubframePage(4, 25));
AlmanacPages::const_iterator sf5p25 = pages.find(SubframePage(5, 25));
// These pages are required for a reasonable alm
if (sf4p18==pages.end() || sf4p25==pages.end() || sf5p25==pages.end())
return false;
long sf4p1sow=0;
if (requireFull)
{
if (sf4p1==pages.end())
return false;
else
sf4p1sow = sf4p1->second.getHOWTime();
}
int week=sf4p18->second.time.GPSfullweek();
for (int p=1; p<=25; p++)
{
for (int sf=4; sf<=5; sf++)
{
AlmanacPages::const_iterator i = pages.find(SubframePage(sf, p));
if (i == pages.end())
{
if (requireFull)
return false;
else
continue;
}
// All pages have to be contingious for the full alm mode.
if (requireFull)
{
long sow = i->second.getHOWTime();
if (sow != sf4p1sow + (sf-4)*6 + (p-1)*30)
return false;
}
long sfa[10];
long long_sfa[10];
i->second.fillArray(sfa);
copy( &sfa[0], &sfa[10], long_sfa);
if (!alm.addSubframe(long_sfa, week))
return false;
}
}
return true;
}
// Try to convert the given pages into an EngEphemeris object. Returns true
// upon success.
bool makeEngEphemeris(EngEphemeris& eph, const EphemerisPages& pages)
{
EphemerisPages::const_iterator sf[4];
sf[1] = pages.find(1);
if (sf[1] == pages.end())
return false;
sf[2] = pages.find(2);
if (sf[2] == pages.end())
return false;
sf[3] = pages.find(3);
if (sf[3] == pages.end())
return false;
long t1 = sf[1]->second.getHOWTime();
long t2 = sf[2]->second.getHOWTime();
long t3 = sf[3]->second.getHOWTime();
if (t2 != t1+6 || t3 != t1+12)
return false;
int prn = sf[1]->second.prn;
int week = sf[1]->second.time.GPSfullweek();
long sfa[10];
long long_sfa[10];
for (int i=1; i<=3; i++)
{
sf[i]->second.fillArray(sfa);
for( int j = 0; j < 10; j++ )
long_sfa[j] = static_cast<long>( sfa[j] );
if (!eph.addSubframe(long_sfa, week, prn, 0))
return false;
}
if (eph.isData(1) && eph.isData(2) && eph.isData(3))
return true;
return false;
}
} // end of namespace gpstk
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2019, Vinitha Ranganeni
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "src/statespace/statespace.h"
#include <Eigen>
#include <assert.h>
#include <cmath>
#include <utility>
#include "aikido/distance/SE2.hpp"
#include "aikido/statespace/SE2.hpp"
#include "cozmo_description/cozmo.hpp"
namespace grid_planner {
namespace statespace {
using aikido::statespace::SE2;
int Statespace::set_start_state(const int& x, const int& y, const int& theta) {
if (is_valid_state(x, y, theta)) {
m_start_id = get_state_id(x, y, theta);
return m_start_id;
}
return -1;
}
int Statespace::set_goal_state(const int& x, const int& y, const int& theta) {
if (is_valid_state(x, y, theta)) {
m_goal_id = get_state_id(x, y, theta);
return m_goal_id;
}
return -1;
}
SE2::State Statespace::create_new_state(const double& x,
const double& y,
const double& theta) {
SE2::State s;
Eigen::Isometry2d t = Eigen::Isometry2d::Identity();
const Eigen::Rotation2D<double> rot(theta);
t.linear() = rot.toRotationMatrix();
Eigen::Vector2d trans;
trans << x, y;
t.translation() = trans;
s.setIsometry(t);
Eigen::Vector xyth(3);
xyth = continuous_pose_to_discrete(x, y, theta);
int tmp_id = get_state_id(xyth[0], xyth[1], xyth[2]);
m_state_map[tmp_id] = s;
return s;
}
SE2::State Statespace::get_or_create_new_state(const int& x,
const int& y,
const int& theta) {
int input_state_id = get_state_id(x, y, theta);
if (m_state_map.find(tmp_id) != map.end()) {
return m_state_map[tmp_id];
} else {
return create_new_state(x, y, theta);
}
}
void Statespace::get_path_coordinates(
const std::vector<int>& path_state_ids,
std::vector<std::pair<int, int> > *path_coordinates) const {
for (int i = 0; i < path_state_ids.size(); ++i) {
int state_id = path_state_ids[i];
int x, y, theta;
if (get_coord_from_state_id(state_id, &x, &y, &theta)) {
path_coordinates->push_back(std::make_pair(x, y, theta));
}
}
}
int Statespace::get_state_id(const int& x,
const int& y,
const int& theta) const {
assert(x < m_width);
assert(y < m_height);
assert(theta <= m_bins);
return (theta * m_width * m_height) + y * m_width + x;
}
bool Statespace::get_coord_from_state_id(const int& state_id,
int* x,
int* y,
int* theta) const {
assert(state_id < m_occupancy_grid.size());
int theta_val = state_id / (m_width * m_height);
state_id = (state_id - theta * m_width * m_height);
int y_val = state_id / m_width;
int x_val = state_id - y_val * m_width;
*x = x_val;
*y = y_val;
*theta = theta_val;
return (is_valid_state(*x, *y, *theta));
}
bool Statespace::is_valid_state(const int& x,
const int& y,
const int& theta) const {
if (!(x >= 0 && x < m_width && y >= 0 && y < m_height)) {
return false;
}
if (!(theta >= 0 && theta < m_bins)) {
return false;
}
int state_id = get_state_id(x, y, theta);
if (m_occupancy_grid[state_id] == 0) {
return true;
}
return false;
}
double Statespace::get_distance(const SE2::State& source,
const SE2::State& succ) {
return SE2::distance(source, succ);
}
double Statespace::normalize_angle_rad(const double& theta_rad) {
assert(m_bins % 2 == 0);
if !(theta_rad >= 0 && theta_rad <= 2 * math.pi) {
theta_rad = theta_rad % (2 * math.pi);
}
return theta_rad;
}
double Statespace::discrete_angle_to_continuous(const int& theta) {
double rad = 2 * math.pi / m_bins * theta;
return rad;
}
int Statespace::continuous_angle_to_discrete(cosnt int& theta_rad) {
int discrete = static_cast<int>(theta_rad / (2 * math.pi / m_bins));
return discrete;
}
Eigen::Vector Statespace::continuous_position_to_discrete(const double& x_m,
const double& y_m) {
int x = static_cast<int>(x_m / (m_width / m_resolution));
int y = static_cast<int>(y_m / (m_height / m_resolution));
Eigen::Vector xy(2);
xy << x, y;
return xy;
}
Eigen::Vector Statespace::discrete_position_to_continuous(const int& x,
const int& y) {
double x_m = x * (m_width / m_resolution);
double y_m = y * (m_height / m_resolution);
Eigen::Vector xy(2);
xy << x_m, y_m;
return xy;
}
Eigen::vector Statespace::discrete_pose_to_continuous(const int& x,
const int& y,
const int& theta) {
Eigen::Vector xy = discrete_position_to_continuous(x, y);
Eigen::Vector th(1);
th << discrete_angle_to_continuous(theta);
Eigen::Vector ans(xy.size() + th.size());
ans << xy, th;
return ans;
}
Eigen::vector Statespace::continuous_pose_to_discrete(const double& x_m,
const double& y_m,
const double& theta_rad) {
Eigen::Vector xy = continuous_position_to_discrete(x_m, y_m);
Eigen::Vector th(1);
th << continuous_angle_to_discrete(normalize_angle_rad(theta_rad));
Eigen::Vector ans(xy.size() + th.size());
ans << xy, th;
return ans;
}
} // namespace statespace
} // namespace grid_planner
<commit_msg>fixed tpypo<commit_after>////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2019, Vinitha Ranganeni
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "src/statespace/statespace.h"
#include <Eigen>
#include <assert.h>
#include <cmath>
#include <utility>
#include "aikido/distance/SE2.hpp"
#include "aikido/statespace/SE2.hpp"
#include "cozmo_description/cozmo.hpp"
namespace grid_planner {
namespace statespace {
using aikido::statespace::SE2;
int Statespace::set_start_state(const int& x, const int& y, const int& theta) {
if (is_valid_state(x, y, theta)) {
m_start_id = get_state_id(x, y, theta);
return m_start_id;
}
return -1;
}
int Statespace::set_goal_state(const int& x, const int& y, const int& theta) {
if (is_valid_state(x, y, theta)) {
m_goal_id = get_state_id(x, y, theta);
return m_goal_id;
}
return -1;
}
SE2::State Statespace::create_new_state(const double& x,
const double& y,
const double& theta) {
SE2::State s;
Eigen::Isometry2d t = Eigen::Isometry2d::Identity();
const Eigen::Rotation2D<double> rot(theta);
t.linear() = rot.toRotationMatrix();
Eigen::Vector2d trans;
trans << x, y;
t.translation() = trans;
s.setIsometry(t);
Eigen::Vector xyth(3);
xyth = continuous_pose_to_discrete(x, y, theta);
int tmp_id = get_state_id(xyth[0], xyth[1], xyth[2]);
m_state_map[tmp_id] = s;
return s;
}
SE2::State Statespace::get_or_create_new_state(const int& x,
const int& y,
const int& theta) {
int input_state_id = get_state_id(x, y, theta);
if (m_state_map.find(tmp_id) != map.end()) {
return m_state_map[tmp_id];
} else {
return create_new_state(x, y, theta);
}
}
void Statespace::get_path_coordinates(
const std::vector<int>& path_state_ids,
std::vector<std::pair<int, int> > *path_coordinates) const {
for (int i = 0; i < path_state_ids.size(); ++i) {
int state_id = path_state_ids[i];
int x, y, theta;
if (get_coord_from_state_id(state_id, &x, &y, &theta)) {
path_coordinates->push_back(std::make_pair(x, y, theta));
}
}
}
int Statespace::get_state_id(const int& x,
const int& y,
const int& theta) const {
assert(x < m_width);
assert(y < m_height);
assert(theta <= m_bins);
return (theta * m_width * m_height) + y * m_width + x;
}
bool Statespace::get_coord_from_state_id(const int& state_id,
int* x,
int* y,
int* theta) const {
assert(state_id < m_occupancy_grid.size());
int theta_val = state_id / (m_width * m_height);
state_id = (state_id - theta * m_width * m_height);
int y_val = state_id / m_width;
int x_val = state_id - y_val * m_width;
*x = x_val;
*y = y_val;
*theta = theta_val;
return (is_valid_state(*x, *y, *theta));
}
bool Statespace::is_valid_state(const int& x,
const int& y,
const int& theta) const {
if (!(x >= 0 && x < m_width && y >= 0 && y < m_height)) {
return false;
}
if (!(theta >= 0 && theta < m_bins)) {
return false;
}
int state_id = get_state_id(x, y, theta);
if (m_occupancy_grid[state_id] == 0) {
return true;
}
return false;
}
double Statespace::get_distance(const SE2::State& source,
const SE2::State& succ) {
return SE2::distance(source, succ);
}
double Statespace::normalize_angle_rad(const double& theta_rad) {
assert(m_bins % 2 == 0);
if !(theta_rad >= 0 && theta_rad <= 2 * math.pi) {
theta_rad = theta_rad % (2 * math.pi);
}
return theta_rad;
}
double Statespace::discrete_angle_to_continuous(const int& theta) {
double rad = 2 * math.pi / m_bins * theta;
return rad;
}
int Statespace::continuous_angle_to_discrete(cosnt int& theta_rad) {
int discrete = static_cast<int>(theta_rad / (2 * math.pi / m_bins));
return discrete;
}
Eigen::Vector Statespace::continuous_position_to_discrete(const double& x_m,
const double& y_m) {
int x = static_cast<int>(x_m / (m_width / m_resolution));
int y = static_cast<int>(y_m / (m_height / m_resolution));
Eigen::Vector xy(2);
xy << x, y;
return xy;
}
Eigen::Vector Statespace::discrete_position_to_continuous(const int& x,
const int& y) {
double x_m = x * (m_width / m_resolution);
double y_m = y * (m_height / m_resolution);
Eigen::Vector xy(2);
xy << x_m, y_m;
return xy;
}
Eigen::vector Statespace::discrete_pose_to_continuous(const int& x,
const int& y,
const int& theta) {
Eigen::Vector xy = discrete_position_to_continuous(x, y);
Eigen::Vector th(1);
th << discrete_angle_to_continuous(theta);
Eigen::Vector ans(xy.size() + th.size());
ans << xy, th;
return ans;
}
Eigen::vector Statespace::continuous_pose_to_discrete(const double& x_m,
const double& y_m,
const double& theta_rad) {
Eigen::Vector xy = continuous_position_to_discrete(x_m, y_m);
Eigen::Vector th(1);
th << continuous_angle_to_discrete(normalize_angle_rad(theta_rad));
Eigen::Vector ans(xy.size() + th.size());
ans << xy, th;
return ans;
}
} // namespace statespace
} // namespace libcozmo
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2003 Unai Garro <ugarro@users.sourceforge.net>
*/
#include "pref.h"
#include "krecipes.h"
#include "krecipesview.h"
#include "dialogs/recipeinputdialog.h"
#include "dialogs/selectrecipedialog.h"
#include "dialogs/ingredientsdialog.h"
#include "dialogs/propertiesdialog.h"
#include "dialogs/shoppinglistdialog.h"
#include "dialogs/categorieseditordialog.h"
#include "dialogs/authorsdialog.h"
#include "dialogs/unitsdialog.h"
#include "dialogs/ingredientmatcherdialog.h"
#include "gui/pagesetupdialog.h"
#include "importers/kreimporter.h"
#include "importers/mmfimporter.h"
#include "importers/mx2importer.h"
#include "importers/mxpimporter.h"
#include "importers/nycgenericimporter.h"
#include "importers/recipemlimporter.h"
#include "importers/rezkonvimporter.h"
#include "recipe.h"
#include "DBBackend/recipedb.h"
#include <qdragobject.h>
#include <kprinter.h>
#include <qpainter.h>
#include <qpaintdevicemetrics.h>
#include <qmessagebox.h>
#include <kprogress.h>
#include <kmessagebox.h>
#include <kglobal.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kmenubar.h>
#include <kstatusbar.h>
#include <kkeydialog.h>
#include <kaccel.h>
#include <kio/netaccess.h>
#include <kfiledialog.h>
#include <kconfig.h>
#include <kedittoolbar.h>
#include <kstdaccel.h>
#include <kaction.h>
#include <kstdaction.h>
//Settings headers
#include <kdeversion.h>
Krecipes::Krecipes()
: KMainWindow( 0, "Krecipes" ),
m_view(new KrecipesView(this)),
m_printer(0)
{
// accept dnd
setAcceptDrops(true);
// tell the KMainWindow that this is indeed the main widget
setCentralWidget(m_view);
// then, setup our actions
setupActions();
// and a status bar
statusBar()->show();
// apply the saved mainwindow settings, if any, and ask the mainwindow
// to automatically save settings if changed: window size, toolbar
// position, icon size, etc.
setAutoSaveSettings();
// Resize if the window is too small so the buttons are shown
QSize wsize=size();
if (wsize.width()<740)
{
wsize.setWidth(740);
resize(wsize);
}
// allow the view to change the statusbar and caption
connect(m_view, SIGNAL(signalChangeStatusbar(const QString&)),
this, SLOT(changeStatusbar(const QString&)));
connect(m_view, SIGNAL(signalChangeCaption(const QString&)),
this, SLOT(changeCaption(const QString&)));
// Enable/Disable the Save Button (Initialize disabled, and connect signal)
connect(this->m_view, SIGNAL(enableSaveOption(bool)), this, SLOT(enableSaveOption(bool)));
enableSaveOption(false); // Disables saving initially
parsing_file_dlg = new KDialog(this,"parsing_file_dlg",true,Qt::WX11BypassWM);
QLabel *parsing_file_dlg_label = new QLabel(i18n("Gathering recipe data from file.\nPlease wait..."),parsing_file_dlg);
parsing_file_dlg_label->setFrameStyle( QFrame::Box | QFrame::Raised );
(new QVBoxLayout(parsing_file_dlg))->addWidget( parsing_file_dlg_label );
parsing_file_dlg->adjustSize();
//parsing_file_dlg->setFixedSize(parsing_file_dlg->size());
}
Krecipes::~Krecipes()
{
}
void Krecipes::setupActions()
{
KStdAction::openNew(this, SLOT(fileNew()), actionCollection());
//KStdAction::open(this, SLOT(fileOpen()), actionCollection());
saveAction=KStdAction::save(this, SLOT(fileSave()), actionCollection());
saveAsAction=KStdAction::saveAs(this, SLOT(fileSaveAs()), actionCollection());
KStdAction::print(this, SLOT(filePrint()), actionCollection());
KStdAction::quit(kapp, SLOT(quit()), actionCollection());
m_toolbarAction = KStdAction::showToolbar(this, SLOT(optionsShowToolbar()), actionCollection());
m_statusbarAction = KStdAction::showStatusbar(this, SLOT(optionsShowStatusbar()), actionCollection());
KStdAction::keyBindings(this, SLOT(optionsConfigureKeys()), actionCollection());
KStdAction::configureToolbars(this, SLOT(optionsConfigureToolbars()), actionCollection());
KStdAction::preferences(this, SLOT(optionsPreferences()), actionCollection());
(void)new KAction(i18n("Import..."), CTRL+Key_I,
this, SLOT(import()),
actionCollection(), "import_action");
(void)new KAction(i18n("Page Setup..."), 0,
this, SLOT(pageSetupSlot()),
actionCollection(), "page_setup_action");
createGUI();
}
void Krecipes::saveProperties(KConfig *)
{
// the 'config' object points to the session managed
// config file. anything you write here will be available
// later when this app is restored
//if (!m_view->currentURL().isNull())
// config->writeEntry("lastURL", m_view->currentURL());
}
void Krecipes::readProperties(KConfig *)
{
// the 'config' object points to the session managed
// config file. this function is automatically called whenever
// the app is being restored. read in here whatever you wrote
// in 'saveProperties'
//QString url = config->readEntry("lastURL");
//if (!url.isNull())
// m_view->openURL(KURL(url));
}
void Krecipes::dragEnterEvent(QDragEnterEvent *event)
{
// accept uri drops only
event->accept(QUriDrag::canDecode(event));
}
void Krecipes::fileNew()
{
// Create a new element (Element depends on active panel. New recipe by default)
m_view->createNewElement();
}
void Krecipes::fileOpen()
{
// this slot is called whenever the File->Open menu is selected,
// the Open shortcut is pressed (usually CTRL+O) or the Open toolbar
// button is clicked
/*
// this brings up the generic open dialog
KURL url = KURLRequesterDlg::getURL(QString::null, this, i18n("Open Location") );
*/
// standard filedialog
/*KURL url = KFileDialog::getOpenURL(QString::null, QString::null, this, i18n("Open Location"));
if (!url.isEmpty())
m_view->openURL(url);*/
}
void Krecipes::fileSave()
{
// this slot is called whenever the File->Save menu is selected,
// the Save shortcut is pressed (usually CTRL+S) or the Save toolbar
// button is clicked
m_view->save();
}
void Krecipes::fileSaveAs()
{
// this slot is called whenever the File->Save As menu is selected,
m_view->exportRecipe();
}
void Krecipes::filePrint()
{
m_view->print();
}
void Krecipes::import()
{
KFileDialog file_dialog( QString::null,
"*.kre *.kreml|Krecipes (*.kre, *.kreml)\n"
"*.mx2|MasterCook (*.mx2)\n"
"*.mxp *.txt|MasterCook Export (*.mxp, *.txt)\n"
"*.mmf *.txt|Meal-Master Format (*.mmf, *.txt)\n"
"*.txt|\"Now You're Cooking\" Generic Export (*.txt)\n"
"*.xml *.recipeml|RecipeML (*.xml, *.recipeml)\n"
"*.rk *.txt|Rezkonv Format (*.rk, *.txt)",
this,
"file_dialog",
true
);
file_dialog.setMode( KFile::Files );
if ( file_dialog.exec() == KFileDialog::Accepted )
{
QStringList warnings_list;
QString selected_filter = file_dialog.currentFilter();
BaseImporter *importer;
if ( selected_filter == "*.mxp *.txt" )
importer = new MXPImporter();
else if ( selected_filter == "*.mmf *.txt" )
importer = new MMFImporter();
else if ( selected_filter == "*.txt" )
importer = new NYCGenericImporter();
else if ( selected_filter == "*.mx2" )
importer = new MX2Importer();
else if ( selected_filter == "*.kre *.kreml" )
importer = new KreImporter();
else if ( selected_filter == "*.xml *.recipeml" )
importer = new RecipeMLImporter();
else if ( selected_filter == "*.rk *.txt" )
importer = new RezkonvImporter();
else
{
KMessageBox::sorry( this,
QString(i18n("Filter \"%1\" not recognized.\n"
"Please select one of the provided filters.")).arg(selected_filter),
i18n("Unrecognized Filter")
);
import(); //let's try again :)
return;
}
parsing_file_dlg->show();
importer->parseFiles(file_dialog.selectedFiles());
parsing_file_dlg->hide();
m_view->import( *importer );
if ( !importer->getMessages().isEmpty() )
{
KTextEdit *warningEdit = new KTextEdit( this );
warningEdit->setTextFormat( Qt::RichText );
warningEdit->setText( QString(i18n("NOTE: We recommend that all recipes generating warnings be checked to ensure that they were properly imported, and no loss of recipe data has occured.<br><br>")) + importer->getMessages() );
warningEdit->setReadOnly(true);
KDialogBase showWarningsDlg( KDialogBase::Swallow, i18n("Import warnings"), KDialogBase::Ok, KDialogBase::Default, this );
showWarningsDlg.setMainWidget( warningEdit ); //KDialogBase will delete warningEdit for us
showWarningsDlg.resize( QSize(550,250) );
showWarningsDlg.exec();
}
delete importer;
//TODO: is this the best way to do it???
m_view->selectPanel->reload();
m_view->ingredientsPanel->reload();
m_view->propertiesPanel->reload();
m_view->unitsPanel->reload();
m_view->shoppingListPanel->reload();
m_view->categoriesPanel->reload();
m_view->authorsPanel->reload();
m_view->ingredientMatcherPanel->reloadIngredients();
}
}
void Krecipes::pageSetupSlot()
{
Recipe recipe;
m_view->selectPanel->getCurrentRecipe(&recipe);
PageSetupDialog *page_setup = new PageSetupDialog(this,recipe);
page_setup->exec();
delete page_setup;
}
//return true to close app
bool Krecipes::queryClose()
{
if ( !m_view->inputPanel->everythingSaved() )
{
switch( KMessageBox::questionYesNoCancel( this,
i18n("A recipe contains unsaved changes.\n"
"Do you want to save the changes before exiting?"),
i18n("Unsaved Changes") ) )
{
case KMessageBox::Yes: m_view->save();
case KMessageBox::No: return true;
case KMessageBox::Cancel: return false;
default: return true;
}
}
else
return true;
}
void Krecipes::optionsShowToolbar()
{
// this is all very cut and paste code for showing/hiding the
// toolbar
if (m_toolbarAction->isChecked())
toolBar()->show();
else
toolBar()->hide();
}
void Krecipes::optionsShowStatusbar()
{
// this is all very cut and paste code for showing/hiding the
// statusbar
if (m_statusbarAction->isChecked())
statusBar()->show();
else
statusBar()->hide();
}
void Krecipes::optionsConfigureKeys()
{
#if KDE_IS_VERSION(3,1,92 )
// for KDE 3.2: KKeyDialog::configureKeys is deprecated
KKeyDialog::configure(actionCollection(), this, true);
#else
KKeyDialog::configureKeys(actionCollection(), "krecipesui.rc");
#endif
}
void Krecipes::optionsConfigureToolbars()
{
// use the standard toolbar editor
#if defined(KDE_MAKE_VERSION)
# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)
saveMainWindowSettings(KGlobal::config(), autoSaveGroup());
# else
saveMainWindowSettings(KGlobal::config());
# endif
#else
saveMainWindowSettings(KGlobal::config());
#endif
KEditToolbar dlg(actionCollection());
connect(&dlg, SIGNAL(newToolbarConfig()), this, SLOT(newToolbarConfig()));
dlg.exec();
}
void Krecipes::newToolbarConfig()
{
// this slot is called when user clicks "Ok" or "Apply" in the toolbar editor.
// recreate our GUI, and re-apply the settings (e.g. "text under icons", etc.)
createGUI();
#if defined(KDE_MAKE_VERSION)
# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)
applyMainWindowSettings(KGlobal::config(), autoSaveGroup());
# else
applyMainWindowSettings(KGlobal::config());
# endif
#else
applyMainWindowSettings(KGlobal::config());
#endif
}
void Krecipes::optionsPreferences()
{
// popup some sort of preference dialog, here
KrecipesPreferences dlg(this);
if (dlg.exec())
{}
}
void Krecipes::changeStatusbar(const QString& text)
{
// display the text on the statusbar
statusBar()->message(text);
}
void Krecipes::changeCaption(const QString& text)
{
// display the text on the caption
setCaption(text);
}
void Krecipes::enableSaveOption(bool en)
{
saveAction->setEnabled(en);
}
#include "krecipes.moc"
<commit_msg>CVS_SILENT: Revert... I'm not ready to commit this<commit_after>/*
* Copyright (C) 2003 Unai Garro <ugarro@users.sourceforge.net>
*/
#include "pref.h"
#include "krecipes.h"
#include "krecipesview.h"
#include "dialogs/recipeinputdialog.h"
#include "dialogs/selectrecipedialog.h"
#include "dialogs/ingredientsdialog.h"
#include "dialogs/propertiesdialog.h"
#include "dialogs/shoppinglistdialog.h"
#include "dialogs/categorieseditordialog.h"
#include "dialogs/authorsdialog.h"
#include "dialogs/unitsdialog.h"
#include "dialogs/ingredientmatcherdialog.h"
#include "gui/pagesetupdialog.h"
#include "importers/kreimporter.h"
#include "importers/mmfimporter.h"
#include "importers/mx2importer.h"
#include "importers/mxpimporter.h"
#include "importers/nycgenericimporter.h"
#include "importers/recipemlimporter.h"
#include "recipe.h"
#include "DBBackend/recipedb.h"
#include <qdragobject.h>
#include <kprinter.h>
#include <qpainter.h>
#include <qpaintdevicemetrics.h>
#include <qmessagebox.h>
#include <kprogress.h>
#include <kmessagebox.h>
#include <kglobal.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kmenubar.h>
#include <kstatusbar.h>
#include <kkeydialog.h>
#include <kaccel.h>
#include <kio/netaccess.h>
#include <kfiledialog.h>
#include <kconfig.h>
#include <kedittoolbar.h>
#include <kstdaccel.h>
#include <kaction.h>
#include <kstdaction.h>
//Settings headers
#include <kdeversion.h>
Krecipes::Krecipes()
: KMainWindow( 0, "Krecipes" ),
m_view(new KrecipesView(this)),
m_printer(0)
{
// accept dnd
setAcceptDrops(true);
// tell the KMainWindow that this is indeed the main widget
setCentralWidget(m_view);
// then, setup our actions
setupActions();
// and a status bar
statusBar()->show();
// apply the saved mainwindow settings, if any, and ask the mainwindow
// to automatically save settings if changed: window size, toolbar
// position, icon size, etc.
setAutoSaveSettings();
// Resize if the window is too small so the buttons are shown
QSize wsize=size();
if (wsize.width()<740)
{
wsize.setWidth(740);
resize(wsize);
}
// allow the view to change the statusbar and caption
connect(m_view, SIGNAL(signalChangeStatusbar(const QString&)),
this, SLOT(changeStatusbar(const QString&)));
connect(m_view, SIGNAL(signalChangeCaption(const QString&)),
this, SLOT(changeCaption(const QString&)));
// Enable/Disable the Save Button (Initialize disabled, and connect signal)
connect(this->m_view, SIGNAL(enableSaveOption(bool)), this, SLOT(enableSaveOption(bool)));
enableSaveOption(false); // Disables saving initially
parsing_file_dlg = new KDialog(this,"parsing_file_dlg",true,Qt::WX11BypassWM);
QLabel *parsing_file_dlg_label = new QLabel(i18n("Gathering recipe data from file.\nPlease wait..."),parsing_file_dlg);
parsing_file_dlg_label->setFrameStyle( QFrame::Box | QFrame::Raised );
(new QVBoxLayout(parsing_file_dlg))->addWidget( parsing_file_dlg_label );
parsing_file_dlg->adjustSize();
//parsing_file_dlg->setFixedSize(parsing_file_dlg->size());
}
Krecipes::~Krecipes()
{
}
void Krecipes::setupActions()
{
KStdAction::openNew(this, SLOT(fileNew()), actionCollection());
//KStdAction::open(this, SLOT(fileOpen()), actionCollection());
saveAction=KStdAction::save(this, SLOT(fileSave()), actionCollection());
saveAsAction=KStdAction::saveAs(this, SLOT(fileSaveAs()), actionCollection());
KStdAction::print(this, SLOT(filePrint()), actionCollection());
KStdAction::quit(kapp, SLOT(quit()), actionCollection());
m_toolbarAction = KStdAction::showToolbar(this, SLOT(optionsShowToolbar()), actionCollection());
m_statusbarAction = KStdAction::showStatusbar(this, SLOT(optionsShowStatusbar()), actionCollection());
KStdAction::keyBindings(this, SLOT(optionsConfigureKeys()), actionCollection());
KStdAction::configureToolbars(this, SLOT(optionsConfigureToolbars()), actionCollection());
KStdAction::preferences(this, SLOT(optionsPreferences()), actionCollection());
(void)new KAction(i18n("Import..."), CTRL+Key_I,
this, SLOT(import()),
actionCollection(), "import_action");
(void)new KAction(i18n("Page Setup..."), 0,
this, SLOT(pageSetupSlot()),
actionCollection(), "page_setup_action");
createGUI();
}
void Krecipes::saveProperties(KConfig *)
{
// the 'config' object points to the session managed
// config file. anything you write here will be available
// later when this app is restored
//if (!m_view->currentURL().isNull())
// config->writeEntry("lastURL", m_view->currentURL());
}
void Krecipes::readProperties(KConfig *)
{
// the 'config' object points to the session managed
// config file. this function is automatically called whenever
// the app is being restored. read in here whatever you wrote
// in 'saveProperties'
//QString url = config->readEntry("lastURL");
//if (!url.isNull())
// m_view->openURL(KURL(url));
}
void Krecipes::dragEnterEvent(QDragEnterEvent *event)
{
// accept uri drops only
event->accept(QUriDrag::canDecode(event));
}
void Krecipes::fileNew()
{
// Create a new element (Element depends on active panel. New recipe by default)
m_view->createNewElement();
}
void Krecipes::fileOpen()
{
// this slot is called whenever the File->Open menu is selected,
// the Open shortcut is pressed (usually CTRL+O) or the Open toolbar
// button is clicked
/*
// this brings up the generic open dialog
KURL url = KURLRequesterDlg::getURL(QString::null, this, i18n("Open Location") );
*/
// standard filedialog
/*KURL url = KFileDialog::getOpenURL(QString::null, QString::null, this, i18n("Open Location"));
if (!url.isEmpty())
m_view->openURL(url);*/
}
void Krecipes::fileSave()
{
// this slot is called whenever the File->Save menu is selected,
// the Save shortcut is pressed (usually CTRL+S) or the Save toolbar
// button is clicked
m_view->save();
}
void Krecipes::fileSaveAs()
{
// this slot is called whenever the File->Save As menu is selected,
m_view->exportRecipe();
}
void Krecipes::filePrint()
{
m_view->print();
}
void Krecipes::import()
{
KFileDialog file_dialog( QString::null,
"*.kre *.kreml|Krecipes (*.kre, *.kreml)\n"
"*.mx2|MasterCook (*.mx2)\n"
"*.mxp *.txt|MasterCook Export (*.mxp, *.txt)\n"
"*.mmf *.txt|Meal-Master Format (*.mmf, *.txt)\n"
"*.txt|\"Now You're Cooking\" Generic Export (*.txt)\n"
"*.xml *.recipeml|RecipeML (*.xml, *.recipeml)",
this,
"file_dialog",
true
);
file_dialog.setMode( KFile::Files );
if ( file_dialog.exec() == KFileDialog::Accepted )
{
QStringList warnings_list;
QString selected_filter = file_dialog.currentFilter();
BaseImporter *importer;
if ( selected_filter == "*.mxp *.txt" )
importer = new MXPImporter();
else if ( selected_filter == "*.mmf *.txt" )
importer = new MMFImporter();
else if ( selected_filter == "*.txt" )
importer = new NYCGenericImporter();
else if ( selected_filter == "*.mx2" )
importer = new MX2Importer();
else if ( selected_filter == "*.kre *.kreml" )
importer = new KreImporter();
else if ( selected_filter == "*.xml *.recipeml" )
importer = new RecipeMLImporter();
else
{
KMessageBox::sorry( this,
QString(i18n("Filter \"%1\" not recognized.\n"
"Please select one of the provided filters.")).arg(selected_filter),
i18n("Unrecognized Filter")
);
import(); //let's try again :)
return;
}
parsing_file_dlg->show();
importer->parseFiles(file_dialog.selectedFiles());
parsing_file_dlg->hide();
m_view->import( *importer );
if ( !importer->getMessages().isEmpty() )
{
KTextEdit *warningEdit = new KTextEdit( this );
warningEdit->setTextFormat( Qt::RichText );
warningEdit->setText( QString(i18n("NOTE: We recommend that all recipes generating warnings be checked to ensure that they were properly imported, and no loss of recipe data has occured.<br><br>")) + importer->getMessages() );
warningEdit->setReadOnly(true);
KDialogBase showWarningsDlg( KDialogBase::Swallow, i18n("Import warnings"), KDialogBase::Ok, KDialogBase::Default, this );
showWarningsDlg.setMainWidget( warningEdit ); //KDialogBase will delete warningEdit for us
showWarningsDlg.resize( QSize(550,250) );
showWarningsDlg.exec();
}
delete importer;
//TODO: is this the best way to do it???
m_view->selectPanel->reload();
m_view->ingredientsPanel->reload();
m_view->propertiesPanel->reload();
m_view->unitsPanel->reload();
m_view->shoppingListPanel->reload();
m_view->categoriesPanel->reload();
m_view->authorsPanel->reload();
m_view->ingredientMatcherPanel->reloadIngredients();
}
}
void Krecipes::pageSetupSlot()
{
Recipe recipe;
m_view->selectPanel->getCurrentRecipe(&recipe);
PageSetupDialog *page_setup = new PageSetupDialog(this,recipe);
page_setup->exec();
delete page_setup;
}
//return true to close app
bool Krecipes::queryClose()
{
if ( !m_view->inputPanel->everythingSaved() )
{
switch( KMessageBox::questionYesNoCancel( this,
i18n("A recipe contains unsaved changes.\n"
"Do you want to save the changes before exiting?"),
i18n("Unsaved Changes") ) )
{
case KMessageBox::Yes: m_view->save();
case KMessageBox::No: return true;
case KMessageBox::Cancel: return false;
default: return true;
}
}
else
return true;
}
void Krecipes::optionsShowToolbar()
{
// this is all very cut and paste code for showing/hiding the
// toolbar
if (m_toolbarAction->isChecked())
toolBar()->show();
else
toolBar()->hide();
}
void Krecipes::optionsShowStatusbar()
{
// this is all very cut and paste code for showing/hiding the
// statusbar
if (m_statusbarAction->isChecked())
statusBar()->show();
else
statusBar()->hide();
}
void Krecipes::optionsConfigureKeys()
{
#if KDE_IS_VERSION(3,1,92 )
// for KDE 3.2: KKeyDialog::configureKeys is deprecated
KKeyDialog::configure(actionCollection(), this, true);
#else
KKeyDialog::configureKeys(actionCollection(), "krecipesui.rc");
#endif
}
void Krecipes::optionsConfigureToolbars()
{
// use the standard toolbar editor
#if defined(KDE_MAKE_VERSION)
# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)
saveMainWindowSettings(KGlobal::config(), autoSaveGroup());
# else
saveMainWindowSettings(KGlobal::config());
# endif
#else
saveMainWindowSettings(KGlobal::config());
#endif
KEditToolbar dlg(actionCollection());
connect(&dlg, SIGNAL(newToolbarConfig()), this, SLOT(newToolbarConfig()));
dlg.exec();
}
void Krecipes::newToolbarConfig()
{
// this slot is called when user clicks "Ok" or "Apply" in the toolbar editor.
// recreate our GUI, and re-apply the settings (e.g. "text under icons", etc.)
createGUI();
#if defined(KDE_MAKE_VERSION)
# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)
applyMainWindowSettings(KGlobal::config(), autoSaveGroup());
# else
applyMainWindowSettings(KGlobal::config());
# endif
#else
applyMainWindowSettings(KGlobal::config());
#endif
}
void Krecipes::optionsPreferences()
{
// popup some sort of preference dialog, here
KrecipesPreferences dlg(this);
if (dlg.exec())
{}
}
void Krecipes::changeStatusbar(const QString& text)
{
// display the text on the statusbar
statusBar()->message(text);
}
void Krecipes::changeCaption(const QString& text)
{
// display the text on the caption
setCaption(text);
}
void Krecipes::enableSaveOption(bool en)
{
saveAction->setEnabled(en);
}
#include "krecipes.moc"
<|endoftext|> |
<commit_before>// This file is part of the ustl library, an STL implementation.
//
// Copyright (C) 2005 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.
//
// sostream.h
//
#include "mistream.h" // for istream_iterator, referenced in utf8.h
#include "sostream.h"
#include "ustring.h"
#include "ulimits.h"
#include <stdio.h>
namespace ustl {
/// Default constructor.
ostringstream::ostringstream (void)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
}
/// Creates a stream for writing into \p p of size \p n.
ostringstream::ostringstream (void* p, size_type n)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
link (p, n);
}
/// Creates a stream for writing into string \p dest.
///
/// dest may be resized by the stream if insufficient space is available.
///
ostringstream::ostringstream (string& dest)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
link (dest);
}
/// Creates a stream for writing into fixed block \p dest.
ostringstream::ostringstream (memlink& dest)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
link (dest);
}
/// Writes a single character into the stream.
void ostringstream::iwrite (uint8_t v)
{
if (remaining() >= sizeof(uint8_t) || overflow() >= sizeof(uint8_t))
ostream::iwrite (v);
}
/// Writes \p buf of size \p bufSize through the internal buffer.
void ostringstream::write_buffer (const char* buf, size_type bufSize)
{
size_type btw = 0, written = 0;
while ((written += btw) < bufSize && (remaining() || overflow(bufSize - written)))
write (buf + written, btw = min (remaining(), bufSize - written));
}
/// Simple decimal encoding of \p n into \p fmt.
inline char* ostringstream::encode_dec (char* fmt, uint32_t n) const
{
do {
*fmt++ = '0' + n % 10;
} while (n /= 10);
return (fmt);
}
/// Generates a sprintf format string for the given type.
void ostringstream::fmtstring (char* fmt, const char* typestr, bool bInteger) const
{
*fmt++ = '%';
if (m_Width)
fmt = encode_dec (fmt, m_Width);
if (m_Flags & ios::left)
*fmt++ = '-';
if (!bInteger) {
*fmt++ = '.';
fmt = encode_dec (fmt, m_Precision);
}
while (*typestr)
*fmt++ = *typestr++;
if (bInteger) {
if (m_Base == 16)
fmt[-1] = 'X';
else if (m_Base == 8)
fmt[-1] = 'o';
} else {
if (m_Flags & ios::scientific)
fmt[-1] = 'E';
}
*fmt = 0;
}
template <typename T>
inline void ostringstream::sprintf_iwrite (T v, const char* typestr)
{
const size_type c_BufSize = 64, c_FmtStrSize = 16;
char fmt [c_FmtStrSize], buffer [c_BufSize];
fmtstring (fmt, typestr, numeric_limits<T>::is_integer);
size_type i = snprintf (buffer, c_BufSize, fmt, v);
i = min (i, c_BufSize - 1);
write_buffer (buffer, i);
}
void ostringstream::iwrite (int v) { sprintf_iwrite (v, "d"); }
void ostringstream::iwrite (unsigned int v) { sprintf_iwrite (v, "u"); }
void ostringstream::iwrite (long v) { sprintf_iwrite (v, "ld"); }
void ostringstream::iwrite (unsigned long v) { sprintf_iwrite (v, "lu"); }
void ostringstream::iwrite (float v) { simd::reset_mmx(); sprintf_iwrite (v, "f"); }
void ostringstream::iwrite (double v) { simd::reset_mmx(); sprintf_iwrite (v, "lf"); }
#if HAVE_LONG_LONG
void ostringstream::iwrite (long long v) { sprintf_iwrite (v, "lld"); }
void ostringstream::iwrite (unsigned long long v) { sprintf_iwrite (v, "llu"); }
#endif
/// Writes \p v into the stream as utf8
void ostringstream::iwrite (wchar_t v)
{
char buffer [9];
*utf8out(buffer) = v;
write_buffer (buffer, Utf8Bytes(v));
}
/// Writes value \p v into the stream as text.
void ostringstream::iwrite (bool v)
{
static const char* c_Names[2] = { "false", "true" };
write_buffer (c_Names[v], 5 - v);
}
/// Writes string \p s into the stream.
void ostringstream::iwrite (const char* s)
{
write_buffer (s, strlen(s));
}
/// Writes string \p v into the stream.
void ostringstream::iwrite (const string& v)
{
write_buffer (v.begin(), v.size());
}
/// Equivalent to a vsprintf on the string.
int ostringstream::vformat (const char* fmt, va_list args)
{
#if HAVE_VA_COPY
va_list args2;
__va_copy (args2, args); // Because vsnprintf will iterate over args, changing them.
#else
#define args2 args
#endif
const bool bIsString (m_pResizable);
int rv = vsnprintf (ipos(), remaining() + bIsString, fmt, args);
if (uoff_t(rv) >= remaining() + bIsString)
rv = vsnprintf (ipos(), overflow(rv) + bIsString, fmt, args2);
skip (min (uoff_t(rv), remaining()));
return (rv);
}
/// Equivalent to a sprintf on the string.
int ostringstream::format (const char* fmt, ...)
{
simd::reset_mmx();
va_list args;
va_start (args, fmt);
const int rv = vformat (fmt, args);
va_end (args);
return (rv);
}
/// Sets the flag \p f in the stream.
void ostringstream::iwrite (ios::fmtflags f)
{
switch (f) {
case ios::oct: set_base (8); break;
case ios::dec: set_base (10); break;
case ios::hex: set_base (16); break;
case ios::left:
m_Flags |= ios::left;
m_Flags &= ~ios::right;
break;
case ios::right:
m_Flags |= ios::right;
m_Flags &= ~ios::left;
break;
default:
m_Flags |= f;
break;
}
}
/// Links to string \p l as resizable.
void ostringstream::link (string& l)
{
if (l.is_linked())
l.reserve (l.capacity());
assert (l.data() && "The output string buffer must not be read-only");
ostream::link (l);
m_pResizable = &l;
}
/// Unlinks the stream from its bound buffer.
void ostringstream::unlink (void)
{
ostream::unlink();
m_pResizable = NULL;
}
/// Writes the contents of \p buffer of \p size into the stream.
void ostringstream::write (const void* buffer, size_type sz)
{
if (remaining() < sz && overflow(sz) < sz)
return;
ostream::write (buffer, sz);
}
/// Writes the contents of \p buf into the stream.
void ostringstream::write (const cmemlink& buf)
{
if (remaining() < buf.size() && overflow(buf.size()) < buf.size())
return;
ostream::write (buf);
}
/// Attempts to create more output space. Returns remaining().
ostringstream::size_type ostringstream::overflow (size_type n)
{
if (m_pResizable && n > remaining()) {
const uoff_t oldPos (pos());
m_pResizable->reserve (oldPos + n, false);
m_pResizable->resize (oldPos + n);
link (*m_pResizable);
seek (oldPos);
}
if (n > remaining())
#ifdef WANT_STREAM_BOUNDS_CHECKING
throw stream_bounds_exception ("write", "text", pos(), n, remaining());
#else
assert (remaining() >= n && "Buffer overrun. Check your stream size calculations.");
#endif
return (remaining());
}
} // namespace ustl
<commit_msg>Fixed undefined operation ordering in snprintf arguments (ipos/overflow)<commit_after>// This file is part of the ustl library, an STL implementation.
//
// Copyright (C) 2005 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.
//
// sostream.h
//
#include "mistream.h" // for istream_iterator, referenced in utf8.h
#include "sostream.h"
#include "ustring.h"
#include "ulimits.h"
#include <stdio.h>
namespace ustl {
/// Default constructor.
ostringstream::ostringstream (void)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
}
/// Creates a stream for writing into \p p of size \p n.
ostringstream::ostringstream (void* p, size_type n)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
link (p, n);
}
/// Creates a stream for writing into string \p dest.
///
/// dest may be resized by the stream if insufficient space is available.
///
ostringstream::ostringstream (string& dest)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
link (dest);
}
/// Creates a stream for writing into fixed block \p dest.
ostringstream::ostringstream (memlink& dest)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
link (dest);
}
/// Writes a single character into the stream.
void ostringstream::iwrite (uint8_t v)
{
if (remaining() >= sizeof(uint8_t) || overflow() >= sizeof(uint8_t))
ostream::iwrite (v);
}
/// Writes \p buf of size \p bufSize through the internal buffer.
void ostringstream::write_buffer (const char* buf, size_type bufSize)
{
size_type btw = 0, written = 0;
while ((written += btw) < bufSize && (remaining() || overflow(bufSize - written)))
write (buf + written, btw = min (remaining(), bufSize - written));
}
/// Simple decimal encoding of \p n into \p fmt.
inline char* ostringstream::encode_dec (char* fmt, uint32_t n) const
{
do {
*fmt++ = '0' + n % 10;
} while (n /= 10);
return (fmt);
}
/// Generates a sprintf format string for the given type.
void ostringstream::fmtstring (char* fmt, const char* typestr, bool bInteger) const
{
*fmt++ = '%';
if (m_Width)
fmt = encode_dec (fmt, m_Width);
if (m_Flags & ios::left)
*fmt++ = '-';
if (!bInteger) {
*fmt++ = '.';
fmt = encode_dec (fmt, m_Precision);
}
while (*typestr)
*fmt++ = *typestr++;
if (bInteger) {
if (m_Base == 16)
fmt[-1] = 'X';
else if (m_Base == 8)
fmt[-1] = 'o';
} else {
if (m_Flags & ios::scientific)
fmt[-1] = 'E';
}
*fmt = 0;
}
template <typename T>
inline void ostringstream::sprintf_iwrite (T v, const char* typestr)
{
const size_type c_BufSize = 64, c_FmtStrSize = 16;
char fmt [c_FmtStrSize], buffer [c_BufSize];
fmtstring (fmt, typestr, numeric_limits<T>::is_integer);
size_type i = snprintf (buffer, c_BufSize, fmt, v);
i = min (i, c_BufSize - 1);
write_buffer (buffer, i);
}
void ostringstream::iwrite (int v) { sprintf_iwrite (v, "d"); }
void ostringstream::iwrite (unsigned int v) { sprintf_iwrite (v, "u"); }
void ostringstream::iwrite (long v) { sprintf_iwrite (v, "ld"); }
void ostringstream::iwrite (unsigned long v) { sprintf_iwrite (v, "lu"); }
void ostringstream::iwrite (float v) { simd::reset_mmx(); sprintf_iwrite (v, "f"); }
void ostringstream::iwrite (double v) { simd::reset_mmx(); sprintf_iwrite (v, "lf"); }
#if HAVE_LONG_LONG
void ostringstream::iwrite (long long v) { sprintf_iwrite (v, "lld"); }
void ostringstream::iwrite (unsigned long long v) { sprintf_iwrite (v, "llu"); }
#endif
/// Writes \p v into the stream as utf8
void ostringstream::iwrite (wchar_t v)
{
char buffer [9];
*utf8out(buffer) = v;
write_buffer (buffer, Utf8Bytes(v));
}
/// Writes value \p v into the stream as text.
void ostringstream::iwrite (bool v)
{
static const char* c_Names[2] = { "false", "true" };
write_buffer (c_Names[v], 5 - v);
}
/// Writes string \p s into the stream.
void ostringstream::iwrite (const char* s)
{
write_buffer (s, strlen(s));
}
/// Writes string \p v into the stream.
void ostringstream::iwrite (const string& v)
{
write_buffer (v.begin(), v.size());
}
/// Equivalent to a vsprintf on the string.
int ostringstream::vformat (const char* fmt, va_list args)
{
#if HAVE_VA_COPY
va_list args2;
__va_copy (args2, args); // Some vsnprintf implementations change args.
#else
#define args2 args
#endif
const bool bIsString (m_pResizable);
size_t rv = vsnprintf (ipos(), remaining() + bIsString, fmt, args);
if (rv >= remaining() + bIsString && rv < overflow(rv) + bIsString)
rv = vsnprintf (ipos(), remaining() + bIsString, fmt, args2);
skip (min (rv, remaining()));
return (rv);
}
/// Equivalent to a sprintf on the string.
int ostringstream::format (const char* fmt, ...)
{
simd::reset_mmx();
va_list args;
va_start (args, fmt);
const int rv = vformat (fmt, args);
va_end (args);
return (rv);
}
/// Sets the flag \p f in the stream.
void ostringstream::iwrite (ios::fmtflags f)
{
switch (f) {
case ios::oct: set_base (8); break;
case ios::dec: set_base (10); break;
case ios::hex: set_base (16); break;
case ios::left:
m_Flags |= ios::left;
m_Flags &= ~ios::right;
break;
case ios::right:
m_Flags |= ios::right;
m_Flags &= ~ios::left;
break;
default:
m_Flags |= f;
break;
}
}
/// Links to string \p l as resizable.
void ostringstream::link (string& l)
{
if (l.is_linked())
l.reserve (l.capacity());
assert (l.data() && "The output string buffer must not be read-only");
ostream::link (l);
m_pResizable = &l;
}
/// Unlinks the stream from its bound buffer.
void ostringstream::unlink (void)
{
ostream::unlink();
m_pResizable = NULL;
}
/// Writes the contents of \p buffer of \p size into the stream.
void ostringstream::write (const void* buffer, size_type sz)
{
if (remaining() < sz && overflow(sz) < sz)
return;
ostream::write (buffer, sz);
}
/// Writes the contents of \p buf into the stream.
void ostringstream::write (const cmemlink& buf)
{
if (remaining() < buf.size() && overflow(buf.size()) < buf.size())
return;
ostream::write (buf);
}
/// Attempts to create more output space. Returns remaining().
ostringstream::size_type ostringstream::overflow (size_type n)
{
if (m_pResizable && n > remaining()) {
const uoff_t oldPos (pos());
m_pResizable->reserve (oldPos + n, false);
m_pResizable->resize (oldPos + n);
link (*m_pResizable);
seek (oldPos);
}
if (n > remaining())
#ifdef WANT_STREAM_BOUNDS_CHECKING
throw stream_bounds_exception ("write", "text", pos(), n, remaining());
#else
assert (remaining() >= n && "Buffer overrun. Check your stream size calculations.");
#endif
return (remaining());
}
} // namespace ustl
<|endoftext|> |
<commit_before>/*
* Nouncer Implementation
*/
#include "nouncer.h"
/*
* Assembles the map<word,phoneme> dictionary by reading one line at a time,
* separating the word from the pronunciation, encoding the phoneme, and
* putting the pair in the map
*/
std::vector<char> Nouncer::cons = {
'9',':',';','<','I','J','K','T','U','V','W',
'X','Y','h','i','j','k','l','m','v','w','y','z','{'
};
Nouncer::Nouncer() {
dict = new std::map<std::string, std::string>;
std::ifstream file(DICTIONARY_FILE);
if (file) {
std::string line;
while (std::getline(file,line)) {
if (line.substr(0,3) == COMMENT_HEAD) {
continue;
}
else {
addWord(line);
}
}
}
else {
std::cerr << "Unable to load dictionary" << std::endl;
}
}
Nouncer::~Nouncer() {
dict->erase(dict->begin(), dict->end());
delete dict;
}
/*
* Given a string, return a pointer to the associated nounce
* or the nounce of "gravy" if the string is not found.
*/
std::string* Nouncer::lookUp(std::string word) {
try {
return &(dict->at(Utils::allCaps(word)));
}
catch (const std::out_of_range& oor) {
return &(dict->at("GRAVY"));
}
}
/*
* TODO: Let's encode outside this and pass in the nounce
*
* Maps a phoneme dictionary entry to a
* <std::string word, std::string nounce> pair
* and inserts in the dictionary.
*/
void Nouncer::addWord(std::string line) {
std::istringstream ss(line);
std::string word;
std::string nounce;
std::string phoneme;
ss >> word;
while (ss >> phoneme) {
char encoded_phoneme = encode(phoneme);
nounce.push_back(encoded_phoneme);
}
std::reverse(nounce.begin(), nounce.end());
std::pair<std::string, std::string> word_phonemes(word, nounce);
dict->insert(word_phonemes);
}
/*
* Encodes the phoneme string as a nounce
*/
char Nouncer::encode(std::string phoneme) {
char phone = '\0';
if (phoneme == "AA") phone = ' ';
else if (phoneme == "AA0") phone = '!';
else if (phoneme == "AA1") phone = '\"';
else if (phoneme == "AA2") phone = '#';
else if (phoneme == "AE") phone = '$';
else if (phoneme == "AE0") phone = '%';
else if (phoneme == "AE1") phone = '&';
else if (phoneme == "AE2") phone = '(';
else if (phoneme == "AH") phone = ')';
else if (phoneme == "AH0") phone = '*';
else if (phoneme == "AH1") phone = '+';
else if (phoneme == "AH2") phone = ',';
else if (phoneme == "AO") phone = '-';
else if (phoneme == "AO0") phone = '.';
else if (phoneme == "AO1") phone = '/';
else if (phoneme == "AO2") phone = '0';
else if (phoneme == "AW") phone = '1';
else if (phoneme == "AW0") phone = '2';
else if (phoneme == "AW1") phone = '3';
else if (phoneme == "AW2") phone = '4';
else if (phoneme == "AY") phone = '5';
else if (phoneme == "AY0") phone = '6';
else if (phoneme == "AY1") phone = '7';
else if (phoneme == "AY2") phone = '8';
else if (phoneme == "B") phone = '9';
else if (phoneme == "CH") phone = ':';
else if (phoneme == "D") phone = ';';
else if (phoneme == "DH") phone = '<';
else if (phoneme == "EH") phone = '=';
else if (phoneme == "EH0") phone = '>';
else if (phoneme == "EH1") phone = '?';
else if (phoneme == "EH2") phone = '@';
else if (phoneme == "ER") phone = 'A';
else if (phoneme == "ER0") phone = 'B';
else if (phoneme == "ER1") phone = 'C';
else if (phoneme == "ER2") phone = 'D';
else if (phoneme == "EY") phone = 'E';
else if (phoneme == "EY0") phone = 'F';
else if (phoneme == "EY1") phone = 'G';
else if (phoneme == "EY2") phone = 'H';
else if (phoneme == "F") phone = 'I';
else if (phoneme == "G") phone = 'J';
else if (phoneme == "HH") phone = 'K';
else if (phoneme == "IH") phone = 'L';
else if (phoneme == "IH0") phone = 'M';
else if (phoneme == "IH1") phone = 'N';
else if (phoneme == "IH2") phone = 'O';
else if (phoneme == "IY") phone = 'P';
else if (phoneme == "IY0") phone = 'Q';
else if (phoneme == "IY1") phone = 'R';
else if (phoneme == "IY2") phone = 'S';
else if (phoneme == "JH") phone = 'T';
else if (phoneme == "K") phone = 'U';
else if (phoneme == "L") phone = 'V';
else if (phoneme == "M") phone = 'W';
else if (phoneme == "N") phone = 'X';
else if (phoneme == "NG") phone = 'Y';
else if (phoneme == "OW") phone = 'Z';
else if (phoneme == "OW0") phone = 'a';
else if (phoneme == "OW1") phone = 'b';
else if (phoneme == "OW2") phone = 'c';
else if (phoneme == "OY") phone = 'd';
else if (phoneme == "OY0") phone = 'e';
else if (phoneme == "OY1") phone = 'f';
else if (phoneme == "OY2") phone = 'g';
else if (phoneme == "P") phone = 'h';
else if (phoneme == "R") phone = 'i';
else if (phoneme == "S") phone = 'j';
else if (phoneme == "SH") phone = 'k';
else if (phoneme == "T") phone = 'l';
else if (phoneme == "TH") phone = 'm';
else if (phoneme == "UH") phone = 'n';
else if (phoneme == "UH0") phone = 'o';
else if (phoneme == "UH1") phone = 'p';
else if (phoneme == "UH2") phone = 'q';
else if (phoneme == "UW") phone = 'r';
else if (phoneme == "UW0") phone = 's';
else if (phoneme == "UW1") phone = 't';
else if (phoneme == "UW2") phone = 'u';
else if (phoneme == "V") phone = 'v';
else if (phoneme == "W") phone = 'w';
else if (phoneme == "Y") phone = 'y';
else if (phoneme == "Z") phone = 'z';
else if (phoneme == "ZH") phone = '{';
else
std::cerr << "Could not identify phoneme " << phoneme << std::endl;
return phone;
}
bool Nouncer::isVowel(char& phone) {
return !(std::find(cons.begin(),cons.end(),phone) != cons.end());
}
int Nouncer::getSylCount(std::string word) {
int count = 0;
std::string* nounce = lookUp(word);
for (auto i = nounce->begin(); i != nounce->end(); ++i) {
if ( isVowel(*i) ) count++;
}
return count;
}
int Nouncer::getSize() {
return dict->size();
}
void Nouncer::print(std::string filename) {
std::ofstream of(filename);
for (auto it = dict->begin(); it!=dict->end(); ++it) {
of<<(*it).first<<":"<<(*it).second<<std::endl;
}
}
<commit_msg>clean up x3<commit_after>/*
* Nouncer Implementation
*/
#include "nouncer.h"
/*
* Assembles the map<word,phoneme> dictionary by reading one line at a time,
* separating the word from the pronunciation, encoding the phoneme, and
* putting the pair in the map
*/
std::vector<char> Nouncer::cons = {
'9',':',';','<','I','J','K','T','U','V','W',
'X','Y','h','i','j','k','l','m','v','w','y','z','{'
};
Nouncer::Nouncer() {
dict = new std::map<std::string, std::string>;
std::ifstream file(DICTIONARY_FILE);
if (file) {
std::string line;
while (std::getline(file,line)) {
if (line.substr(0,3) == COMMENT_HEAD) {
continue;
}
else {
addWord(line);
}
}
}
else {
std::cerr << "Unable to load dictionary" << std::endl;
}
}
Nouncer::~Nouncer() {
dict->erase(dict->begin(), dict->end());
delete dict;
}
/*
* Given a string, return a pointer to the associated nounce
* or the nounce of "gravy" if the string is not found.
*/
std::string* Nouncer::lookUp(std::string word) {
try {
return &(dict->at(Utils::allCaps(word)));
}
catch (const std::out_of_range& oor) {
return &(dict->at("GRAVY"));
}
}
/*
* TODO: Let's encode outside this and pass in the nounce
*
* Maps a phoneme dictionary entry to a
* <std::string word, std::string nounce> pair
* and inserts in the dictionary.
*/
void Nouncer::addWord(std::string line) {
std::istringstream ss(line);
std::string word;
std::string nounce;
std::string phoneme;
ss >> word;
while (ss >> phoneme) {
char encoded_phoneme = encode(phoneme);
nounce.push_back(encoded_phoneme);
}
std::reverse(nounce.begin(), nounce.end());
std::pair<std::string, std::string> word_phonemes(word, nounce);
dict->insert(word_phonemes);
}
/*
* Encodes the phoneme string as a nounce
*/
char Nouncer::encode(std::string phoneme) {
char phone = '\0';
if (phoneme == "AA") phone = ' ';
else if (phoneme == "AA0") phone = '!';
else if (phoneme == "AA1") phone = '\"';
else if (phoneme == "AA2") phone = '#';
else if (phoneme == "AE") phone = '$';
else if (phoneme == "AE0") phone = '%';
else if (phoneme == "AE1") phone = '&';
else if (phoneme == "AE2") phone = '(';
else if (phoneme == "AH") phone = ')';
else if (phoneme == "AH0") phone = '*';
else if (phoneme == "AH1") phone = '+';
else if (phoneme == "AH2") phone = ',';
else if (phoneme == "AO") phone = '-';
else if (phoneme == "AO0") phone = '.';
else if (phoneme == "AO1") phone = '/';
else if (phoneme == "AO2") phone = '0';
else if (phoneme == "AW") phone = '1';
else if (phoneme == "AW0") phone = '2';
else if (phoneme == "AW1") phone = '3';
else if (phoneme == "AW2") phone = '4';
else if (phoneme == "AY") phone = '5';
else if (phoneme == "AY0") phone = '6';
else if (phoneme == "AY1") phone = '7';
else if (phoneme == "AY2") phone = '8';
else if (phoneme == "B") phone = '9';
else if (phoneme == "CH") phone = ':';
else if (phoneme == "D") phone = ';';
else if (phoneme == "DH") phone = '<';
else if (phoneme == "EH") phone = '=';
else if (phoneme == "EH0") phone = '>';
else if (phoneme == "EH1") phone = '?';
else if (phoneme == "EH2") phone = '@';
else if (phoneme == "ER") phone = 'A';
else if (phoneme == "ER0") phone = 'B';
else if (phoneme == "ER1") phone = 'C';
else if (phoneme == "ER2") phone = 'D';
else if (phoneme == "EY") phone = 'E';
else if (phoneme == "EY0") phone = 'F';
else if (phoneme == "EY1") phone = 'G';
else if (phoneme == "EY2") phone = 'H';
else if (phoneme == "F") phone = 'I';
else if (phoneme == "G") phone = 'J';
else if (phoneme == "HH") phone = 'K';
else if (phoneme == "IH") phone = 'L';
else if (phoneme == "IH0") phone = 'M';
else if (phoneme == "IH1") phone = 'N';
else if (phoneme == "IH2") phone = 'O';
else if (phoneme == "IY") phone = 'P';
else if (phoneme == "IY0") phone = 'Q';
else if (phoneme == "IY1") phone = 'R';
else if (phoneme == "IY2") phone = 'S';
else if (phoneme == "JH") phone = 'T';
else if (phoneme == "K") phone = 'U';
else if (phoneme == "L") phone = 'V';
else if (phoneme == "M") phone = 'W';
else if (phoneme == "N") phone = 'X';
else if (phoneme == "NG") phone = 'Y';
else if (phoneme == "OW") phone = 'Z';
else if (phoneme == "OW0") phone = 'a';
else if (phoneme == "OW1") phone = 'b';
else if (phoneme == "OW2") phone = 'c';
else if (phoneme == "OY") phone = 'd';
else if (phoneme == "OY0") phone = 'e';
else if (phoneme == "OY1") phone = 'f';
else if (phoneme == "OY2") phone = 'g';
else if (phoneme == "P") phone = 'h';
else if (phoneme == "R") phone = 'i';
else if (phoneme == "S") phone = 'j';
else if (phoneme == "SH") phone = 'k';
else if (phoneme == "T") phone = 'l';
else if (phoneme == "TH") phone = 'm';
else if (phoneme == "UH") phone = 'n';
else if (phoneme == "UH0") phone = 'o';
else if (phoneme == "UH1") phone = 'p';
else if (phoneme == "UH2") phone = 'q';
else if (phoneme == "UW") phone = 'r';
else if (phoneme == "UW0") phone = 's';
else if (phoneme == "UW1") phone = 't';
else if (phoneme == "UW2") phone = 'u';
else if (phoneme == "V") phone = 'v';
else if (phoneme == "W") phone = 'w';
else if (phoneme == "Y") phone = 'y';
else if (phoneme == "Z") phone = 'z';
else if (phoneme == "ZH") phone = '{';
else
std::cerr << "Could not identify phoneme " << phoneme << std::endl;
return phone;
}
bool Nouncer::isVowel(char& phone) {
return (std::find(cons.begin(),cons.end(),phone) == cons.end());
}
int Nouncer::getSylCount(std::string word) {
int count = 0;
std::string* nounce = lookUp(word);
for (auto i = nounce->begin(); i != nounce->end(); ++i) {
if ( isVowel(*i) ) count++;
}
return count;
}
int Nouncer::getSize() {
return dict->size();
}
void Nouncer::print(std::string filename) {
std::ofstream of(filename);
for (auto it = dict->begin(); it!=dict->end(); ++it) {
of<<(*it).first<<":"<<(*it).second<<std::endl;
}
}
<|endoftext|> |
<commit_before>#include "/Users/Jarno/Arduino/bluetoothOhjausBot/AvoidObstacleController.h"
AvoidObstacleController::AvoidObstacleController(MotorController* motorCtrl, ServoController* servoCtrl, SonarSRF08* sonar, BluetoothController* BT) {
motorController = motorCtrl;
servoController = servoCtrl;
sonarPanLastMovement = millis();
bluetoothController = BT;
mainSonar = sonar;
}
void AvoidObstacleController::moveRobot() {
time = millis();
if (time - sonarPanLastMovement > 400) {
sonarPanLastMovement = time;
if (panServoAngle == 90 && previousPanServoAngle == 140) {
panServoAngle = 60;
previousPanServoAngle = 90;
}
else if (panServoAngle == 90 && previousPanServoAngle == 60) {
panServoAngle = 140;
previousPanServoAngle = 60;
}
else if (panServoAngle == 140) {
panServoAngle = 90;
previousPanServoAngle = 140;
}
else {
panServoAngle = 90;
previousPanServoAngle = 60;
}
servoController->setPanAndTilt(panServoAngle, tiltServoAngle);
float sensorReading = 0;
sensorReading = mainSonar->getRange(unit);
if (sensorReading > 30) {
bluetoothController->sendMessage("Yli 30");
motorController->moveForward();
}
if (sensorReading <=30 && sensorReading != 0) {
bluetoothController->sendMessage("Alle 30");
motorController->turnLeft();
delay(700);
}
}
}
<commit_msg>Delete AvoidObstacleController.cpp<commit_after><|endoftext|> |
<commit_before>#ifndef _options_hpp_INCLUDED
#define _options_hpp_INCLUDED
/*------------------------------------------------------------------------*/
// The 'check' option has by default '0' in optimized compilation, but for
// debugging and testing we want to set it to '1', by default. Setting
// 'check' to '1' for instance triggers saving all the original clauses for
// checking witnesses and also learned clauses if a solution is provided.
#ifndef NDEBUG
#define DEBUG 1
#else
#define DEBUG 0
#endif
/*------------------------------------------------------------------------*/
// Some of the 'OPTION' macros below should only be included if certain
// compile time options are enabled. This has the effect, that for instance
// if 'LOGGING' is defined, and thus logging code is included, then also the
// 'log' option is defined. Otherwise the 'log' option is not included.
#ifdef LOGGING
#define LOGOPT OPTION
#else
#define LOGOPT(ARGS...) /**/
#endif
#ifdef QUIET
#define QUTOPT(ARGS...) /**/
#else
#define QUTOPT OPTION
#endif
/*------------------------------------------------------------------------*/
// In order to add new option, simply add a new line below.
#define OPTIONS \
\
/* NAME TYPE, VAL, LO, HI, USAGE */ \
\
OPTION(arena, int, 3, 0, 3, "1=clause,2=var,3=queue") \
OPTION(arenacompact, bool, 0, 0, 1, "keep clauses compact") \
OPTION(arenasort, int, 1, 0, 1, "sort clauses after arenaing") \
OPTION(binary, bool, 1, 0, 1, "use binary proof format") \
OPTION(check, bool,DEBUG, 0, 1, "save & check original CNF") \
OPTION(clim, int, -1, 0,1e9, "conflict limit (-1=none)") \
OPTION(compact, bool, 1, 0, 1, "enable compactification") \
OPTION(compactint, int, 1e3, 1,1e9, "compactification conflic tlimit") \
OPTION(compactlim, double, 0.1, 0, 1, "inactive variable limit") \
OPTION(compactmin, int, 100, 1,1e9, "inactive variable limit") \
OPTION(dlim, int, -1, 0,1e9, "decision limit (-1=none)") \
OPTION(elim, bool, 1, 0, 1, "bounded variable elimination") \
OPTION(elimclslim, int, 1000, 0,1e9, "ignore clauses of this size") \
OPTION(eliminit, int, 1e3, 0,1e9, "initial conflict limit") \
OPTION(elimint, int, 1e4, 1,1e9, "initial conflict interval") \
OPTION(elimocclim, int, 100, 0,1e9, "one sided occurrence limit") \
OPTION(elimroundsinit, int, 5, 1,1e9, "initial number of rounds") \
OPTION(elimrounds, int, 2, 1,1e9, "usual number of rounds") \
OPTION(emabumplast, double, 1e-5, 0, 1, "alpha bump last percentage") \
OPTION(emagluefast, double, 3e-2, 0, 1, "alpha fast glue") \
OPTION(emaglueslow, double, 1e-5, 0, 1, "alpha slow glue") \
OPTION(emajump, double, 1e-5, 0, 1, "alpha jump level") \
OPTION(emasize, double, 1e-5, 0, 1, "alpha learned clause size") \
OPTION(decompose, bool, 1, 0, 1, "SCC decompose BIG and ELS") \
OPTION(decomposerounds, int, 1, 1,1e9, "number of decompose rounds") \
OPTION(hbr, bool, 1, 0, 1, "learn hyper binary clauses") \
OPTION(hbrsizelim, int, 1e9, 3, 1e9, "max size HBR base clause") \
OPTION(keepglue, int, 2, 1,1e9, "glue kept learned clauses") \
OPTION(keepsize, int, 3, 2,1e9, "size kept learned clauses") \
OPTION(leak, bool, 1, 0, 1, "leak solver memory") \
LOGOPT(log, bool, 0, 0, 1, "enable logging") \
LOGOPT(logsort, bool, 0, 0, 1, "sort logged clauses") \
OPTION(minimize, bool, 1, 0, 1, "minimize learned clauses") \
OPTION(minimizedepth, int, 1000, 0,1e9, "minimization depth") \
OPTION(phase, int, 1, 0, 1, "initial phase: 0=neg,1=pos") \
OPTION(posize, int, 4, 4,1e9, "size for saving position") \
OPTION(probe, bool, 1, 0, 1, "failed literal probing" ) \
OPTION(probeinit, int, 500, 0,1e9, "initial probing interval" ) \
OPTION(probeint, int, 1e4, 1,1e9, "probing interval increment" ) \
OPTION(probereleff, double, 0.02, 0, 1, "relative probing efficiency") \
OPTION(probemaxeff, double, 1e7, 0, 1, "maximum probing efficiency") \
OPTION(probemineff, double, 1e5, 0, 1, "minimum probing efficiency") \
OPTION(prefetch, bool, 1, 0, 1, "prefetch watches") \
OPTION(profile, int, 2, 0, 4, "profiling level") \
QUTOPT(quiet, bool, 0, 0, 1, "disable all messages") \
OPTION(reduceinc, int, 300, 1,1e6, "reduce limit increment") \
OPTION(reduceinit, int, 2000, 0,1e6, "initial reduce limit") \
OPTION(rephase, bool, 1, 0, 1, "enable rephasing") \
OPTION(rephaseint, int, 1e5, 1,1e9, "rephasing interval") \
OPTION(restart, bool, 1, 0, 1, "enable restarting") \
OPTION(restartint, int, 6, 1,1e9, "restart base interval") \
OPTION(restartmargin, double, 1.1, 0, 10, "restart slow fast margin") \
OPTION(reusetrail, bool, 1, 0, 1, "enable trail reuse") \
OPTION(simplify, bool, 1, 0, 1, "enable simplifier") \
OPTION(strengthen, bool, 1, 0, 1, "strengthen during subsume") \
OPTION(subsume, bool, 1, 0, 1, "enable clause subsumption") \
OPTION(subsumebinlim, int, 1e4, 0,1e9, "watch list length limit") \
OPTION(subsumeclslim, int, 1e3, 0,1e9, "clause length limit") \
OPTION(subsumeinc, int, 1e4, 1,1e9, "interval in conflicts") \
OPTION(subsumeinit, int, 1e4, 0,1e9, "initial subsume limit") \
OPTION(subsumeocclim, int, 1e2, 0,1e9, "watch list length limit") \
OPTION(trailbump, bool, 1, 0, 1, "use trail + bumped") \
OPTION(trailbumplast, double, 40, 0,100, "trail bump last level limit") \
OPTION(trailbumprops, double, 200, 0,1e9, "trail bump propagation limit") \
OPTION(transred, bool, 1, 0, 1, "transitive reduction of BIG") \
OPTION(transredreleff,double, 0.10, 0, 1, "relative efficiency") \
OPTION(transredmaxeff,double, 1e7, 0, 1, "maximum efficiency") \
OPTION(transredmineff,double, 1e5, 0, 1, "minimum efficiency") \
QUTOPT(verbose, int, 0, 0, 2, "more verbose messages") \
OPTION(vivify, bool, 1, 0, 1, "vivification") \
OPTION(vivifyreleff, double, 0.03, 0, 1, "relative efficiency") \
OPTION(vivifymaxeff, double, 1e7, 0, 1, "maximum efficiency") \
OPTION(vivifymineff, double, 1e5, 0, 1, "minimum efficiency") \
OPTION(witness, bool, 1, 0, 1, "print witness") \
/*------------------------------------------------------------------------*/
namespace CaDiCaL {
class Internal;
class Options {
Internal * internal;
bool set ( int &, const char *, const char *, const int, const int);
bool set ( bool &, const char *, const char *, const bool, const bool);
bool set (double &, const char *, const char *, const double, const double);
const char * match (const char *, const char *);
public:
// Makes options directly accessible, e.g., for instance declares the
// member 'bool Options.restart' here. This will give fast and type save
// access to option values (internally). In principle one could make all
// options simply 'double' though, but that requires double conversions
// during accessing options at run-time and disregards the intended types,
// e.g., one would need to allow fractional values for actual integer
// or boolean options. Keeping the different types makes the output of
// 'print' and 'usage' also more appealing (since correctly typed values
// are printed).
#define OPTION(N,T,V,L,H,D) \
T N;
OPTIONS
#undef OPTION
Options (Internal *);
// This sets the value of an option assuming a 'long' command line
// argument form. The argument 'arg' thus should look like
//
// "--<NAME>=<VAL>", "--<NAME>" or "--no-<NAME>"
//
// where 'NAME' is one of the option names above. Returns 'true' if the
// option was parsed and set correctly. For boolean values we strictly
// only allow "true", "false", "0" and "1" as "<VAL>" string. For 'int'
// type options we parse "<VAL>" with 'atoi' and force the resulting 'int'
// value to the 'LO' and 'HI' range and similarly for 'double' type
// options using 'atof'. If the string is not a valid 'int' for 'int'
// options or a 'double' value for 'double' options, then the function
// returns 'false'.
//
bool set (const char * arg);
// Interface to options using in a certain sense non-type-safe 'double'
// values even for 'int' and 'bool'. However, 'double' can hold a 'bool'
// as well an 'int' value precisely, e.g., if the result of 'get' is cast
// down again by the client. This would only fail for 64 byte 'long',
// which we currently do not support as option type.
//
bool has (const char * name);
double get (const char * name);
bool set (const char * name, double);
void print (); // print current values in command line form
static void usage (); // print usage message for all options
};
};
#endif
<commit_msg>new stuff<commit_after>#ifndef _options_hpp_INCLUDED
#define _options_hpp_INCLUDED
/*------------------------------------------------------------------------*/
// The 'check' option has by default '0' in optimized compilation, but for
// debugging and testing we want to set it to '1', by default. Setting
// 'check' to '1' for instance triggers saving all the original clauses for
// checking witnesses and also learned clauses if a solution is provided.
#ifndef NDEBUG
#define DEBUG 1
#else
#define DEBUG 0
#endif
/*------------------------------------------------------------------------*/
// Some of the 'OPTION' macros below should only be included if certain
// compile time options are enabled. This has the effect, that for instance
// if 'LOGGING' is defined, and thus logging code is included, then also the
// 'log' option is defined. Otherwise the 'log' option is not included.
#ifdef LOGGING
#define LOGOPT OPTION
#else
#define LOGOPT(ARGS...) /**/
#endif
#ifdef QUIET
#define QUTOPT(ARGS...) /**/
#else
#define QUTOPT OPTION
#endif
/*------------------------------------------------------------------------*/
// In order to add new option, simply add a new line below.
#define OPTIONS \
\
/* NAME TYPE, VAL, LO, HI, USAGE */ \
\
OPTION(arena, int, 3, 0, 3, "1=clause,2=var,3=queue") \
OPTION(arenacompact, bool, 1, 0, 1, "keep clauses compact") \
OPTION(arenasort, int, 1, 0, 1, "sort clauses after arenaing") \
OPTION(binary, bool, 1, 0, 1, "use binary proof format") \
OPTION(check, bool,DEBUG, 0, 1, "save & check original CNF") \
OPTION(clim, int, -1, 0,1e9, "conflict limit (-1=none)") \
OPTION(compact, bool, 1, 0, 1, "enable compactification") \
OPTION(compactint, int, 1e3, 1,1e9, "compactification conflic tlimit") \
OPTION(compactlim, double, 0.1, 0, 1, "inactive variable limit") \
OPTION(compactmin, int, 100, 1,1e9, "inactive variable limit") \
OPTION(dlim, int, -1, 0,1e9, "decision limit (-1=none)") \
OPTION(elim, bool, 1, 0, 1, "bounded variable elimination") \
OPTION(elimclslim, int, 1000, 0,1e9, "ignore clauses of this size") \
OPTION(eliminit, int, 1e3, 0,1e9, "initial conflict limit") \
OPTION(elimint, int, 1e4, 1,1e9, "initial conflict interval") \
OPTION(elimocclim, int, 100, 0,1e9, "one sided occurrence limit") \
OPTION(elimroundsinit, int, 5, 1,1e9, "initial number of rounds") \
OPTION(elimrounds, int, 2, 1,1e9, "usual number of rounds") \
OPTION(emabumplast, double, 1e-5, 0, 1, "alpha bump last percentage") \
OPTION(emagluefast, double, 3e-2, 0, 1, "alpha fast glue") \
OPTION(emaglueslow, double, 1e-5, 0, 1, "alpha slow glue") \
OPTION(emajump, double, 1e-5, 0, 1, "alpha jump level") \
OPTION(emasize, double, 1e-5, 0, 1, "alpha learned clause size") \
OPTION(decompose, bool, 1, 0, 1, "SCC decompose BIG and ELS") \
OPTION(decomposerounds, int, 1, 1,1e9, "number of decompose rounds") \
OPTION(hbr, bool, 1, 0, 1, "learn hyper binary clauses") \
OPTION(hbrsizelim, int, 1e9, 3, 1e9, "max size HBR base clause") \
OPTION(keepglue, int, 2, 1,1e9, "glue kept learned clauses") \
OPTION(keepsize, int, 3, 2,1e9, "size kept learned clauses") \
OPTION(leak, bool, 1, 0, 1, "leak solver memory") \
LOGOPT(log, bool, 0, 0, 1, "enable logging") \
LOGOPT(logsort, bool, 0, 0, 1, "sort logged clauses") \
OPTION(minimize, bool, 1, 0, 1, "minimize learned clauses") \
OPTION(minimizedepth, int, 1000, 0,1e9, "minimization depth") \
OPTION(phase, int, 1, 0, 1, "initial phase: 0=neg,1=pos") \
OPTION(posize, int, 4, 4,1e9, "size for saving position") \
OPTION(probe, bool, 1, 0, 1, "failed literal probing" ) \
OPTION(probeinit, int, 500, 0,1e9, "initial probing interval" ) \
OPTION(probeint, int, 1e4, 1,1e9, "probing interval increment" ) \
OPTION(probereleff, double, 0.02, 0, 1, "relative probing efficiency") \
OPTION(probemaxeff, double, 1e7, 0, 1, "maximum probing efficiency") \
OPTION(probemineff, double, 1e5, 0, 1, "minimum probing efficiency") \
OPTION(prefetch, bool, 1, 0, 1, "prefetch watches") \
OPTION(profile, int, 2, 0, 4, "profiling level") \
QUTOPT(quiet, bool, 0, 0, 1, "disable all messages") \
OPTION(reduceinc, int, 300, 1,1e6, "reduce limit increment") \
OPTION(reduceinit, int, 2000, 0,1e6, "initial reduce limit") \
OPTION(rephase, bool, 1, 0, 1, "enable rephasing") \
OPTION(rephaseint, int, 1e5, 1,1e9, "rephasing interval") \
OPTION(restart, bool, 1, 0, 1, "enable restarting") \
OPTION(restartint, int, 6, 1,1e9, "restart base interval") \
OPTION(restartmargin, double, 1.1, 0, 10, "restart slow fast margin") \
OPTION(reusetrail, bool, 1, 0, 1, "enable trail reuse") \
OPTION(simplify, bool, 1, 0, 1, "enable simplifier") \
OPTION(strengthen, bool, 1, 0, 1, "strengthen during subsume") \
OPTION(subsume, bool, 1, 0, 1, "enable clause subsumption") \
OPTION(subsumebinlim, int, 1e4, 0,1e9, "watch list length limit") \
OPTION(subsumeclslim, int, 1e3, 0,1e9, "clause length limit") \
OPTION(subsumeinc, int, 1e4, 1,1e9, "interval in conflicts") \
OPTION(subsumeinit, int, 1e4, 0,1e9, "initial subsume limit") \
OPTION(subsumeocclim, int, 1e2, 0,1e9, "watch list length limit") \
OPTION(trailbump, bool, 1, 0, 1, "use trail + bumped") \
OPTION(trailbumplast, double, 40, 0,100, "trail bump last level limit") \
OPTION(trailbumprops, double, 200, 0,1e9, "trail bump propagation limit") \
OPTION(transred, bool, 1, 0, 1, "transitive reduction of BIG") \
OPTION(transredreleff,double, 0.10, 0, 1, "relative efficiency") \
OPTION(transredmaxeff,double, 1e7, 0, 1, "maximum efficiency") \
OPTION(transredmineff,double, 1e5, 0, 1, "minimum efficiency") \
QUTOPT(verbose, int, 0, 0, 2, "more verbose messages") \
OPTION(vivify, bool, 1, 0, 1, "vivification") \
OPTION(vivifyreleff, double, 0.03, 0, 1, "relative efficiency") \
OPTION(vivifymaxeff, double, 1e7, 0, 1, "maximum efficiency") \
OPTION(vivifymineff, double, 1e5, 0, 1, "minimum efficiency") \
OPTION(witness, bool, 1, 0, 1, "print witness") \
/*------------------------------------------------------------------------*/
namespace CaDiCaL {
class Internal;
class Options {
Internal * internal;
bool set ( int &, const char *, const char *, const int, const int);
bool set ( bool &, const char *, const char *, const bool, const bool);
bool set (double &, const char *, const char *, const double, const double);
const char * match (const char *, const char *);
public:
// Makes options directly accessible, e.g., for instance declares the
// member 'bool Options.restart' here. This will give fast and type save
// access to option values (internally). In principle one could make all
// options simply 'double' though, but that requires double conversions
// during accessing options at run-time and disregards the intended types,
// e.g., one would need to allow fractional values for actual integer
// or boolean options. Keeping the different types makes the output of
// 'print' and 'usage' also more appealing (since correctly typed values
// are printed).
#define OPTION(N,T,V,L,H,D) \
T N;
OPTIONS
#undef OPTION
Options (Internal *);
// This sets the value of an option assuming a 'long' command line
// argument form. The argument 'arg' thus should look like
//
// "--<NAME>=<VAL>", "--<NAME>" or "--no-<NAME>"
//
// where 'NAME' is one of the option names above. Returns 'true' if the
// option was parsed and set correctly. For boolean values we strictly
// only allow "true", "false", "0" and "1" as "<VAL>" string. For 'int'
// type options we parse "<VAL>" with 'atoi' and force the resulting 'int'
// value to the 'LO' and 'HI' range and similarly for 'double' type
// options using 'atof'. If the string is not a valid 'int' for 'int'
// options or a 'double' value for 'double' options, then the function
// returns 'false'.
//
bool set (const char * arg);
// Interface to options using in a certain sense non-type-safe 'double'
// values even for 'int' and 'bool'. However, 'double' can hold a 'bool'
// as well an 'int' value precisely, e.g., if the result of 'get' is cast
// down again by the client. This would only fail for 64 byte 'long',
// which we currently do not support as option type.
//
bool has (const char * name);
double get (const char * name);
bool set (const char * name, double);
void print (); // print current values in command line form
static void usage (); // print usage message for all options
};
};
#endif
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2017 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/io/all.hpp"
#include "caf/io/network/test_multiplexer.hpp"
#include "caf/test/dsl.hpp"
namespace {
template <class BaseFixture =
test_coordinator_fixture<caf::actor_system_config>>
class test_node_fixture : public BaseFixture {
public:
using super = BaseFixture;
caf::io::middleman& mm;
caf::io::network::test_multiplexer& mpx;
caf::io::basp_broker* basp;
caf::io::connection_handle conn;
caf::io::accept_handle acc;
test_node_fixture* peer = nullptr;
caf::strong_actor_ptr stream_serv;
test_node_fixture()
: mm(this->sys.middleman()),
mpx(dynamic_cast<caf::io::network::test_multiplexer&>(mm.backend())),
basp(get_basp_broker()),
stream_serv(this->sys.stream_serv()) {
// nop
}
void publish(caf::actor whom, uint16_t port) {
auto ma = mm.actor_handle();
auto& sys = this->sys;
auto& sched = this->sched;
caf::scoped_actor self{sys};
std::set<std::string> sigs;
// Make sure no pending BASP broker messages are in the queue.
mpx.flush_runnables();
// Trigger middleman actor.
self->send(ma, caf::publish_atom::value, port,
caf::actor_cast<caf::strong_actor_ptr>(std::move(whom)),
std::move(sigs), "", false);
// Wait for the message of the middleman actor.
expect((caf::atom_value, uint16_t, caf::strong_actor_ptr,
std::set<std::string>, std::string, bool),
from(self)
.to(sys.middleman().actor_handle())
.with(caf::publish_atom::value, port, _, _, _, false));
mpx.exec_runnable();
// Fetch response.
self->receive(
[](uint16_t) {
// nop
},
[&](caf::error& err) {
CAF_FAIL(sys.render(err));
}
);
}
caf::actor remote_actor(std::string host, uint16_t port) {
CAF_MESSAGE("remote actor: " << host << ":" << port);
auto& sys = this->sys;
auto& sched = this->sched;
// both schedulers must be idle at this point
CAF_REQUIRE(!sched.has_job());
CAF_REQUIRE(!peer->sched.has_job());
// get necessary handles
auto ma = mm.actor_handle();
caf::scoped_actor self{sys};
// make sure no pending BASP broker messages are in the queue
mpx.flush_runnables();
// trigger middleman actor
self->send(ma, caf::connect_atom::value, std::move(host), port);
expect((caf::atom_value, std::string, uint16_t),
from(self).to(ma).with(caf::connect_atom::value, _, port));
CAF_MESSAGE("wait for the message of the middleman actor in BASP");
mpx.exec_runnable();
CAF_MESSAGE("tell peer to accept the connection");
peer->mpx.accept_connection(peer->acc);
CAF_MESSAGE("run handshake between the two BASP broker instances");
while (sched.run_once() || peer->sched.run_once()
|| mpx.try_exec_runnable() || peer->mpx.try_exec_runnable()
|| mpx.read_data() || peer->mpx.read_data()) {
// re-run until handhsake is fully completed
}
CAF_MESSAGE("fetch remote actor proxy");
caf::actor result;
self->receive(
[&](caf::node_id&, caf::strong_actor_ptr& ptr, std::set<std::string>&) {
result = caf::actor_cast<caf::actor>(std::move(ptr));
},
[&](caf::error& err) {
CAF_FAIL(sys.render(err));
}
);
return result;
}
private:
caf::io::basp_broker* get_basp_broker() {
auto hdl = mm.named_broker<caf::io::basp_broker>(caf::atom("BASP"));
return dynamic_cast<caf::io::basp_broker*>(
caf::actor_cast<caf::abstract_actor*>(hdl));
}
};
/// Binds `test_coordinator_fixture<Config>` to `test_node_fixture`.
template <class Config = caf::actor_system_config>
using test_node_fixture_t = test_node_fixture<test_coordinator_fixture<Config>>;
/// A simple fixture that includes two nodes (`earth` and `mars`) that are
/// connected to each other.
template <class BaseFixture =
test_coordinator_fixture<caf::actor_system_config>>
class point_to_point_fixture {
public:
using planet_type = test_node_fixture<BaseFixture>;
planet_type earth;
planet_type mars;
point_to_point_fixture() {
mars.peer = &earth;
earth.peer = &mars;
earth.acc = caf::io::accept_handle::from_int(1);
earth.conn = caf::io::connection_handle::from_int(2);
mars.acc = caf::io::accept_handle::from_int(3);
mars.conn = caf::io::connection_handle::from_int(4);
}
// Convenience function for transmitting all "network" traffic.
void network_traffic() {
while (earth.mpx.try_exec_runnable() || mars.mpx.try_exec_runnable()
|| earth.mpx.read_data() || mars.mpx.read_data()) {
// rince and repeat
}
}
// Convenience function for transmitting all "network" traffic and running
// all executables on earth and mars.
void exec_all() {
while (earth.mpx.try_exec_runnable() || mars.mpx.try_exec_runnable()
|| earth.mpx.read_data() || mars.mpx.read_data()
|| earth.sched.run_once() || mars.sched.run_once()) {
// rince and repeat
}
}
void prepare_connection(planet_type& server, planet_type& client,
std::string host, uint16_t port) {
server.mpx.prepare_connection(server.acc, server.conn, client.mpx,
std::move(host), port, client.conn);
}
};
/// Binds `test_coordinator_fixture<Config>` to `point_to_point_fixture`.
template <class Config = caf::actor_system_config>
using point_to_point_fixture_t =
point_to_point_fixture<test_coordinator_fixture<Config>>;
}// namespace <anonymous>
#define expect_on(where, types, fields) \
CAF_MESSAGE(#where << ": expect" << #types << "." << #fields); \
expect_clause< CAF_EXPAND(CAF_DSL_LIST types) >{where . sched} . fields
#define disallow_on(where, types, fields) \
CAF_MESSAGE(#where << ": disallow" << #types << "." << #fields); \
disallow_clause< CAF_EXPAND(CAF_DSL_LIST types) >{where . sched} . fields
<commit_msg>Add convenience function to I/O dsl<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2017 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/io/all.hpp"
#include "caf/io/network/test_multiplexer.hpp"
#include "caf/test/dsl.hpp"
namespace {
template <class BaseFixture =
test_coordinator_fixture<caf::actor_system_config>>
class test_node_fixture : public BaseFixture {
public:
using super = BaseFixture;
caf::io::middleman& mm;
caf::io::network::test_multiplexer& mpx;
caf::io::basp_broker* basp;
caf::io::connection_handle conn;
caf::io::accept_handle acc;
test_node_fixture* peer = nullptr;
caf::strong_actor_ptr stream_serv;
test_node_fixture()
: mm(this->sys.middleman()),
mpx(dynamic_cast<caf::io::network::test_multiplexer&>(mm.backend())),
basp(get_basp_broker()),
stream_serv(this->sys.stream_serv()) {
// nop
}
// Convenience function for transmitting all "network" traffic and running
// all executables on this node.
void exec_all() {
while (mpx.try_exec_runnable() || mpx.read_data()
|| this->sched.run_once()) {
// rince and repeat
}
}
void publish(caf::actor whom, uint16_t port) {
auto ma = mm.actor_handle();
auto& sys = this->sys;
auto& sched = this->sched;
caf::scoped_actor self{sys};
std::set<std::string> sigs;
// Make sure no pending BASP broker messages are in the queue.
mpx.flush_runnables();
// Trigger middleman actor.
self->send(ma, caf::publish_atom::value, port,
caf::actor_cast<caf::strong_actor_ptr>(std::move(whom)),
std::move(sigs), "", false);
// Wait for the message of the middleman actor.
expect((caf::atom_value, uint16_t, caf::strong_actor_ptr,
std::set<std::string>, std::string, bool),
from(self)
.to(sys.middleman().actor_handle())
.with(caf::publish_atom::value, port, _, _, _, false));
mpx.exec_runnable();
// Fetch response.
self->receive(
[](uint16_t) {
// nop
},
[&](caf::error& err) {
CAF_FAIL(sys.render(err));
}
);
}
caf::actor remote_actor(std::string host, uint16_t port) {
CAF_MESSAGE("remote actor: " << host << ":" << port);
auto& sys = this->sys;
auto& sched = this->sched;
// both schedulers must be idle at this point
CAF_REQUIRE(!sched.has_job());
CAF_REQUIRE(!peer->sched.has_job());
// get necessary handles
auto ma = mm.actor_handle();
caf::scoped_actor self{sys};
// make sure no pending BASP broker messages are in the queue
mpx.flush_runnables();
// trigger middleman actor
self->send(ma, caf::connect_atom::value, std::move(host), port);
expect((caf::atom_value, std::string, uint16_t),
from(self).to(ma).with(caf::connect_atom::value, _, port));
CAF_MESSAGE("wait for the message of the middleman actor in BASP");
mpx.exec_runnable();
CAF_MESSAGE("tell peer to accept the connection");
peer->mpx.accept_connection(peer->acc);
CAF_MESSAGE("run handshake between the two BASP broker instances");
while (sched.run_once() || peer->sched.run_once()
|| mpx.try_exec_runnable() || peer->mpx.try_exec_runnable()
|| mpx.read_data() || peer->mpx.read_data()) {
// re-run until handhsake is fully completed
}
CAF_MESSAGE("fetch remote actor proxy");
caf::actor result;
self->receive(
[&](caf::node_id&, caf::strong_actor_ptr& ptr, std::set<std::string>&) {
result = caf::actor_cast<caf::actor>(std::move(ptr));
},
[&](caf::error& err) {
CAF_FAIL(sys.render(err));
}
);
return result;
}
private:
caf::io::basp_broker* get_basp_broker() {
auto hdl = mm.named_broker<caf::io::basp_broker>(caf::atom("BASP"));
return dynamic_cast<caf::io::basp_broker*>(
caf::actor_cast<caf::abstract_actor*>(hdl));
}
};
/// Binds `test_coordinator_fixture<Config>` to `test_node_fixture`.
template <class Config = caf::actor_system_config>
using test_node_fixture_t = test_node_fixture<test_coordinator_fixture<Config>>;
/// A simple fixture that includes two nodes (`earth` and `mars`) that are
/// connected to each other.
template <class BaseFixture =
test_coordinator_fixture<caf::actor_system_config>>
class point_to_point_fixture {
public:
using planet_type = test_node_fixture<BaseFixture>;
planet_type earth;
planet_type mars;
point_to_point_fixture() {
mars.peer = &earth;
earth.peer = &mars;
earth.acc = caf::io::accept_handle::from_int(1);
earth.conn = caf::io::connection_handle::from_int(2);
mars.acc = caf::io::accept_handle::from_int(3);
mars.conn = caf::io::connection_handle::from_int(4);
}
// Convenience function for transmitting all "network" traffic.
void network_traffic() {
while (earth.mpx.try_exec_runnable() || mars.mpx.try_exec_runnable()
|| earth.mpx.read_data() || mars.mpx.read_data()) {
// rince and repeat
}
}
// Convenience function for transmitting all "network" traffic and running
// all executables on earth and mars.
void exec_all() {
while (earth.mpx.try_exec_runnable() || mars.mpx.try_exec_runnable()
|| earth.mpx.read_data() || mars.mpx.read_data()
|| earth.sched.run_once() || mars.sched.run_once()) {
// rince and repeat
}
}
void prepare_connection(planet_type& server, planet_type& client,
std::string host, uint16_t port) {
server.mpx.prepare_connection(server.acc, server.conn, client.mpx,
std::move(host), port, client.conn);
}
};
/// Binds `test_coordinator_fixture<Config>` to `point_to_point_fixture`.
template <class Config = caf::actor_system_config>
using point_to_point_fixture_t =
point_to_point_fixture<test_coordinator_fixture<Config>>;
}// namespace <anonymous>
#define expect_on(where, types, fields) \
CAF_MESSAGE(#where << ": expect" << #types << "." << #fields); \
expect_clause< CAF_EXPAND(CAF_DSL_LIST types) >{where . sched} . fields
#define disallow_on(where, types, fields) \
CAF_MESSAGE(#where << ": disallow" << #types << "." << #fields); \
disallow_clause< CAF_EXPAND(CAF_DSL_LIST types) >{where . sched} . fields
<|endoftext|> |
<commit_before>/*
Simple Addressbook for KMail
Copyright Stefan Taferner <taferner@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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kaddrbookexternal.h"
#include "kaddressbookcore_interface.h"
#include <kabc/distributionlist.h>
#include <kabc/resource.h>
#include <kabc/stdaddressbook.h>
#include <kabc/vcardconverter.h>
#include <kabc/errorhandler.h>
#include <kresources/selectdialog.h>
#include <kdefakes.h> // usleep
#include <KDebug>
#include <KLocale>
#include <KMessageBox>
#include <KToolInvocation>
#include <QApplication>
#include <QEventLoop>
#include <QList>
#include <QRegExp>
#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusConnection>
#include <unistd.h>
using namespace KPIM;
//-----------------------------------------------------------------------------
void KAddrBookExternal::openEmail( const QString &email, const QString &addr, QWidget *) {
KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );
KABC::Addressee::List addresseeList = addressBook->findByEmail(email);
// If KAddressbook is running, talk to it, otherwise start it.
QDBusInterface abinterface( "org.kde.kaddressbook", "/kaddressbook_PimApplication",
"org.kde.KUniqueApplication" );
if ( abinterface.isValid() ) {
//make sure kaddressbook is loaded, otherwise showContactEditor
//won't work as desired, see bug #87233
abinterface.call("newInstance", QByteArray(), QByteArray());
} else {
KToolInvocation::startServiceByDesktopName( "kaddressbook" );
}
OrgKdeKAddressbookCoreInterface interface( "org.kde.kaddressbook",
"/KAddressBook",
QDBusConnection::sessionBus() );
if( !addresseeList.isEmpty() ) {
interface.showContactEditor( addresseeList.first().uid() );
} else {
interface.addEmail( addr );
}
}
//-----------------------------------------------------------------------------
void KAddrBookExternal::addEmail( const QString &addr, QWidget *parent )
{
QString email;
QString name;
KABC::Addressee::parseEmailAddress( addr, name, email );
KABC::AddressBook *ab = KABC::StdAddressBook::self( true );
ab->setErrorHandler( new KABC::GuiErrorHandler( parent ) );
// force a reload of the address book file so that changes that were made
// by other programs are loaded
ab->asyncLoad();
KABC::Addressee::List addressees = ab->findByEmail( email );
if ( addressees.isEmpty() ) {
KABC::Addressee a;
a.setNameFromString( name );
a.insertEmail( email, true );
if ( KAddrBookExternal::addAddressee( a ) ) {
QString text = i18n( "<qt>The email address <b>%1</b> was added to your "
"address book; you can add more information to this "
"entry by opening the address book.</qt>", addr );
KMessageBox::information( parent, text, QString(), "addedtokabc" );
}
} else {
QString text =
i18n( "<qt>The email address <b>%1</b> is already in your address book.</qt>", addr );
KMessageBox::information( parent, text, QString(), "alreadyInAddressBook" );
}
ab->setErrorHandler( 0 );
}
void KAddrBookExternal::openAddressBook( QWidget * )
{
KToolInvocation::startServiceByDesktopName( "kaddressbook" );
}
void KAddrBookExternal::addNewAddressee( QWidget * )
{
KToolInvocation::startServiceByDesktopName( "kaddressbook" );
OrgKdeKAddressbookCoreInterface interface( "org.kde.kaddressbook",
"/KAddressBook",
QDBusConnection::sessionBus() );
interface.newContact();
}
bool KAddrBookExternal::addVCard( const KABC::Addressee &addressee, QWidget *parent )
{
KABC::AddressBook *ab = KABC::StdAddressBook::self( true );
bool inserted = false;
ab->setErrorHandler( new KABC::GuiErrorHandler( parent ) );
KABC::Addressee::List addressees =
ab->findByEmail( addressee.preferredEmail() );
if ( addressees.isEmpty() ) {
if ( KAddrBookExternal::addAddressee( addressee ) ) {
QString text = i18n( "The VCard was added to your address book; "
"you can add more information to this "
"entry by opening the address book." );
KMessageBox::information( parent, text, QString(), "addedtokabc" );
inserted = true;
}
} else {
QString text = i18n( "The VCard's primary email address is already in "
"your address book; however, you may save the VCard "
"into a file and import it into the address book manually." );
KMessageBox::information( parent, text );
inserted = true;
}
ab->setErrorHandler( 0 );
return inserted;
}
bool KAddrBookExternal::addAddressee( const KABC::Addressee &addr )
{
KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );
// PORT. FIXME: This ugly hack will be removed in 4.0
while ( !addressBook->loadingHasFinished() ) {
qApp->processEvents( QEventLoop::ExcludeUserInputEvents );
// use sleep here to reduce cpu usage
usleep( 100 );
}
// Select a resource
QList<KABC::Resource*> kabcResources = addressBook->resources();
QList<KRES::Resource*> kresResources;
QListIterator<KABC::Resource*> resIt( kabcResources );
KABC::Resource *kabcResource;
while ( resIt.hasNext() ) {
kabcResource = resIt.next();
if ( !kabcResource->readOnly() ) {
KRES::Resource *res = static_cast<KRES::Resource*>( kabcResource );
if ( res ) {
kresResources.append( res );
}
}
}
kabcResource =
static_cast<KABC::Resource*>( KRES::SelectDialog::getResource( kresResources, 0 ) );
KABC::Ticket *ticket = addressBook->requestSaveTicket( kabcResource );
bool saved = false;
if ( ticket ) {
KABC::Addressee addressee( addr );
addressee.setResource( kabcResource );
addressBook->insertAddressee( addressee );
saved = addressBook->save( ticket );
if ( !saved ) {
addressBook->releaseSaveTicket( ticket );
}
}
addressBook->emitAddressBookChanged();
return saved;
}
QString KAddrBookExternal::expandDistributionList( const QString &listName )
{
if ( listName.isEmpty() ) {
return QString();
}
const QString lowerListName = listName.toLower();
KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );
KABC::DistributionList* list = addressBook->findDistributionListByName( listName, Qt::CaseInsensitive );
if ( list ) {
return list->emails().join( ", " );
}
return QString();
}
<commit_msg>We canceled store in resource => don't store it (don't know how it works before and not crash... perhaps it fallbacked on default resources when resource selected was nil)<commit_after>/*
Simple Addressbook for KMail
Copyright Stefan Taferner <taferner@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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kaddrbookexternal.h"
#include "kaddressbookcore_interface.h"
#include <kabc/distributionlist.h>
#include <kabc/resource.h>
#include <kabc/stdaddressbook.h>
#include <kabc/vcardconverter.h>
#include <kabc/errorhandler.h>
#include <kresources/selectdialog.h>
#include <kdefakes.h> // usleep
#include <KDebug>
#include <KLocale>
#include <KMessageBox>
#include <KToolInvocation>
#include <QApplication>
#include <QEventLoop>
#include <QList>
#include <QRegExp>
#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusConnection>
#include <unistd.h>
using namespace KPIM;
//-----------------------------------------------------------------------------
void KAddrBookExternal::openEmail( const QString &email, const QString &addr, QWidget *) {
KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );
KABC::Addressee::List addresseeList = addressBook->findByEmail(email);
// If KAddressbook is running, talk to it, otherwise start it.
QDBusInterface abinterface( "org.kde.kaddressbook", "/kaddressbook_PimApplication",
"org.kde.KUniqueApplication" );
if ( abinterface.isValid() ) {
//make sure kaddressbook is loaded, otherwise showContactEditor
//won't work as desired, see bug #87233
abinterface.call("newInstance", QByteArray(), QByteArray());
} else {
KToolInvocation::startServiceByDesktopName( "kaddressbook" );
}
OrgKdeKAddressbookCoreInterface interface( "org.kde.kaddressbook",
"/KAddressBook",
QDBusConnection::sessionBus() );
if( !addresseeList.isEmpty() ) {
interface.showContactEditor( addresseeList.first().uid() );
} else {
interface.addEmail( addr );
}
}
//-----------------------------------------------------------------------------
void KAddrBookExternal::addEmail( const QString &addr, QWidget *parent )
{
QString email;
QString name;
KABC::Addressee::parseEmailAddress( addr, name, email );
KABC::AddressBook *ab = KABC::StdAddressBook::self( true );
ab->setErrorHandler( new KABC::GuiErrorHandler( parent ) );
// force a reload of the address book file so that changes that were made
// by other programs are loaded
ab->asyncLoad();
KABC::Addressee::List addressees = ab->findByEmail( email );
if ( addressees.isEmpty() ) {
KABC::Addressee a;
a.setNameFromString( name );
a.insertEmail( email, true );
if ( KAddrBookExternal::addAddressee( a ) ) {
QString text = i18n( "<qt>The email address <b>%1</b> was added to your "
"address book; you can add more information to this "
"entry by opening the address book.</qt>", addr );
KMessageBox::information( parent, text, QString(), "addedtokabc" );
}
} else {
QString text =
i18n( "<qt>The email address <b>%1</b> is already in your address book.</qt>", addr );
KMessageBox::information( parent, text, QString(), "alreadyInAddressBook" );
}
ab->setErrorHandler( 0 );
}
void KAddrBookExternal::openAddressBook( QWidget * )
{
KToolInvocation::startServiceByDesktopName( "kaddressbook" );
}
void KAddrBookExternal::addNewAddressee( QWidget * )
{
KToolInvocation::startServiceByDesktopName( "kaddressbook" );
OrgKdeKAddressbookCoreInterface interface( "org.kde.kaddressbook",
"/KAddressBook",
QDBusConnection::sessionBus() );
interface.newContact();
}
bool KAddrBookExternal::addVCard( const KABC::Addressee &addressee, QWidget *parent )
{
KABC::AddressBook *ab = KABC::StdAddressBook::self( true );
bool inserted = false;
ab->setErrorHandler( new KABC::GuiErrorHandler( parent ) );
KABC::Addressee::List addressees =
ab->findByEmail( addressee.preferredEmail() );
if ( addressees.isEmpty() ) {
if ( KAddrBookExternal::addAddressee( addressee ) ) {
QString text = i18n( "The VCard was added to your address book; "
"you can add more information to this "
"entry by opening the address book." );
KMessageBox::information( parent, text, QString(), "addedtokabc" );
inserted = true;
}
} else {
QString text = i18n( "The VCard's primary email address is already in "
"your address book; however, you may save the VCard "
"into a file and import it into the address book manually." );
KMessageBox::information( parent, text );
inserted = true;
}
ab->setErrorHandler( 0 );
return inserted;
}
bool KAddrBookExternal::addAddressee( const KABC::Addressee &addr )
{
KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );
// PORT. FIXME: This ugly hack will be removed in 4.0
while ( !addressBook->loadingHasFinished() ) {
qApp->processEvents( QEventLoop::ExcludeUserInputEvents );
// use sleep here to reduce cpu usage
usleep( 100 );
}
// Select a resource
QList<KABC::Resource*> kabcResources = addressBook->resources();
QList<KRES::Resource*> kresResources;
QListIterator<KABC::Resource*> resIt( kabcResources );
KABC::Resource *kabcResource;
while ( resIt.hasNext() ) {
kabcResource = resIt.next();
if ( !kabcResource->readOnly() ) {
KRES::Resource *res = static_cast<KRES::Resource*>( kabcResource );
if ( res ) {
kresResources.append( res );
}
}
}
kabcResource =
static_cast<KABC::Resource*>( KRES::SelectDialog::getResource( kresResources, 0 ) );
if( !kabcResource )
return false;
KABC::Ticket *ticket = addressBook->requestSaveTicket( kabcResource );
bool saved = false;
if ( ticket ) {
KABC::Addressee addressee( addr );
addressee.setResource( kabcResource );
addressBook->insertAddressee( addressee );
saved = addressBook->save( ticket );
if ( !saved ) {
addressBook->releaseSaveTicket( ticket );
}
}
addressBook->emitAddressBookChanged();
return saved;
}
QString KAddrBookExternal::expandDistributionList( const QString &listName )
{
if ( listName.isEmpty() ) {
return QString();
}
const QString lowerListName = listName.toLower();
KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );
KABC::DistributionList* list = addressBook->findDistributionListByName( listName, Qt::CaseInsensitive );
if ( list ) {
return list->emails().join( ", " );
}
return QString();
}
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief デバイス用ラッパークラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/glfw3_app/blob/master/LICENSE
*/
//=====================================================================//
#include <GLFW/glfw3.h>
#include "core/device.hpp"
namespace gl {
//-----------------------------------------------------------------//
/*!
@brief サービス@n
サンプリングと状態の作成
@param[in] bits スイッチの状態
@param[in] poss 位置情報
*/
//-----------------------------------------------------------------//
void device::service(const bits_t& bits, const locator& poss)
{
bits_t b = bits;
int joy = 0;
if(glfwJoystickPresent(joy) == GL_TRUE) {
int count;
const float* axes = glfwGetJoystickAxes(joy, &count);
for(int i = 0; i < count; ++i) {
if(i == 1) {
if(axes[i] > 0.5f) b.set(key::GAME_UP);
else if(axes[i] < -0.5f) b.set(key::GAME_DOWN);
} else if(i == 0) {
if(axes[i] > 0.5f) b.set(key::GAME_RIGHT);
else if(axes[i] < -0.5f) b.set(key::GAME_LEFT);
}
}
const unsigned char* bl = glfwGetJoystickButtons(joy, &count);
if(count > 16) count = 16;
for(int i = 0; i < count; ++i) {
if(bl[i] != 0) b.set(static_cast<key>(static_cast<int>(key::GAME_0) + i));
}
}
b.set(key::STATE_CAPS_LOCK, level_.test(key::STATE_CAPS_LOCK));
b.set(key::STATE_SCROLL_LOCK, level_.test(key::STATE_SCROLL_LOCK));
b.set(key::STATE_NUM_LOCK, level_.test(key::STATE_NUM_LOCK));
positive_ = b & ~level_;
negative_ = ~b & level_;
if(positive_.test(key::CAPS_LOCK)) {
b.flip(key::STATE_CAPS_LOCK);
}
if(positive_.test(key::SCROLL_LOCK)) {
b.flip(key::STATE_SCROLL_LOCK);
}
if(positive_.test(key::NUM_LOCK)) {
b.flip(key::STATE_NUM_LOCK);
}
level_ = b;
locator_ = poss;
}
}
<commit_msg>Update: Change JoystickAxis to JoystickHat<commit_after>//=====================================================================//
/*! @file
@brief デバイス用ラッパークラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/glfw3_app/blob/master/LICENSE
*/
//=====================================================================//
#include <GLFW/glfw3.h>
#include "core/device.hpp"
namespace gl {
//-----------------------------------------------------------------//
/*!
@brief サービス@n
サンプリングと状態の作成
@param[in] bits スイッチの状態
@param[in] poss 位置情報
*/
//-----------------------------------------------------------------//
void device::service(const bits_t& bits, const locator& poss)
{
bits_t b = bits;
int joy = GLFW_JOYSTICK_1; // first JOY-STICK
if(glfwJoystickPresent(joy) == GL_TRUE) {
int count;
const unsigned char* hats = glfwGetJoystickHats(joy, &count);
if((hats[0] & GLFW_HAT_UP) != 0) {
b.set(key::GAME_UP);
}
if((hats[0] & GLFW_HAT_DOWN) != 0) {
b.set(key::GAME_DOWN);
}
if((hats[0] & GLFW_HAT_LEFT) != 0) {
b.set(key::GAME_LEFT);
}
if((hats[0] & GLFW_HAT_RIGHT) != 0) {
b.set(key::GAME_RIGHT);
}
// const float* axes = glfwGetJoystickAxes(joy, &count);
// for(int i = 0; i < count; ++i) {
// if(i == 1) {
// if(axes[i] > 0.5f) b.set(key::GAME_UP);
// else if(axes[i] < -0.5f) b.set(key::GAME_DOWN);
// } else if(i == 0) {
// if(axes[i] > 0.5f) b.set(key::GAME_RIGHT);
// else if(axes[i] < -0.5f) b.set(key::GAME_LEFT);
// }
// }
const unsigned char* bl = glfwGetJoystickButtons(joy, &count);
if(count > 16) count = 16;
for(int i = 0; i < count; ++i) {
if(bl[i] != 0) b.set(static_cast<key>(static_cast<int>(key::GAME_0) + i));
}
}
b.set(key::STATE_CAPS_LOCK, level_.test(key::STATE_CAPS_LOCK));
b.set(key::STATE_SCROLL_LOCK, level_.test(key::STATE_SCROLL_LOCK));
b.set(key::STATE_NUM_LOCK, level_.test(key::STATE_NUM_LOCK));
positive_ = b & ~level_;
negative_ = ~b & level_;
if(positive_.test(key::CAPS_LOCK)) {
b.flip(key::STATE_CAPS_LOCK);
}
if(positive_.test(key::SCROLL_LOCK)) {
b.flip(key::STATE_SCROLL_LOCK);
}
if(positive_.test(key::NUM_LOCK)) {
b.flip(key::STATE_NUM_LOCK);
}
level_ = b;
locator_ = poss;
}
}
<|endoftext|> |
<commit_before>/**
* @file attributes.hpp
* @brief attributes utilities.
* @author zer0
* @date 2016-07-22
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_MACRO_ATTRIBUTES_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_MACRO_ATTRIBUTES_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/macro/platform.hpp>
#include <libtbag/macro/compiler.hpp>
#ifndef ATTRIBUTE_FORCE_INLINE
# if defined(__COMP_GNUC_CXX__) && (__COMP_GNUC_VERSION__ >= 30100)
# define ATTRIBUTE_FORCE_INLINE __attribute__((always_inline)) inline
# elif defined(__COMP_MSVC__)
# define ATTRIBUTE_FORCE_INLINE __forceinline
# else
# define ATTRIBUTE_FORCE_INLINE inline
# endif
#endif
#ifndef ATTRIBUTE_DEPRECATED
# if defined(__COMP_GNUC_CXX__) && (__COMP_GNUC_VERSION__ >= 30100)
# define ATTRIBUTE_DEPRECATED __attribute__((deprecated))
# elif defined(__COMP_MSVC__)
# define ATTRIBUTE_DEPRECATED __declspec(deprecated)
# else
# define ATTRIBUTE_DEPRECATED
# endif
#endif
#ifndef ATTRIBUTE_NORETURN
# if defined(__COMP_GNUC_CXX__) && (__COMP_GNUC_VERSION__ >= 20500)
# define ATTRIBUTE_NORETURN __attribute__((noreturn))
# else
# define ATTRIBUTE_NORETURN
# endif
#endif
#ifndef ATTRIBUTE_NO_WARNING_DEPRECATED
# if defined(__COMP_GNUC_CXX__) && (__COMP_GNUC_VERSION__ >= 40600)
# define ATTRIBUTE_NO_WARNING_DEPRECATED(code) \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") \
code; \
_Pragma("GCC diagnostic pop")
# elif defined(__COMP_MSVC__)
# define ATTRIBUTE_NO_WARNING_DEPRECATED(code) \
__pragma(warning(push)) \
__pragma(warning(disable : 4996)) \
code; \
__pragma(warning(pop))
# else
# define ATTRIBUTE_NO_WARNING_DEPRECATED(code)
# endif
#endif
#if defined(TBAG_EXPORT_API)
# if defined(__PLATFORM_WINDOWS__)
# define TBAG_API __declspec(dllexport)
# elif defined(__COMP_GNUC__) && (__COMP_GNUC_VERSION__ >= 40000)
# define TBAG_API __attribute__((visibility("default")))
# else
# define TBAG_API
# endif
#else // defined(TBAG_EXPORT_API)
# if defined(__PLATFORM_WINDOWS__)
# define TBAG_API __declspec(dllimport)
# else
# define TBAG_API
# endif
#endif // defined(TBAG_EXPORT_API)
#if defined(TBAG_EXPORT_API) && defined(__COMP_GNUC__)
# define TBAG_CONSTRUCTOR __attribute__((constructor))
# define TBAG_DESTRUCTOR __attribute__((destructor))
#else // defined(TBAG_EXPORT_API)
# define TBAG_CONSTRUCTOR
# define TBAG_DESTRUCTOR
#endif // defined(TBAG_EXPORT_API)
#endif // __INCLUDE_LIBTBAG__LIBTBAG_MACRO_ATTRIBUTES_HPP__
<commit_msg>Create TBAG_PUSH_MACRO & TBAG_POP_MACRO macros.<commit_after>/**
* @file attributes.hpp
* @brief attributes utilities.
* @author zer0
* @date 2016-07-22
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_MACRO_ATTRIBUTES_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_MACRO_ATTRIBUTES_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/macro/platform.hpp>
#include <libtbag/macro/compiler.hpp>
#ifndef ATTRIBUTE_FORCE_INLINE
# if defined(__COMP_GNUC_CXX__) && (__COMP_GNUC_VERSION__ >= 30100)
# define ATTRIBUTE_FORCE_INLINE __attribute__((always_inline)) inline
# elif defined(__COMP_MSVC__)
# define ATTRIBUTE_FORCE_INLINE __forceinline
# else
# define ATTRIBUTE_FORCE_INLINE inline
# endif
#endif
#ifndef ATTRIBUTE_DEPRECATED
# if defined(__COMP_GNUC_CXX__) && (__COMP_GNUC_VERSION__ >= 30100)
# define ATTRIBUTE_DEPRECATED __attribute__((deprecated))
# elif defined(__COMP_MSVC__)
# define ATTRIBUTE_DEPRECATED __declspec(deprecated)
# else
# define ATTRIBUTE_DEPRECATED
# endif
#endif
#ifndef ATTRIBUTE_NORETURN
# if defined(__COMP_GNUC_CXX__) && (__COMP_GNUC_VERSION__ >= 20500)
# define ATTRIBUTE_NORETURN __attribute__((noreturn))
# else
# define ATTRIBUTE_NORETURN
# endif
#endif
#ifndef ATTRIBUTE_NO_WARNING_DEPRECATED
# if defined(__COMP_GNUC_CXX__) && (__COMP_GNUC_VERSION__ >= 40600)
# define ATTRIBUTE_NO_WARNING_DEPRECATED(code) \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") \
code; \
_Pragma("GCC diagnostic pop")
# elif defined(__COMP_MSVC__)
# define ATTRIBUTE_NO_WARNING_DEPRECATED(code) \
__pragma(warning(push)) \
__pragma(warning(disable : 4996)) \
code; \
__pragma(warning(pop))
# else
# define ATTRIBUTE_NO_WARNING_DEPRECATED(code)
# endif
#endif
#ifndef TBAG_PUSH_MACRO
# if defined(__COMP_GNUC_CXX__)
# define TBAG_PUSH_MACRO(name) _Pragma("push_macro(\"" #name "\")")
# elif defined(__COMP_MSVC__)
# define TBAG_PUSH_MACRO(name) __pragma(push_macro("\"" #name "\""))
# else
# define TBAG_PUSH_MACRO(name)
# endif
#endif
#ifndef TBAG_POP_MACRO
# if defined(__COMP_GNUC_CXX__)
# define TBAG_POP_MACRO(name) _Pragma("pop_macro(\"" #name "\")")
# elif defined(__COMP_MSVC__)
# define TBAG_POP_MACRO(name) __pragma(pop_macro("\"" #name "\""))
# else
# define TBAG_POP_MACRO(name)
# endif
#endif
#if defined(TBAG_EXPORT_API)
# if defined(__PLATFORM_WINDOWS__)
# define TBAG_API __declspec(dllexport)
# elif defined(__COMP_GNUC__) && (__COMP_GNUC_VERSION__ >= 40000)
# define TBAG_API __attribute__((visibility("default")))
# else
# define TBAG_API
# endif
#else // defined(TBAG_EXPORT_API)
# if defined(__PLATFORM_WINDOWS__)
# define TBAG_API __declspec(dllimport)
# else
# define TBAG_API
# endif
#endif // defined(TBAG_EXPORT_API)
#if defined(TBAG_EXPORT_API) && defined(__COMP_GNUC__)
# define TBAG_CONSTRUCTOR __attribute__((constructor))
# define TBAG_DESTRUCTOR __attribute__((destructor))
#else // defined(TBAG_EXPORT_API)
# define TBAG_CONSTRUCTOR
# define TBAG_DESTRUCTOR
#endif // defined(TBAG_EXPORT_API)
#endif // __INCLUDE_LIBTBAG__LIBTBAG_MACRO_ATTRIBUTES_HPP__
<|endoftext|> |
<commit_before>/**
* @file OS_Iocp.cpp
* @author Longwei Lai<lailongwei@126.com>
* @date 2013/10/02
* @version 1.0
*
* @brief
*/
#include "llbc/common/Export.h"
#include "llbc/common/BeforeIncl.h"
#include "llbc/core/os/OS_Console.h"
#include "llbc/core/utils/Util_Debug.h"
#include "llbc/core/os/OS_Iocp.h"
#if LLBC_TARGET_PLATFORM_WIN32
__LLBC_NS_BEGIN
LLBC_IocpHandle LLBC_CreateIocp()
{
LLBC_IocpHandle handle = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE,
LLBC_INVALID_IOCP_HANDLE,
0,
0);
if (handle == LLBC_INVALID_IOCP_HANDLE)
{
LLBC_SetLastError(LLBC_ERROR_OSAPI);
}
return handle;
}
int LLBC_AddSocketToIocp(LLBC_IocpHandle handle,
LLBC_SocketHandle sock,
void *completionKey)
{
LLBC_IocpHandle ret = ::CreateIoCompletionPort((HANDLE)sock,
handle,
(ULONG_PTR)completionKey,
0);
if (ret == LLBC_INVALID_IOCP_HANDLE)
{
LLBC_SetLastError(LLBC_ERROR_OSAPI);
trace("LLBC_AddSocketToIocp() failed, reason: %s\n", LLBC_FormatLastError());
return LLBC_FAILED;
}
return LLBC_OK;
}
int LLBC_CloseIocp(LLBC_IocpHandle handle)
{
if (::CloseHandle(handle) == FALSE)
{
LLBC_SetLastError(LLBC_ERROR_OSAPI);
return LLBC_FAILED;
}
return LLBC_OK;
}
int LLBC_GetQueuedCompletionStatus(LLBC_IocpHandle handle,
void *numOfBytes,
void **compKey,
LLBC_POverlapped *ol,
ulong milliSeconds)
{
BOOL ret = ::GetQueuedCompletionStatus(handle,
(LPDWORD)numOfBytes,
(PULONG_PTR)compKey,
(LPOVERLAPPED *)ol,
milliSeconds);
if (ret == FALSE)
{
if (::GetLastError() == WAIT_TIMEOUT)
{
LLBC_SetLastError(LLBC_ERROR_TIMEOUT);
}
else
{
LLBC_SetLastError(LLBC_ERROR_OSAPI);
}
return LLBC_FAILED;
}
return LLBC_OK;
}
__LLBC_NS_END
#endif // LLBC_TARGET_PLATFORM_WIN32
#include "llbc/common/AfterIncl.h"
<commit_msg>Fix when LLBC_GetQueuedCompletionStatus() failed, could not get real errno BUG<commit_after>/**
* @file OS_Iocp.cpp
* @author Longwei Lai<lailongwei@126.com>
* @date 2013/10/02
* @version 1.0
*
* @brief
*/
#include "llbc/common/Export.h"
#include "llbc/common/BeforeIncl.h"
#include "llbc/core/os/OS_Console.h"
#include "llbc/core/utils/Util_Debug.h"
#include "llbc/core/os/OS_Iocp.h"
#if LLBC_TARGET_PLATFORM_WIN32
__LLBC_NS_BEGIN
LLBC_IocpHandle LLBC_CreateIocp()
{
LLBC_IocpHandle handle = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE,
LLBC_INVALID_IOCP_HANDLE,
0,
0);
if (handle == LLBC_INVALID_IOCP_HANDLE)
{
LLBC_SetLastError(LLBC_ERROR_OSAPI);
}
return handle;
}
int LLBC_AddSocketToIocp(LLBC_IocpHandle handle,
LLBC_SocketHandle sock,
void *completionKey)
{
LLBC_IocpHandle ret = ::CreateIoCompletionPort((HANDLE)sock,
handle,
(ULONG_PTR)completionKey,
0);
if (ret == LLBC_INVALID_IOCP_HANDLE)
{
LLBC_SetLastError(LLBC_ERROR_OSAPI);
trace("LLBC_AddSocketToIocp() failed, reason: %s\n", LLBC_FormatLastError());
return LLBC_FAILED;
}
return LLBC_OK;
}
int LLBC_CloseIocp(LLBC_IocpHandle handle)
{
if (::CloseHandle(handle) == FALSE)
{
LLBC_SetLastError(LLBC_ERROR_OSAPI);
return LLBC_FAILED;
}
return LLBC_OK;
}
int LLBC_GetQueuedCompletionStatus(LLBC_IocpHandle handle,
void *numOfBytes,
void **compKey,
LLBC_POverlapped *ol,
ulong milliSeconds)
{
BOOL ret = ::GetQueuedCompletionStatus(handle,
(LPDWORD)numOfBytes,
(PULONG_PTR)compKey,
(LPOVERLAPPED *)ol,
milliSeconds);
if (ret == FALSE)
{
if (::GetLastError() == WAIT_TIMEOUT)
{
LLBC_SetLastError(LLBC_ERROR_TIMEOUT);
}
else
{
DWORD flags = 0;
DWORD bytesTransfer = 0;
#if LLBC_DEBUG
BOOL grRet =
#endif
::WSAGetOverlappedResult((*ol)->sock,
*ol,
&bytesTransfer,
TRUE,
&flags);
#if LLBC_DEBUG
ASSERT(grRet == FALSE && "llbc library internal error, in LLBC_GetQueuedCompletionStatus()!");
#endif
LLBC_SetLastError(LLBC_ERROR_NETAPI);
}
return LLBC_FAILED;
}
return LLBC_OK;
}
__LLBC_NS_END
#endif // LLBC_TARGET_PLATFORM_WIN32
#include "llbc/common/AfterIncl.h"
<|endoftext|> |
<commit_before>
#include <cassert>
#include <QKeyEvent>
#include <QVector4D>
#include <QRectF>
#include <QPointF>
#include <QPolygonF>
#include "Terrain.h"
#include "FileAssociatedShader.h"
#include "FileAssociatedTexture.h"
#include "Camera.h"
#include "Canvas.h"
#include "PatchedTerrain.h"
#include "ScreenAlignedQuad.h"
#include "Painter.h"
namespace
{
}
Painter::Painter()
: m_camera(nullptr)
, m_quad(nullptr)
, m_terrain(nullptr)
, m_height (-1)
, m_normals(-1)
, m_diffuse(-1)
, m_detail (-1)
, m_detailn(-1)
, m_drawLineStrips(false)
, m_precission(1.f)
, m_level(0)
, m_debug(false)
{
setMode(PaintMode0);
}
Painter::~Painter()
{
qDeleteAll(m_programs);
qDeleteAll(m_shaders);
FileAssociatedTexture::clean(*this);
}
bool Painter::initialize()
{
initializeOpenGLFunctions();
// Note: As always, feel free to change/modify parameters .. as long as its possible to
// see the terrain and navigation basically works, everything is ok.
glClearColor(1.f, 1.f, 1.f, 0.f);
m_quad = new ScreenAlignedQuad(*this);
QOpenGLShaderProgram * program;
program = createBasicShaderProgram("data/terrain_4_1.vert", "data/terrain_4_1.frag");
m_programs[PaintMode1] = program;
program->bindAttributeLocation("a_vertex", 0);
program->link();
// load resources - goto https://moodle.hpi3d.de/course/view.php?id=58 and download either
// the Tree Canyon Terrain or the complete Terrain Pack. Feel free to modify/exchange the data and extends/scales/offsets.
m_height = FileAssociatedTexture::getOrCreate2Dus16("data/tree_canyon_h.raw", 2048, 2048, *this, &m_heights);
// m_yOffset = -1.f;
m_yOffset = -2.f;
m_yScale = 3.f;
m_normals = FileAssociatedTexture::getOrCreate2D("data/tree_canyon_n.png", *this);
m_diffuse = FileAssociatedTexture::getOrCreate2D("data/tree_canyon_c.png", *this);
m_detail = FileAssociatedTexture::getOrCreate2D("data/moss_detail.png", *this, GL_REPEAT, GL_REPEAT);
m_detailn = FileAssociatedTexture::getOrCreate2D("data/moss_detail_n.png", *this, GL_REPEAT, GL_REPEAT);
//m_detailc = FileAssociatedTexture::getOrCreate2D("data/moss-detail-c.png", *this, GL_REPEAT, GL_REPEAT);
// Task_4_1 - ToDo Begin
// Pick your maximum tree traversal depth/level (or recursion depth)
// This should limit the minimum extend of a single patch in respect to the terrain
// and your approach (4x4 or 2x2 subdivisions)
m_level = 2;
// Pick a starting LOD for your patches (the enumeration still remains on 0, 1, and 2, but the
// with each starting level, the resulting tiles are subdivided further, resulting in more detailed tiles.
m_terrain = new PatchedTerrain(2, *this);
// Task_4_1 - ToDo End
glClearColor(0.6f, 0.8f, 0.94f, 1.f);
return true;
}
void Painter::keyPressEvent(QKeyEvent * event)
{
switch (event->key())
{
case Qt::Key_L:
m_drawLineStrips = !m_drawLineStrips;
update();
break;
case Qt::Key_C:
m_debug = !m_debug;
update();
break;
case Qt::Key_P:
m_precission *= (event->modifiers() && Qt::Key_Shift ? 1.1f : 1.f / 1.1f);
patchify();
break;
default:
break;
}
}
QOpenGLShaderProgram * Painter::createBasicShaderProgram(
const QString & vertexShaderFileName
, const QString & fragmentShaderFileName)
{
QOpenGLShaderProgram * program = new QOpenGLShaderProgram();
m_shaders << FileAssociatedShader::getOrCreate(
QOpenGLShader::Vertex, vertexShaderFileName, *program);
m_shaders << FileAssociatedShader::getOrCreate(
QOpenGLShader::Fragment, fragmentShaderFileName, *program);
program->bindAttributeLocation("a_vertex", 0);
program->link();
return program;
}
QOpenGLShaderProgram * Painter::createBasicShaderProgram(
const QString & vertexShaderFileName
, const QString & geometryShaderFileName
, const QString & fragmentShaderFileName)
{
QOpenGLShaderProgram * program = new QOpenGLShaderProgram();
m_shaders << FileAssociatedShader::getOrCreate(
QOpenGLShader::Vertex, vertexShaderFileName, *program);
m_shaders << FileAssociatedShader::getOrCreate(
QOpenGLShader::Geometry, geometryShaderFileName, *program);
m_shaders << FileAssociatedShader::getOrCreate(
QOpenGLShader::Fragment, fragmentShaderFileName, *program);
program->bindAttributeLocation("a_vertex", 0);
program->link();
return program;
}
void Painter::resize(
int width
, int height)
{
glViewport(0, 0, width, height);
update();
}
void Painter::update()
{
update(m_programs.values());
}
void Painter::update(const QList<QOpenGLShaderProgram *> & programs)
{
foreach(const int i, m_programs.keys())
{
QOpenGLShaderProgram * program(m_programs[i]);
if (programs.contains(program) && program->isLinked())
{
program->bind();
switch (i)
{
case PaintMode0:
case PaintMode9:
case PaintMode8:
case PaintMode7:
case PaintMode6:
case PaintMode5:
case PaintMode4:
case PaintMode3:
case PaintMode2:
case PaintMode1:
if (!m_debug || camera()->eye() != m_cachedEye)
{
m_cachedEye = camera()->eye();
patchify();
}
program->setUniformValue("mvp", camera()->viewProjection());
program->setUniformValue("view", camera()->view());
program->setUniformValue("yScale", m_yScale);
program->setUniformValue("yOffset", m_yOffset);
program->setUniformValue("height", 0);
program->setUniformValue("normals", 1);
program->setUniformValue("diffuse", 2);
program->setUniformValue("detail", 3);
program->setUniformValue("detailn", 4);
break;
//case OtherProgram: // feel free to use more than one program per mode...
// break;
}
program->release();
}
}
}
void Painter::paint(float timef)
{
switch (mode())
{
case PaintMode0:
case PaintMode1:
paint_4_1(timef); break;
case PaintMode2:
case PaintMode3:
case PaintMode4:
//paint_1_4(timef); break;
//case PaintMode5:
// paint_1_5(timef); break;
// ...
default:
break;
}
}
// returns the height of the terrain at x, z with respect to the vertical
// scale and offset used by the vertex shader and the terrains extend of 8.0
float Painter::height(
const float x
, const float z) const
{
float y = static_cast<float>(m_heights[2048 * qBound<int>(0, 2048 * (z * 0.125 + 0.5f), 2047) + qBound<int>(0, 2048 * (x * 0.125 + 0.5), 2047)]);
y /= 65536.f;
return y * m_yScale + m_yOffset;
}
// Note: Feel free to remove your old code and start on minor cleanups and refactorings....
void Painter::patchify()
{
m_terrain->drawReset();
// Task_4_1 - ToDo Begin
// Here you should initiate the "patchification"
// You can modify the signature of patchify as it pleases you.
// This function is called whenever the camera changes.
patchify(8.f, 0.f, 0.f, 0);
// Task_4_1 - ToDo End
}
bool Painter::cull(
const QVector4D & v0
, const QVector4D & v1
, const QVector4D & v2)
{
// Task_4_1 - ToDo Begin
// This function should return true, if the tile specified by vertices v0, v1, and v2
// is within the cameras view frustum.
// Hint: you might try to use NDCs and transfer the incomming verticies appropriatelly.
// With that in mind, it should be simpler to cull...
// If you like, make use of QVector3D, QVector4D (toVector3DAffine), QPolygonF (boundingRect), and QRectF (intersects)
// Task_4_1 - ToDo End
return false;
}
void Painter::patchify(
const float extend
, const float x
, const float z
, const int level)
{
float unitSize = extend/2;
QPointF cameraPosition = QPointF(camera()->eye().x(), camera()->eye().z());
QRectF currentRect = QRectF(x + tx, z + tz, unitSize, unitSize);
// Task_4_1 - ToDo Begin
if(currentRect.contains(cameraPosition) || extend >= 0.5f)
{
m_terrain->drawPatch(QVector3D(x + tx, 0.0, z + tz), unitSize, level, level, level, level);
return;
}
// Use an ad-hoc or "static" approach where you decide to either
// subdivide the terrain patch and continue with the resulting
// children (2x2 or 4x4), or initiate a draw call of patch.
// For the draw call the LODs for all four tiles are required.
// For skipping a tile (e.g., because of culling), use LOD = 3.
// This functions signature suggest a recursive approach.
// Feel free to implement this in any way with as few or as much traversals
// /passes/recursions you need.
// Checkt out the paper "Seamless Patches for GPU-Based Terrain Rendering"
//if () // needs subdivide?
//{
//}
//else // draw patch!
//{
// // check culling
// //if (cull(.., .., ..))
// // xLOD = 3;
// // ...
// m_terrain->drawPatch(QVector3D(x, 0.0, z), extend, bLOD, rLOD, tLOD, lLOD);
for(float tx = -extend/2; tx < extend/2; tx += unitSize)
{
for(float tz = -extend/2; tz < extend/2; tz += unitSize)
{
qDebug()<<level;
if(level < 2)
patchify(unitSize, x + tx + unitSize/4, z + tz + unitSize/4, level);
else
patchify(unitSize, x + tx + unitSize/4, z + tz + unitSize/4, level);
return;
}
}
//}
// Task_4_1 - ToDo End
}
void Painter::paint_4_1(float timef)
{
QOpenGLShaderProgram * program(m_programs[PaintMode1]);
if (program->isLinked())
{
glActiveTexture(GL_TEXTURE0);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_height);
glActiveTexture(GL_TEXTURE1);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_normals);
glActiveTexture(GL_TEXTURE2);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_diffuse);
glActiveTexture(GL_TEXTURE3);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_detail);
glActiveTexture(GL_TEXTURE4);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_detailn);
m_terrain->draw(*this, *program, m_drawLineStrips);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);
}
}
<commit_msg>implemented in recursion<commit_after>
#include <cassert>
#include <QKeyEvent>
#include <QVector4D>
#include <QRectF>
#include <QPointF>
#include <QPolygonF>
#include "Terrain.h"
#include "FileAssociatedShader.h"
#include "FileAssociatedTexture.h"
#include "Camera.h"
#include "Canvas.h"
#include "PatchedTerrain.h"
#include "ScreenAlignedQuad.h"
#include "Painter.h"
namespace
{
}
Painter::Painter()
: m_camera(nullptr)
, m_quad(nullptr)
, m_terrain(nullptr)
, m_height (-1)
, m_normals(-1)
, m_diffuse(-1)
, m_detail (-1)
, m_detailn(-1)
, m_drawLineStrips(false)
, m_precission(1.f)
, m_level(0)
, m_debug(false)
{
setMode(PaintMode0);
}
Painter::~Painter()
{
qDeleteAll(m_programs);
qDeleteAll(m_shaders);
FileAssociatedTexture::clean(*this);
}
bool Painter::initialize()
{
initializeOpenGLFunctions();
// Note: As always, feel free to change/modify parameters .. as long as its possible to
// see the terrain and navigation basically works, everything is ok.
glClearColor(1.f, 1.f, 1.f, 0.f);
m_quad = new ScreenAlignedQuad(*this);
QOpenGLShaderProgram * program;
program = createBasicShaderProgram("data/terrain_4_1.vert", "data/terrain_4_1.frag");
m_programs[PaintMode1] = program;
program->bindAttributeLocation("a_vertex", 0);
program->link();
// load resources - goto https://moodle.hpi3d.de/course/view.php?id=58 and download either
// the Tree Canyon Terrain or the complete Terrain Pack. Feel free to modify/exchange the data and extends/scales/offsets.
m_height = FileAssociatedTexture::getOrCreate2Dus16("data/tree_canyon_h.raw", 2048, 2048, *this, &m_heights);
// m_yOffset = -1.f;
m_yOffset = -2.f;
m_yScale = 3.f;
m_normals = FileAssociatedTexture::getOrCreate2D("data/tree_canyon_n.png", *this);
m_diffuse = FileAssociatedTexture::getOrCreate2D("data/tree_canyon_c.png", *this);
m_detail = FileAssociatedTexture::getOrCreate2D("data/moss_detail.png", *this, GL_REPEAT, GL_REPEAT);
m_detailn = FileAssociatedTexture::getOrCreate2D("data/moss_detail_n.png", *this, GL_REPEAT, GL_REPEAT);
//m_detailc = FileAssociatedTexture::getOrCreate2D("data/moss-detail-c.png", *this, GL_REPEAT, GL_REPEAT);
// Task_4_1 - ToDo Begin
// Pick your maximum tree traversal depth/level (or recursion depth)
// This should limit the minimum extend of a single patch in respect to the terrain
// and your approach (4x4 or 2x2 subdivisions)
m_level = 2;
// Pick a starting LOD for your patches (the enumeration still remains on 0, 1, and 2, but the
// with each starting level, the resulting tiles are subdivided further, resulting in more detailed tiles.
m_terrain = new PatchedTerrain(2, *this);
// Task_4_1 - ToDo End
glClearColor(0.6f, 0.8f, 0.94f, 1.f);
return true;
}
void Painter::keyPressEvent(QKeyEvent * event)
{
switch (event->key())
{
case Qt::Key_L:
m_drawLineStrips = !m_drawLineStrips;
update();
break;
case Qt::Key_C:
m_debug = !m_debug;
update();
break;
case Qt::Key_P:
m_precission *= (event->modifiers() && Qt::Key_Shift ? 1.1f : 1.f / 1.1f);
patchify();
break;
default:
break;
}
}
QOpenGLShaderProgram * Painter::createBasicShaderProgram(
const QString & vertexShaderFileName
, const QString & fragmentShaderFileName)
{
QOpenGLShaderProgram * program = new QOpenGLShaderProgram();
m_shaders << FileAssociatedShader::getOrCreate(
QOpenGLShader::Vertex, vertexShaderFileName, *program);
m_shaders << FileAssociatedShader::getOrCreate(
QOpenGLShader::Fragment, fragmentShaderFileName, *program);
program->bindAttributeLocation("a_vertex", 0);
program->link();
return program;
}
QOpenGLShaderProgram * Painter::createBasicShaderProgram(
const QString & vertexShaderFileName
, const QString & geometryShaderFileName
, const QString & fragmentShaderFileName)
{
QOpenGLShaderProgram * program = new QOpenGLShaderProgram();
m_shaders << FileAssociatedShader::getOrCreate(
QOpenGLShader::Vertex, vertexShaderFileName, *program);
m_shaders << FileAssociatedShader::getOrCreate(
QOpenGLShader::Geometry, geometryShaderFileName, *program);
m_shaders << FileAssociatedShader::getOrCreate(
QOpenGLShader::Fragment, fragmentShaderFileName, *program);
program->bindAttributeLocation("a_vertex", 0);
program->link();
return program;
}
void Painter::resize(
int width
, int height)
{
glViewport(0, 0, width, height);
update();
}
void Painter::update()
{
update(m_programs.values());
}
void Painter::update(const QList<QOpenGLShaderProgram *> & programs)
{
foreach(const int i, m_programs.keys())
{
QOpenGLShaderProgram * program(m_programs[i]);
if (programs.contains(program) && program->isLinked())
{
program->bind();
switch (i)
{
case PaintMode0:
case PaintMode9:
case PaintMode8:
case PaintMode7:
case PaintMode6:
case PaintMode5:
case PaintMode4:
case PaintMode3:
case PaintMode2:
case PaintMode1:
if (!m_debug || camera()->eye() != m_cachedEye)
{
m_cachedEye = camera()->eye();
patchify();
}
program->setUniformValue("mvp", camera()->viewProjection());
program->setUniformValue("view", camera()->view());
program->setUniformValue("yScale", m_yScale);
program->setUniformValue("yOffset", m_yOffset);
program->setUniformValue("height", 0);
program->setUniformValue("normals", 1);
program->setUniformValue("diffuse", 2);
program->setUniformValue("detail", 3);
program->setUniformValue("detailn", 4);
break;
//case OtherProgram: // feel free to use more than one program per mode...
// break;
}
program->release();
}
}
}
void Painter::paint(float timef)
{
switch (mode())
{
case PaintMode0:
case PaintMode1:
paint_4_1(timef); break;
case PaintMode2:
case PaintMode3:
case PaintMode4:
//paint_1_4(timef); break;
//case PaintMode5:
// paint_1_5(timef); break;
// ...
default:
break;
}
}
// returns the height of the terrain at x, z with respect to the vertical
// scale and offset used by the vertex shader and the terrains extend of 8.0
float Painter::height(
const float x
, const float z) const
{
float y = static_cast<float>(m_heights[2048 * qBound<int>(0, 2048 * (z * 0.125 + 0.5f), 2047) + qBound<int>(0, 2048 * (x * 0.125 + 0.5), 2047)]);
y /= 65536.f;
return y * m_yScale + m_yOffset;
}
// Note: Feel free to remove your old code and start on minor cleanups and refactorings....
void Painter::patchify()
{
m_terrain->drawReset();
// Task_4_1 - ToDo Begin
// Here you should initiate the "patchification"
// You can modify the signature of patchify as it pleases you.
// This function is called whenever the camera changes.
patchify(8.f, 0.f, 0.f, 0);
// Task_4_1 - ToDo End
}
bool Painter::cull(
const QVector4D & v0
, const QVector4D & v1
, const QVector4D & v2)
{
// Task_4_1 - ToDo Begin
// This function should return true, if the tile specified by vertices v0, v1, and v2
// is within the cameras view frustum.
// Hint: you might try to use NDCs and transfer the incomming verticies appropriatelly.
// With that in mind, it should be simpler to cull...
// If you like, make use of QVector3D, QVector4D (toVector3DAffine), QPolygonF (boundingRect), and QRectF (intersects)
// Task_4_1 - ToDo End
return false;
}
void Painter::patchify(
const float extend
, const float x
, const float z
, const int level)
{
if(level >= 2 || extend <= 1.0f)
{
m_terrain->drawPatch(QVector3D(x, 0.0, z), extend, level, level, level, level);
return;
}
QPointF cameraPosition = QPointF(camera()->eye().x(), camera()->eye().z());
QRectF currentRect = QRectF(x, z, extend, extend);
// Task_4_1 - ToDo Begin
if(currentRect.contains(cameraPosition))
{
patchify(extend/2, x - extend/4, z - extend/4, level+1);
patchify(extend/2, x, z - extend/4, level+1);
patchify(extend/2, x, z, level+1);
patchify(extend/2, x - extend/4, z, level+1);
}
else
m_terrain->drawPatch(QVector3D(x, 0.0, z), extend, level, level, level, level);
// Use an ad-hoc or "static" approach where you decide to either
// subdivide the terrain patch and continue with the resulting
// children (2x2 or 4x4), or initiate a draw call of patch.
// For the draw call the LODs for all four tiles are required.
// For skipping a tile (e.g., because of culling), use LOD = 3.
// This functions signature suggest a recursive approach.
// Feel free to implement this in any way with as few or as much traversals
// /passes/recursions you need.
// Checkt out the paper "Seamless Patches for GPU-Based Terrain Rendering"
//if () // needs subdivide?
//{
//}
//else // draw patch!
//{
// // check culling
// //if (cull(.., .., ..))
// // xLOD = 3;
// // ...
// m_terrain->drawPatch(QVector3D(x, 0.0, z), extend, bLOD, rLOD, tLOD, lLOD);
//}
// Task_4_1 - ToDo End
}
void Painter::paint_4_1(float timef)
{
QOpenGLShaderProgram * program(m_programs[PaintMode1]);
if (program->isLinked())
{
glActiveTexture(GL_TEXTURE0);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_height);
glActiveTexture(GL_TEXTURE1);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_normals);
glActiveTexture(GL_TEXTURE2);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_diffuse);
glActiveTexture(GL_TEXTURE3);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_detail);
glActiveTexture(GL_TEXTURE4);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_detailn);
m_terrain->draw(*this, *program, m_drawLineStrips);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);
}
}
<|endoftext|> |
<commit_before>#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <cstring>
#define sizeLim 10
using namespace std;
struct arguments
{
int argc;
char **argv;
};
arguments* readPrompt();
arguments* writePrompt();
void testArgs(arguments*);
void testSuite(arguments*, string);
bool isValid(arguments*);
bool run;
int main()
{
run = true;
while (run) {
arguments * temp = writePrompt();
if (isValid(temp)) {
int status;
if (fork() != 0) {
//parent
cout<<"parent thread start"<<endl;
waitpid(-1, &status, 0);
cout<<"parent thread stopd\n";
}
else {
//child
cout<<"child start\n";
execv(*temp->argv, temp->argv);
cout<<"child stop\n";
return 0;
}
}
//system("pause");
}
//system("pause");
return 0;
}
arguments* readPrompt() {
arguments* temp = new arguments;
string rawInput;
getline(std::cin,rawInput);
temp->argc = 1;
char* ptr = new char[rawInput.length()+1];
char* head = ptr; //create unchanging head refrence so we don't advance as we create new array
temp->argv = (&head);
for (int i = 0; i < rawInput.length()+1; ++i, ++ptr) {//need to catch terminating null
if (rawInput[i] == ' ') {
rawInput[i] = NULL;
temp->argc += 1;
}
(*ptr) = rawInput[i];
}
//testSuite(temp, rawInput); commented out for production
return temp;
}
bool isValid(arguments * args) {
char* comp = *args->argv;
if (strcmp("cd", comp)==0){
chdir(&comp[3]);
return false;
}
else if(strcmp("pwd", comp)==0) {
char* WD = get_current_dir_name();
cout<<*WD<<endl;
delete WD;
return false;
}
else if(strcmp("quit", comp)==0){
run = false;
}
return true;
}
arguments* writePrompt() {
cout << ">";
return readPrompt();
}
void testArgs(arguments* args) { //just tests using our args class
char* ptr = (*args->argv);
cout << "there are " << (args->argc) << " arguments" << endl;
for (int i = 0; i < args->argc; ++i, ++ptr) {
while ((*ptr) != NULL) {
cout << (*ptr);
++ptr;
}
cout << '\n';
}
}
void testSuite(arguments* args, string input) {
char* ptr = (*args->argv);
for (int i = 0; i < args->argc; ++i, ++ptr) {
if (!input.find(ptr, strlen(ptr)-1)) {
cout << "failed test at: " << i << endl;
}
}
}
<commit_msg>fixed bad pointers<commit_after>#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <cstring>
#define sizeLim 10
using namespace std;
struct arguments
{
int argc;
char **argv;
};
arguments* readPrompt();
arguments* writePrompt();
void testArgs(arguments*);
void testSuite(arguments, string);
bool isValid(arguments*);
bool run;
extern char **environ;
int main()
{
//char* arg[] = {"ls", "-l", NULL};
//execvp(arg[0],arg);
run = true;
while (run) {
arguments * temp = writePrompt();
if (isValid(temp)) {
int status;
testArgs(temp);
cout<<&temp->argv<<endl;
if (fork() != 0) {
//parent
cout<<"parent thread start"<<endl;
waitpid(-1, &status, 0);
cout<<"parent thread end\n";
}
else {
//child
cout<<"child start\n";
cout<<&temp->argv<<endl;
testArgs(temp);
execvp(temp->argv[0], temp->argv);
cout<<"failed\n";
return 0;
}
}
//system("pause");
}
//system("pause");
return 0;
}
arguments* readPrompt() {
arguments* temp = new arguments;
string rawInput;
getline(std::cin,rawInput);
temp->argc = 1;
char* ptr = new char[rawInput.length()+1];
char* head = ptr; //create unchanging head refrence so we don't advance as we create new array
for (int i = 0; i < rawInput.length()+1; ++i, ++ptr) {//need to catch terminating null
if (rawInput[i] == ' ') {
rawInput[i] = NULL;
temp->argc += 1;
}
(*ptr) = rawInput[i];
}
temp->argv = (&head);
//testSuite(temp, rawInput); commented out for production
return temp;
}
bool isValid(arguments* args) {
char * head = *args->argv;
char* comp = *args->argv;
bool tf = true;
cout<<comp<<endl;
if (strcmp("cd", comp)==0){
chdir(&comp[3]);
tf = false;
}
else if(strcmp("pwd", comp)==0) {
char* WD = get_current_dir_name();
cout<<*WD<<endl;
delete WD;
tf = false;
}
else if(strcmp("quit", comp)==0){
run = false;
tf = false;
}
*args->argv = head;
return tf;
}
arguments* writePrompt() {
cout << ">";
return readPrompt();
}
void testArgs(arguments* args) { //just tests using our args class
char * head = *args->argv;
char* ptr = (*args->argv);
cout << "there are " << (args->argc) << " arguments" << endl;
for (int i = 0; i < args->argc; ++i, ++ptr) {
while ((*ptr) != NULL) {
cout << (*ptr);
++ptr;
}
cout << '\n';
}
*args->argv = head;
}
void testSuite(arguments* args, string input) {
char* ptr = (*args->argv);
for (int i = 0; i < args->argc; ++i, ++ptr) {
if (!input.find(ptr, strlen(ptr)-1)) {
cout << "failed test at: " << i << endl;
}
}
}
<|endoftext|> |
<commit_before>#include <Source/Headers.h>
#include "WinCoder.h"
#include "WinRaster.h"
#include "WinSearch.h"
#include "Document.h"
#include "FileSystem.h"
#include "Config.h"
// ============================================================================
static const wchar* gCoderClassName = L"CoderClass";
// ----------------------------------------------------------------------------
WinCoderFactory::WinCoderFactory()
{
_registerClass(gCoderClassName, nullptr, "\"APPICON\"");
}
// ----------------------------------------------------------------------------
retcode WinCoderFactory::createWindow(TextDocument* pDoc, WinCoder** ppWin)
{
RECT rec = { 0 };
WinCoder::getWindowClientRect(&rec);
AdjustWindowRectEx(&rec, WS_OVERLAPPEDWINDOW, FALSE, 0);
WinCoder* pWin = new WinCoder(pDoc);
HWND hwnd = CreateWindowW(gCoderClassName, L"", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, rec.right-rec.left, rec.bottom-rec.top,
nullptr, nullptr, ghInstance, static_cast<BaseWinProc*>(pWin));
if (hwnd == nullptr) {
return rcFailed;
}
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
*ppWin = pWin;
return rcSuccess;
}
// ----------------------------------------------------------------------------
int gSearchHeight = 50;
int gNavPanelWidth = 0;
// ----------------------------------------------------------------------------
void WinCoder::getWindowClientRect(RECT* prc)
{
WinRaster::getWindowClientRect(prc);
prc->right += gNavPanelWidth;
prc->bottom += gSearchHeight;
}
// ----------------------------------------------------------------------------
WinCoder::WinCoder(TextDocument* pDoc)
: _pDoc(pDoc)
, _pWinRaster(nullptr)
, _pWinSearch(nullptr)
, _hwndRaster(nullptr)
, _hwndSearch(nullptr)
, _hwndNavPanel(nullptr)
{
}
// ----------------------------------------------------------------------------
LRESULT WinCoder::proc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CREATE:
return onCreate();
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_SIZE:
return onSize(LOWORD(lParam), HIWORD(lParam), wParam);
case WM_KEYDOWN:
return onKeyDown((int)wParam, lParam & 0x0f, lParam >> 4);
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
// ----------------------------------------------------------------------------
LRESULT WinCoder::onCreate()
{
retcode rv;
WinRasterFactory WinRasterFab;
if (failed(rv = WinRasterFab.createWindow(this, &_pWinRaster))) {
return rv;
}
WinSearchFactory WinSearchFab;
if (failed(rv = WinSearchFab.createWindow(this, &_pWinSearch))) {
return rv;
}
_hwndRaster = _pWinRaster->hwnd();
_hwndSearch = _pWinSearch->hwnd();
ShowWindow(_hwndRaster, SW_SHOW);
UpdateWindow(_hwndRaster);
ShowWindow(_hwndSearch, SW_SHOW);
UpdateWindow(_hwndSearch);
onCursorDirty();
_updateTitle();
SetFocus(_hwndRaster);
return 0;
}
// --------------------------------------------------------------------------
LRESULT WinCoder::onSize(int cx, int cy, uint flags)
{
SetRect(&_rcRaster, 0, 0, cx, cy - gSearchHeight);
SetRect(&_rcSearchPanel, 0, cy - gSearchHeight, cx, cy);
SetWindowPos(_hwndRaster, nullptr,
0, 0, cx, cy - gSearchHeight,
SWP_NOZORDER);
SetWindowPos(_hwndSearch, nullptr,
0, cy - gSearchHeight,
cx, gSearchHeight,
SWP_NOZORDER);
return 0;
}
// ----------------------------------------------------------------------------
LRESULT WinCoder::onKeyDown(int chr, int RepCount, int Flags)
{
bool ControlKey = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
bool ShiftKey = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
switch (chr)
{
case VK_ESCAPE:
if (_Search.getResultCount() > 0)
{
_Search.invalidate();
_pWinSearch->updateResultCount(_Search.getResultCount());
_pWinRaster->onSearchResultDirty();
}
else
{
PostQuitMessage(0);
}
break;
case VK_F3:
goToNextResult(ShiftKey);
onCursorDirty();
break;
case 'F':
if (ControlKey) {
_pWinSearch->giveFocus(WinSearch::focusSearch);
onCursorDirty();
}
break;
case 'G':
if (ControlKey) {
_pWinSearch->giveFocus(WinSearch::focusGoToLine);
}
break;
case 'O':
if (ControlKey) {
char File[MaxFNameLength];
if (_queryFileName(File, MaxFNameLength)) {
}
}
break;
case 'R':
if (ControlKey) {
_pWinSearch->giveFocus(WinSearch::focusReplace);
onCursorDirty();
}
break;
case 'S':
if (ControlKey) {
_pDoc->save();
_updateTitle();
}
break;
case 'L':
if (ControlKey) {
_pDoc->deleteLine();
onDocumentDirty();
}
}
return 0;
}
// ----------------------------------------------------------------------------
void WinCoder::onDocumentDirty()
{
_Search.updateDocument(_pDoc->getDoc());
_pWinSearch->updateResultCount(_Search.getResultCount());
_updateTitle();
_pWinRaster->onDocumentDirty();
}
// ----------------------------------------------------------------------------
void WinCoder::onCursorDirty()
{
TextPos pos = _pDoc->getCursor();
const TextDoc* pDoc = _pDoc->getDoc();
_pWinSearch->updateCursorPos(pos, pDoc->getLineCount(), pDoc->getLineLength(pos.line));
_pWinRaster->onCursorDirty();
}
// ----------------------------------------------------------------------------
void WinCoder::onSearchResultDirty()
{
_pWinRaster->onSearchResultDirty();
}
// ----------------------------------------------------------------------------
void WinCoder::_updateTitle()
{
// Update Title Bar
char FileName[MaxFNameLength];
char Text[1000];
splitFilePath(_pDoc->getPath().c_str(), nullptr, 0, FileName, MaxFNameLength);
sprintf(Text, "%s%s", _pDoc->isDirty() ? "* " : "", FileName);
SetWindowText(_hWnd, Text);
}
// ----------------------------------------------------------------------------
void WinCoder::goToLine(size_t line)
{
const TextDoc* pDoc = _pDoc->getDoc();
size_t cLines = pDoc->getLineCount();
if (line >= cLines) {
return;
}
size_t column = pDoc->getLineLength(line);
_pDoc->setCursor(TextPos(line, column));
onCursorDirty();
_focusEditor();
}
// ----------------------------------------------------------------------------
void WinCoder::goToNextResult(bool Direction)
{
TextPos pos = _pDoc->getCursor();
if (_Search.getNextResult(&pos, Direction)) {
_pDoc->setCursor(pos);
}
onCursorDirty();
_focusEditor();
}
// ----------------------------------------------------------------------------
void WinCoder::hilightText(const char* Text, bool WholeWord, bool MatchCase)
{
if (*Text == 0) {
_Search.invalidate();
} else {
_Search.indexDocument(_pDoc->getDoc(), Text, WholeWord, MatchCase);
}
_pWinSearch->updateResultCount(_Search.getResultCount());
_pWinRaster->onSearchResultDirty();
}
// ----------------------------------------------------------------------------
bool WinCoder::_queryFileName(char *pszFile, size_t cszFile)
{
OPENFILENAMEA ofn = { 0 };
char szFileTitle[128];
const char* Title = "Open C++ File";
const char* Filter = "All Files (*.*)\0*.*\0C++ Files (*.cpp;*.h)\0*.cpp\0\0";
const char* lpszext = "cpp";
*pszFile = 0;
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = _hWnd;
ofn.hInstance = ghInstance;
ofn.lpstrFilter = Filter;
ofn.nFilterIndex = 0;
ofn.lpstrFile = pszFile;
ofn.nMaxFile = cszFile;
ofn.lpstrFileTitle = szFileTitle;
ofn.nMaxFileTitle = sizeof(szFileTitle);
ofn.lpstrTitle = Title;
ofn.lpstrDefExt = lpszext;
if (!GetOpenFileNameA(&ofn))
return false;
return true;
}
// ----------------------------------------------------------------------------
void WinCoder::_focusEditor()
{
SetFocus(_hwndRaster);
}
<commit_msg>Delegate focus to editor window if Coder window is focused.<commit_after>#include <Source/Headers.h>
#include "WinCoder.h"
#include "WinRaster.h"
#include "WinSearch.h"
#include "Document.h"
#include "FileSystem.h"
#include "Config.h"
// ============================================================================
static const wchar* gCoderClassName = L"CoderClass";
// ----------------------------------------------------------------------------
WinCoderFactory::WinCoderFactory()
{
_registerClass(gCoderClassName, nullptr, "\"APPICON\"");
}
// ----------------------------------------------------------------------------
retcode WinCoderFactory::createWindow(TextDocument* pDoc, WinCoder** ppWin)
{
RECT rec = { 0 };
WinCoder::getWindowClientRect(&rec);
AdjustWindowRectEx(&rec, WS_OVERLAPPEDWINDOW, FALSE, 0);
WinCoder* pWin = new WinCoder(pDoc);
HWND hwnd = CreateWindowW(gCoderClassName, L"", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, rec.right-rec.left, rec.bottom-rec.top,
nullptr, nullptr, ghInstance, static_cast<BaseWinProc*>(pWin));
if (hwnd == nullptr) {
return rcFailed;
}
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
*ppWin = pWin;
return rcSuccess;
}
// ----------------------------------------------------------------------------
int gSearchHeight = 50;
int gNavPanelWidth = 0;
// ----------------------------------------------------------------------------
void WinCoder::getWindowClientRect(RECT* prc)
{
WinRaster::getWindowClientRect(prc);
prc->right += gNavPanelWidth;
prc->bottom += gSearchHeight;
}
// ----------------------------------------------------------------------------
WinCoder::WinCoder(TextDocument* pDoc)
: _pDoc(pDoc)
, _pWinRaster(nullptr)
, _pWinSearch(nullptr)
, _hwndRaster(nullptr)
, _hwndSearch(nullptr)
, _hwndNavPanel(nullptr)
{
}
// ----------------------------------------------------------------------------
LRESULT WinCoder::proc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CREATE:
return onCreate();
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_SETFOCUS:
SetFocus(_hwndRaster);
break;
case WM_SIZE:
return onSize(LOWORD(lParam), HIWORD(lParam), wParam);
case WM_KEYDOWN:
return onKeyDown((int)wParam, lParam & 0x0f, lParam >> 4);
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
// ----------------------------------------------------------------------------
LRESULT WinCoder::onCreate()
{
retcode rv;
WinRasterFactory WinRasterFab;
if (failed(rv = WinRasterFab.createWindow(this, &_pWinRaster))) {
return rv;
}
WinSearchFactory WinSearchFab;
if (failed(rv = WinSearchFab.createWindow(this, &_pWinSearch))) {
return rv;
}
_hwndRaster = _pWinRaster->hwnd();
_hwndSearch = _pWinSearch->hwnd();
ShowWindow(_hwndRaster, SW_SHOW);
UpdateWindow(_hwndRaster);
ShowWindow(_hwndSearch, SW_SHOW);
UpdateWindow(_hwndSearch);
onCursorDirty();
_updateTitle();
SetFocus(_hwndRaster);
return 0;
}
// --------------------------------------------------------------------------
LRESULT WinCoder::onSize(int cx, int cy, uint flags)
{
SetRect(&_rcRaster, 0, 0, cx, cy - gSearchHeight);
SetRect(&_rcSearchPanel, 0, cy - gSearchHeight, cx, cy);
SetWindowPos(_hwndRaster, nullptr,
0, 0, cx, cy - gSearchHeight,
SWP_NOZORDER);
SetWindowPos(_hwndSearch, nullptr,
0, cy - gSearchHeight,
cx, gSearchHeight,
SWP_NOZORDER);
return 0;
}
// ----------------------------------------------------------------------------
LRESULT WinCoder::onKeyDown(int chr, int RepCount, int Flags)
{
bool ControlKey = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
bool ShiftKey = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
switch (chr)
{
case VK_ESCAPE:
if (_Search.getResultCount() > 0)
{
_Search.invalidate();
_pWinSearch->updateResultCount(_Search.getResultCount());
_pWinRaster->onSearchResultDirty();
}
else
{
PostQuitMessage(0);
}
break;
case VK_F3:
goToNextResult(ShiftKey);
onCursorDirty();
break;
case 'F':
if (ControlKey) {
_pWinSearch->giveFocus(WinSearch::focusSearch);
onCursorDirty();
}
break;
case 'G':
if (ControlKey) {
_pWinSearch->giveFocus(WinSearch::focusGoToLine);
}
break;
case 'O':
if (ControlKey) {
char File[MaxFNameLength];
if (_queryFileName(File, MaxFNameLength)) {
}
}
break;
case 'R':
if (ControlKey) {
_pWinSearch->giveFocus(WinSearch::focusReplace);
onCursorDirty();
}
break;
case 'S':
if (ControlKey) {
_pDoc->save();
_updateTitle();
}
break;
case 'L':
if (ControlKey) {
_pDoc->deleteLine();
onDocumentDirty();
}
}
return 0;
}
// ----------------------------------------------------------------------------
void WinCoder::onDocumentDirty()
{
_Search.updateDocument(_pDoc->getDoc());
_pWinSearch->updateResultCount(_Search.getResultCount());
_updateTitle();
_pWinRaster->onDocumentDirty();
}
// ----------------------------------------------------------------------------
void WinCoder::onCursorDirty()
{
TextPos pos = _pDoc->getCursor();
const TextDoc* pDoc = _pDoc->getDoc();
_pWinSearch->updateCursorPos(pos, pDoc->getLineCount(), pDoc->getLineLength(pos.line));
_pWinRaster->onCursorDirty();
}
// ----------------------------------------------------------------------------
void WinCoder::onSearchResultDirty()
{
_pWinRaster->onSearchResultDirty();
}
// ----------------------------------------------------------------------------
void WinCoder::_updateTitle()
{
// Update Title Bar
char FileName[MaxFNameLength];
char Text[1000];
splitFilePath(_pDoc->getPath().c_str(), nullptr, 0, FileName, MaxFNameLength);
sprintf(Text, "%s%s", _pDoc->isDirty() ? "* " : "", FileName);
SetWindowText(_hWnd, Text);
}
// ----------------------------------------------------------------------------
void WinCoder::goToLine(size_t line)
{
const TextDoc* pDoc = _pDoc->getDoc();
size_t cLines = pDoc->getLineCount();
if (line >= cLines) {
return;
}
size_t column = pDoc->getLineLength(line);
_pDoc->setCursor(TextPos(line, column));
onCursorDirty();
_focusEditor();
}
// ----------------------------------------------------------------------------
void WinCoder::goToNextResult(bool Direction)
{
TextPos pos = _pDoc->getCursor();
if (_Search.getNextResult(&pos, Direction)) {
_pDoc->setCursor(pos);
}
onCursorDirty();
_focusEditor();
}
// ----------------------------------------------------------------------------
void WinCoder::hilightText(const char* Text, bool WholeWord, bool MatchCase)
{
if (*Text == 0) {
_Search.invalidate();
} else {
_Search.indexDocument(_pDoc->getDoc(), Text, WholeWord, MatchCase);
}
_pWinSearch->updateResultCount(_Search.getResultCount());
_pWinRaster->onSearchResultDirty();
}
// ----------------------------------------------------------------------------
bool WinCoder::_queryFileName(char *pszFile, size_t cszFile)
{
OPENFILENAMEA ofn = { 0 };
char szFileTitle[128];
const char* Title = "Open C++ File";
const char* Filter = "All Files (*.*)\0*.*\0C++ Files (*.cpp;*.h)\0*.cpp\0\0";
const char* lpszext = "cpp";
*pszFile = 0;
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = _hWnd;
ofn.hInstance = ghInstance;
ofn.lpstrFilter = Filter;
ofn.nFilterIndex = 0;
ofn.lpstrFile = pszFile;
ofn.nMaxFile = cszFile;
ofn.lpstrFileTitle = szFileTitle;
ofn.nMaxFileTitle = sizeof(szFileTitle);
ofn.lpstrTitle = Title;
ofn.lpstrDefExt = lpszext;
if (!GetOpenFileNameA(&ofn))
return false;
return true;
}
// ----------------------------------------------------------------------------
void WinCoder::_focusEditor()
{
SetFocus(_hwndRaster);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: layerimp.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: dvo $ $Date: 2001-06-29 21:07:13 $
*
* 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 <tools/debug.hxx>
#ifndef _COM_SUN_STAR_DRAWING_XLAYERMANAGER_HPP_
#include <com/sun/star/drawing/XLayerManager.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XLAYERSUPPLIER_HPP_
#include <com/sun/star/drawing/XLayerSupplier.hpp>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_LAYERIMP_HXX
#include "layerimp.hxx"
#endif
using namespace ::rtl;
using namespace ::std;
using namespace ::cppu;
using namespace ::com::sun::star;
using namespace ::com::sun::star::xml;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_NAME;
TYPEINIT1( SdXMLLayerSetContext, SvXMLImportContext );
SdXMLLayerSetContext::SdXMLLayerSetContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList)
: SvXMLImportContext(rImport, nPrfx, rLocalName)
{
Reference< XLayerSupplier > xLayerSupplier( rImport.GetModel(), UNO_QUERY );
DBG_ASSERT( xLayerSupplier.is(), "XModel is not supporting XLayerSupplier!" );
if( xLayerSupplier.is() )
mxLayerManager = xLayerSupplier->getLayerManager();
}
SdXMLLayerSetContext::~SdXMLLayerSetContext()
{
}
SvXMLImportContext * SdXMLLayerSetContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
if( mxLayerManager.is() )
{
const OUString strName( RTL_CONSTASCII_USTRINGPARAM( "Name" ) );
OUString aName;
const sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for(sal_Int16 i=0; i < nAttrCount; i++)
{
OUString aLocalName;
if( GetImport().GetNamespaceMap().GetKeyByAttrName( xAttrList->getNameByIndex( i ), &aLocalName ) == XML_NAMESPACE_DRAW )
{
const OUString sValue( xAttrList->getValueByIndex( i ) );
if( IsXMLToken( aLocalName, XML_NAME ) )
{
aName = sValue;
}
}
}
DBG_ASSERT( aName.getLength(), "draw:layer element without draw:name!" );
if( aName.getLength() )
{
Reference< XPropertySet > xLayer;
if( mxLayerManager->hasByName( aName ) )
{
mxLayerManager->getByName( aName ) >>= xLayer;
DBG_ASSERT( xLayer.is(), "failed to get existing XLayer!" );
}
else
{
Reference< XLayerManager > xLayerManager( mxLayerManager, UNO_QUERY );
if( xLayerManager.is() )
xLayer = Reference< XPropertySet >::query( xLayerManager->insertNewByIndex( xLayerManager->getCount() ) );
DBG_ASSERT( xLayer.is(), "failed to create new XLayer!" );
if( xLayer.is() )
{
Any aAny;
aAny <<= aName;
xLayer->setPropertyValue( strName, aAny );
}
}
}
}
return new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.636); FILE MERGED 2005/09/05 14:38:43 rt 1.5.636.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: layerimp.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-09 13:45:32 $
*
* 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 <tools/debug.hxx>
#ifndef _COM_SUN_STAR_DRAWING_XLAYERMANAGER_HPP_
#include <com/sun/star/drawing/XLayerManager.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XLAYERSUPPLIER_HPP_
#include <com/sun/star/drawing/XLayerSupplier.hpp>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_LAYERIMP_HXX
#include "layerimp.hxx"
#endif
using namespace ::rtl;
using namespace ::std;
using namespace ::cppu;
using namespace ::com::sun::star;
using namespace ::com::sun::star::xml;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_NAME;
TYPEINIT1( SdXMLLayerSetContext, SvXMLImportContext );
SdXMLLayerSetContext::SdXMLLayerSetContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList)
: SvXMLImportContext(rImport, nPrfx, rLocalName)
{
Reference< XLayerSupplier > xLayerSupplier( rImport.GetModel(), UNO_QUERY );
DBG_ASSERT( xLayerSupplier.is(), "XModel is not supporting XLayerSupplier!" );
if( xLayerSupplier.is() )
mxLayerManager = xLayerSupplier->getLayerManager();
}
SdXMLLayerSetContext::~SdXMLLayerSetContext()
{
}
SvXMLImportContext * SdXMLLayerSetContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
if( mxLayerManager.is() )
{
const OUString strName( RTL_CONSTASCII_USTRINGPARAM( "Name" ) );
OUString aName;
const sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for(sal_Int16 i=0; i < nAttrCount; i++)
{
OUString aLocalName;
if( GetImport().GetNamespaceMap().GetKeyByAttrName( xAttrList->getNameByIndex( i ), &aLocalName ) == XML_NAMESPACE_DRAW )
{
const OUString sValue( xAttrList->getValueByIndex( i ) );
if( IsXMLToken( aLocalName, XML_NAME ) )
{
aName = sValue;
}
}
}
DBG_ASSERT( aName.getLength(), "draw:layer element without draw:name!" );
if( aName.getLength() )
{
Reference< XPropertySet > xLayer;
if( mxLayerManager->hasByName( aName ) )
{
mxLayerManager->getByName( aName ) >>= xLayer;
DBG_ASSERT( xLayer.is(), "failed to get existing XLayer!" );
}
else
{
Reference< XLayerManager > xLayerManager( mxLayerManager, UNO_QUERY );
if( xLayerManager.is() )
xLayer = Reference< XPropertySet >::query( xLayerManager->insertNewByIndex( xLayerManager->getCount() ) );
DBG_ASSERT( xLayer.is(), "failed to create new XLayer!" );
if( xLayer.is() )
{
Any aAny;
aAny <<= aName;
xLayer->setPropertyValue( strName, aAny );
}
}
}
}
return new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: layerimp.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2007-06-29 13:48:32 $
*
* 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_xmloff.hxx"
#include <tools/debug.hxx>
#ifndef _COM_SUN_STAR_DRAWING_XLAYERMANAGER_HPP_
#include <com/sun/star/drawing/XLayerManager.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XLAYERSUPPLIER_HPP_
#include <com/sun/star/drawing/XLayerSupplier.hpp>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_LAYERIMP_HXX
#include "layerimp.hxx"
#endif
#include <xmloff/xmltoken.hxx>
#include "XMLStringBufferImportContext.hxx"
using namespace ::rtl;
using namespace ::std;
using namespace ::cppu;
using namespace ::xmloff::token;
using namespace ::com::sun::star;
using namespace ::com::sun::star::xml;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using ::xmloff::token::IsXMLToken;
class SdXMLLayerContext : public SvXMLImportContext
{
public:
SdXMLLayerContext( SvXMLImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList, const Reference< XNameAccess >& xLayerManager );
virtual ~SdXMLLayerContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const Reference< XAttributeList >& xAttrList );
virtual void EndElement();
private:
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > mxLayerManager;
::rtl::OUString msName;
::rtl::OUStringBuffer sDescriptionBuffer;
::rtl::OUStringBuffer sTitleBuffer;
};
SdXMLLayerContext::SdXMLLayerContext( SvXMLImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList, const Reference< XNameAccess >& xLayerManager )
: SvXMLImportContext(rImport, nPrefix, rLocalName)
, mxLayerManager( xLayerManager )
{
const OUString strName( RTL_CONSTASCII_USTRINGPARAM( "Name" ) );
OUString aName;
const sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for(sal_Int16 i=0; i < nAttrCount; i++)
{
OUString aLocalName;
if( GetImport().GetNamespaceMap().GetKeyByAttrName( xAttrList->getNameByIndex( i ), &aLocalName ) == XML_NAMESPACE_DRAW )
{
const OUString sValue( xAttrList->getValueByIndex( i ) );
if( IsXMLToken( aLocalName, XML_NAME ) )
{
msName = sValue;
break; // no more attributes needed
}
}
}
}
SdXMLLayerContext::~SdXMLLayerContext()
{
}
SvXMLImportContext * SdXMLLayerContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const Reference< XAttributeList >& )
{
if( (XML_NAMESPACE_SVG == nPrefix) && IsXMLToken(rLocalName, XML_TITLE) )
{
return new XMLStringBufferImportContext( GetImport(), nPrefix, rLocalName, sTitleBuffer);
}
else if( (XML_NAMESPACE_SVG == nPrefix) && IsXMLToken(rLocalName, XML_DESC) )
{
return new XMLStringBufferImportContext( GetImport(), nPrefix, rLocalName, sDescriptionBuffer);
}
else
{
return new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
}
}
void SdXMLLayerContext::EndElement()
{
DBG_ASSERT( msName.getLength(), "xmloff::SdXMLLayerContext::EndElement(), draw:layer element without draw:name!" );
if( msName.getLength() ) try
{
Reference< XPropertySet > xLayer;
if( mxLayerManager->hasByName( msName ) )
{
mxLayerManager->getByName( msName ) >>= xLayer;
DBG_ASSERT( xLayer.is(), "xmloff::SdXMLLayerContext::EndElement(), failed to get existing XLayer!" );
}
else
{
Reference< XLayerManager > xLayerManager( mxLayerManager, UNO_QUERY );
if( xLayerManager.is() )
xLayer = Reference< XPropertySet >::query( xLayerManager->insertNewByIndex( xLayerManager->getCount() ) );
DBG_ASSERT( xLayer.is(), "xmloff::SdXMLLayerContext::EndElement(), failed to create new XLayer!" );
if( xLayer.is() )
xLayer->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Name" ) ), Any( msName ) );
}
if( xLayer.is() )
{
xLayer->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM("Title") ), Any( sTitleBuffer.makeStringAndClear() ) );
xLayer->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM("Description") ), Any( sDescriptionBuffer.makeStringAndClear() ) );
}
}
catch( Exception& )
{
DBG_ERROR("SdXMLLayerContext::EndElement(), exception caught!");
}
}
TYPEINIT1( SdXMLLayerSetContext, SvXMLImportContext );
SdXMLLayerSetContext::SdXMLLayerSetContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>&)
: SvXMLImportContext(rImport, nPrfx, rLocalName)
{
Reference< XLayerSupplier > xLayerSupplier( rImport.GetModel(), UNO_QUERY );
DBG_ASSERT( xLayerSupplier.is(), "xmloff::SdXMLLayerSetContext::SdXMLLayerSetContext(), XModel is not supporting XLayerSupplier!" );
if( xLayerSupplier.is() )
mxLayerManager = xLayerSupplier->getLayerManager();
}
SdXMLLayerSetContext::~SdXMLLayerSetContext()
{
}
SvXMLImportContext * SdXMLLayerSetContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
return new SdXMLLayerContext( GetImport(), nPrefix, rLocalName, xAttrList, mxLayerManager );
}
<commit_msg>INTEGRATION: CWS impresstables2 (1.8.80); FILE MERGED 2007/08/01 14:10:55 cl 1.8.80.2: RESYNC: (1.8-1.11); FILE MERGED 2007/07/27 09:09:51 cl 1.8.80.1: fixed build issues due to pch and namespace ::rtl<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: layerimp.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2008-03-12 10:33:21 $
*
* 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_xmloff.hxx"
#include <tools/debug.hxx>
#ifndef _COM_SUN_STAR_DRAWING_XLAYERMANAGER_HPP_
#include <com/sun/star/drawing/XLayerManager.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XLAYERSUPPLIER_HPP_
#include <com/sun/star/drawing/XLayerSupplier.hpp>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_LAYERIMP_HXX
#include "layerimp.hxx"
#endif
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
#include "XMLStringBufferImportContext.hxx"
using namespace ::std;
using namespace ::cppu;
using namespace ::xmloff::token;
using namespace ::com::sun::star;
using namespace ::com::sun::star::xml;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using ::xmloff::token::IsXMLToken;
class SdXMLLayerContext : public SvXMLImportContext
{
public:
SdXMLLayerContext( SvXMLImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList, const Reference< XNameAccess >& xLayerManager );
virtual ~SdXMLLayerContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const Reference< XAttributeList >& xAttrList );
virtual void EndElement();
private:
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > mxLayerManager;
::rtl::OUString msName;
::rtl::OUStringBuffer sDescriptionBuffer;
::rtl::OUStringBuffer sTitleBuffer;
};
SdXMLLayerContext::SdXMLLayerContext( SvXMLImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList, const Reference< XNameAccess >& xLayerManager )
: SvXMLImportContext(rImport, nPrefix, rLocalName)
, mxLayerManager( xLayerManager )
{
const OUString strName( RTL_CONSTASCII_USTRINGPARAM( "Name" ) );
OUString aName;
const sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for(sal_Int16 i=0; i < nAttrCount; i++)
{
OUString aLocalName;
if( GetImport().GetNamespaceMap().GetKeyByAttrName( xAttrList->getNameByIndex( i ), &aLocalName ) == XML_NAMESPACE_DRAW )
{
const OUString sValue( xAttrList->getValueByIndex( i ) );
if( IsXMLToken( aLocalName, XML_NAME ) )
{
msName = sValue;
break; // no more attributes needed
}
}
}
}
SdXMLLayerContext::~SdXMLLayerContext()
{
}
SvXMLImportContext * SdXMLLayerContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const Reference< XAttributeList >& )
{
if( (XML_NAMESPACE_SVG == nPrefix) && IsXMLToken(rLocalName, XML_TITLE) )
{
return new XMLStringBufferImportContext( GetImport(), nPrefix, rLocalName, sTitleBuffer);
}
else if( (XML_NAMESPACE_SVG == nPrefix) && IsXMLToken(rLocalName, XML_DESC) )
{
return new XMLStringBufferImportContext( GetImport(), nPrefix, rLocalName, sDescriptionBuffer);
}
else
{
return new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
}
}
void SdXMLLayerContext::EndElement()
{
DBG_ASSERT( msName.getLength(), "xmloff::SdXMLLayerContext::EndElement(), draw:layer element without draw:name!" );
if( msName.getLength() ) try
{
Reference< XPropertySet > xLayer;
if( mxLayerManager->hasByName( msName ) )
{
mxLayerManager->getByName( msName ) >>= xLayer;
DBG_ASSERT( xLayer.is(), "xmloff::SdXMLLayerContext::EndElement(), failed to get existing XLayer!" );
}
else
{
Reference< XLayerManager > xLayerManager( mxLayerManager, UNO_QUERY );
if( xLayerManager.is() )
xLayer = Reference< XPropertySet >::query( xLayerManager->insertNewByIndex( xLayerManager->getCount() ) );
DBG_ASSERT( xLayer.is(), "xmloff::SdXMLLayerContext::EndElement(), failed to create new XLayer!" );
if( xLayer.is() )
xLayer->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "Name" ) ), Any( msName ) );
}
if( xLayer.is() )
{
xLayer->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM("Title") ), Any( sTitleBuffer.makeStringAndClear() ) );
xLayer->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM("Description") ), Any( sDescriptionBuffer.makeStringAndClear() ) );
}
}
catch( Exception& )
{
DBG_ERROR("SdXMLLayerContext::EndElement(), exception caught!");
}
}
TYPEINIT1( SdXMLLayerSetContext, SvXMLImportContext );
SdXMLLayerSetContext::SdXMLLayerSetContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>&)
: SvXMLImportContext(rImport, nPrfx, rLocalName)
{
Reference< XLayerSupplier > xLayerSupplier( rImport.GetModel(), UNO_QUERY );
DBG_ASSERT( xLayerSupplier.is(), "xmloff::SdXMLLayerSetContext::SdXMLLayerSetContext(), XModel is not supporting XLayerSupplier!" );
if( xLayerSupplier.is() )
mxLayerManager = xLayerSupplier->getLayerManager();
}
SdXMLLayerSetContext::~SdXMLLayerSetContext()
{
}
SvXMLImportContext * SdXMLLayerSetContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
return new SdXMLLayerContext( GetImport(), nPrefix, rLocalName, xAttrList, mxLayerManager );
}
<|endoftext|> |
<commit_before>#include "API.hpp"
#include "ros/ros.h"
#include <ros/console.h>
using namespace kitrokopter;
API::API(int argc, char **argv)
{
idCounter = 0;
cameras = vector<int[2]>(8);
quadcopters = vector<int>(10);
controllers = vector<int>(1);
positions = vector<int>(5);
ros::init(argc, argv, "api_server");
ros::NodeHandle n;
ros::ServiceServer service = n.advertiseService("announce", &API::announce, this);
ROS_INFO("Ready to deliver IDs.");
ros::spin();
}
bool API::announce(api_application::Announce::Request &req, api_application::Announce::Response &res)
{
res.id = idCounter++;
switch (req.type) {
case 0:
cameras.push_back({res.id, req.camera_id});
break;
case 1:
quadcopters.push_back(res.id);
break;
case 2:
controllers.push_back(res.id);
break;
case 3:
positions.push_back(res.id);
break;
default:
ROS_ERROR("Malformed register attempt!");
res.id = -1;
return false;
}
ROS_INFO("Registered new module with type %d and id %d", req.type, res.id);
return true;
}<commit_msg>Forgot std<commit_after>#include "API.hpp"
#include "ros/ros.h"
#include <ros/console.h>
using namespace kitrokopter;
API::API(int argc, char **argv)
{
idCounter = 0;
cameras = std::vector<int[2]>(8);
quadcopters = std::vector<int>(10);
controllers = std::vector<int>(1);
positions = std::vector<int>(5);
ros::init(argc, argv, "api_server");
ros::NodeHandle n;
ros::ServiceServer service = n.advertiseService("announce", &API::announce, this);
ROS_INFO("Ready to deliver IDs.");
ros::spin();
}
bool API::announce(api_application::Announce::Request &req, api_application::Announce::Response &res)
{
res.id = idCounter++;
switch (req.type) {
case 0:
cameras.push_back({res.id, req.camera_id});
break;
case 1:
quadcopters.push_back(res.id);
break;
case 2:
controllers.push_back(res.id);
break;
case 3:
positions.push_back(res.id);
break;
default:
ROS_ERROR("Malformed register attempt!");
res.id = -1;
return false;
}
ROS_INFO("Registered new module with type %d and id %d", req.type, res.id);
return true;
}<|endoftext|> |
<commit_before>#include "App.hpp"
#include <Camera.hpp>
#include <DevUI.hpp>
#include <Log.hpp>
#include <Shader.hpp>
#include <iostream>
#include <imgui/imgui.h>
#include <imgui/imgui_impl_glfw_gl3.h>
#define TINYGLTF_IMPLEMENTATION
#define TINYGLTF_NO_STB_IMAGE_WRITE
#include <tinygltf/tiny_gltf.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb/stb_image.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb/stb_image_write.h>
App* App::_sInst = nullptr;
const float TARGET_FPS = 60.0f;
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void mouse_button_callback(GLFWwindow* window, int button, int action, int mode);
void mouse_pos_callback(GLFWwindow* window, double x, double y);
App::~App() {
DeleteShaders();
ImGui_ImplGlfwGL3_Shutdown();
delete _mWindow;
_mWindow = nullptr;
}
void App::Run()
{
const float targetElapsed = 1.0f / TARGET_FPS;
Start();
float prevTime = 0.0f;
float frameTime = 0.0f;
while (!GetWindow()->ShouldClose()) {
float currTime = (float)glfwGetTime();
float elapsed = currTime - prevTime;
frameTime += elapsed;
float dt = elapsed / targetElapsed;
HandleInput(dt);
Update(dt);
if (frameTime >= targetElapsed)
{
frameTime = 0.0f;
Render();
}
prevTime = currTime;
}
}
void App::Start()
{
// Welcome
printf("Temporality Engine v%s\n\n", VERSION);
// Window
_mWindow = new Window(1024, 768);
// Display OpenGL info
OpenGLInfo();
// Load Engine Shaders
printf("\nLoading Engine Shaders\n");
AddShader("axis", new Shader({
"shaders/axis.vert",
"shaders/axis.frag" }));
AddShader("defaultLighting", new Shader({
"shaders/defaultLighting.vert",
"shaders/defaultLighting.frag" }));
// Clear Window
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
// Depth
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
// Blend
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Setup Scene
_mCurrentScene->Start();
GLFWwindow * glfwWin = GetWindow()->GetGLFWWindow();
// Input
glfwSetKeyCallback(glfwWin, &key_callback);
glfwSetMouseButtonCallback(glfwWin, &mouse_button_callback);
glfwSetScrollCallback(glfwWin, &scroll_callback);
glfwSetCursorPosCallback(glfwWin, &mouse_pos_callback);
glfwSetInputMode(glfwWin, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
// Movement
_mInputMap[GLFW_KEY_W] = false;
_mInputMap[GLFW_KEY_A] = false;
_mInputMap[GLFW_KEY_S] = false;
_mInputMap[GLFW_KEY_D] = false;
_mInputMap[GLFW_KEY_Q] = false;
_mInputMap[GLFW_KEY_E] = false;
_mInputMap[GLFW_MOUSE_BUTTON_RIGHT] = false;
// Other Input keys
_mInputMap[GLFW_KEY_H] = false;
// Register the options function into the UI
DevUI::RegisterOptionsFunc(&Scene::Options);
}
void App::Update(float dt)
{
glfwPollEvents();
_mCurrentScene->Update(dt);
}
void App::Render()
{
_mWindow->Clear();
_mCurrentScene->Render();
DevUI::Render();
_mWindow->Present();
}
void App::OpenGLInfo()
{
// OpenGL Basic Info
LogInfo("OpenGL Vendor: %s\n", glGetString(GL_VENDOR));
LogInfo("OpenGL Renderer: %s\n", glGetString(GL_RENDERER));
LogInfo("OpenGL Version: %s\n", glGetString(GL_VERSION));
LogInfo("GLSL Version: %s\n\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
// Anti-Aliasing
int samples;
glGetIntegerv(GL_SAMPLES, &samples);
LogInfo("Anti-Aliasing: %dx\n", samples);
// Binary Shader Formats
GLint formats = 0;
glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &formats);
LogInfo("Binary Shader Formats: %d\n", formats);
// Max UBO Size
int tmp;
glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &tmp);
LogInfo("Max UBO Size: %d\n", tmp);
// Max Vertex UBOs
glGetIntegerv(GL_MAX_VERTEX_UNIFORM_BLOCKS, &tmp);
LogInfo("Max Vertex UBOs: %d\n", tmp);
// Max Fragment UBOs
glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, &tmp);
LogInfo("Max Fragment UBOs: %d\n", tmp);
// Max Geometry UBOs
glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_BLOCKS, &tmp);
LogInfo("Max Geometry UBOs: %d\n", tmp);
// Max UBO Bindings
int maxBindings;
glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, &maxBindings);
LogInfo("Max UBO Bindings: %d\n", maxBindings);
}
void App::Screenshot()
{
std::vector<unsigned int> pixels(3 * GetWindow()->GetWidth() * GetWindow()->GetHeight());
glReadPixels(0, 0, GetWindow()->GetWidth(), GetWindow()->GetHeight(), GL_RGB, GL_UNSIGNED_BYTE, pixels.data());
stbi_flip_vertically_on_write(true);
stbi_write_png("Screenshot.png", GetWindow()->GetWidth(), GetWindow()->GetHeight(), 3, pixels.data(), 3 * GetWindow()->GetWidth());
}
void App::AddShader(std::string name, Shader* shader)
{
_mShaders[name] = shader;
}
Shader* App::GetShader(std::string name)
{
if (_mShaders.find(name) == _mShaders.end())
{
return nullptr;
}
return _mShaders[name];
}
void App::DeleteShaders()
{
// Destroy the shaders
for (auto& shader : _mShaders)
shader.second->Destroy();
// Clear shader vector
_mShaders.clear();
}
void App::ReloadShaders()
{
for (auto s : _mShaders)
s.second->Reload();
}
void App::HandleInput(float dt)
{
if (_mInputMap[GLFW_KEY_W])
_mCurrentCamera->HandleMovement(Direction::FORWARD, dt);
if (_mInputMap[GLFW_KEY_S])
_mCurrentCamera->HandleMovement(Direction::BACKWARD, dt);
if (_mInputMap[GLFW_KEY_A])
_mCurrentCamera->HandleMovement(Direction::LEFT, dt);
if (_mInputMap[GLFW_KEY_D])
_mCurrentCamera->HandleMovement(Direction::RIGHT, dt);
if (_mInputMap[GLFW_KEY_Q])
_mCurrentCamera->HandleMovement(Direction::UP, dt);
if (_mInputMap[GLFW_KEY_E])
_mCurrentCamera->HandleMovement(Direction::DOWN, dt);
}
void App::HandleGLFWKey(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (action == GLFW_RELEASE) {
if (_mInputMap.find(key) != _mInputMap.end()) {
_mInputMap[key] = false;
}
}
if (action == GLFW_PRESS)
{
if (_mInputMap.find(key) != _mInputMap.end()) {
_mInputMap[key] = true;
}
switch (key) {
case GLFW_KEY_F5: // Reloads shaders
{
std::cout << "\nReloading shaders!\n";
ReloadShaders();
break;
}
case GLFW_KEY_PRINT_SCREEN:
{
Screenshot();
break;
}
}
}
DevUI::HandleKeyEvent(key, scancode, action, mode);
ImGui_ImplGlfw_KeyCallback(window, key, scancode, action, mode);
}
void App::HandleGLFWMouseButton(GLFWwindow* window, int button, int action, int mode)
{
if (action == GLFW_RELEASE) {
if (_mInputMap.find(button) != _mInputMap.end()) {
_mInputMap[button] = false;
}
}
if (action == GLFW_PRESS)
{
if (_mInputMap.find(button) != _mInputMap.end()) {
_mInputMap[button] = true;
}
}
// Handle mouse button
ImGui_ImplGlfw_MouseButtonCallback(window, button, action, mode);
}
void App::HandleGLFWScroll(GLFWwindow* window, double xoffset, double yoffset)
{
//Camera::Inst().HandleFoV((float)xoffset, (float)yoffset);
// scroll
ImGui_ImplGlfw_ScrollCallback(window, xoffset, yoffset);
}
void App::HandleGLFWMousePos(GLFWwindow* window, double x, double y)
{
if (_mLastMX < 0 && _mLastMY < 0) {
_mLastMX = (float)x;
_mLastMY = (float)y;
}
float xoffset = (float)x - _mLastMX;
float yoffset = _mLastMY - (float)y;
_mLastMX = (float)x;
_mLastMY = (float)y;
// handle mouse pos
if (_mInputMap[GLFW_MOUSE_BUTTON_RIGHT]) {
_mCurrentCamera->HandleRotation(xoffset, yoffset);
}
}
// Not part of the class itself but used for key callback.
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
App::Inst()->HandleGLFWKey(window, key, scancode, action, mode);
}
void mouse_button_callback(GLFWwindow* window, int button, int action, int mode)
{
App::Inst()->HandleGLFWMouseButton(window, button, action, mode);
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
App::Inst()->HandleGLFWScroll(window, xoffset, yoffset);
}
void mouse_pos_callback(GLFWwindow* window, double x, double y)
{
App::Inst()->HandleGLFWMousePos(window, x, y);
}
<commit_msg>HOTFIX: Logging for screenshot (#17)<commit_after>#include "App.hpp"
#include <Camera.hpp>
#include <DevUI.hpp>
#include <Log.hpp>
#include <Shader.hpp>
#include <iostream>
#include <imgui/imgui.h>
#include <imgui/imgui_impl_glfw_gl3.h>
#define TINYGLTF_IMPLEMENTATION
#define TINYGLTF_NO_STB_IMAGE_WRITE
#include <tinygltf/tiny_gltf.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb/stb_image.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb/stb_image_write.h>
App* App::_sInst = nullptr;
const float TARGET_FPS = 60.0f;
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void mouse_button_callback(GLFWwindow* window, int button, int action, int mode);
void mouse_pos_callback(GLFWwindow* window, double x, double y);
App::~App() {
DeleteShaders();
ImGui_ImplGlfwGL3_Shutdown();
delete _mWindow;
_mWindow = nullptr;
}
void App::Run()
{
const float targetElapsed = 1.0f / TARGET_FPS;
Start();
float prevTime = 0.0f;
float frameTime = 0.0f;
while (!GetWindow()->ShouldClose()) {
float currTime = (float)glfwGetTime();
float elapsed = currTime - prevTime;
frameTime += elapsed;
float dt = elapsed / targetElapsed;
HandleInput(dt);
Update(dt);
if (frameTime >= targetElapsed)
{
frameTime = 0.0f;
Render();
}
prevTime = currTime;
}
}
void App::Start()
{
// Welcome
printf("Temporality Engine v%s\n\n", VERSION);
// Window
_mWindow = new Window(1024, 768);
// Display OpenGL info
OpenGLInfo();
// Load Engine Shaders
printf("\nLoading Engine Shaders\n");
AddShader("axis", new Shader({
"shaders/axis.vert",
"shaders/axis.frag" }));
AddShader("defaultLighting", new Shader({
"shaders/defaultLighting.vert",
"shaders/defaultLighting.frag" }));
// Clear Window
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
// Depth
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
// Blend
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Setup Scene
_mCurrentScene->Start();
GLFWwindow * glfwWin = GetWindow()->GetGLFWWindow();
// Input
glfwSetKeyCallback(glfwWin, &key_callback);
glfwSetMouseButtonCallback(glfwWin, &mouse_button_callback);
glfwSetScrollCallback(glfwWin, &scroll_callback);
glfwSetCursorPosCallback(glfwWin, &mouse_pos_callback);
glfwSetInputMode(glfwWin, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
// Movement
_mInputMap[GLFW_KEY_W] = false;
_mInputMap[GLFW_KEY_A] = false;
_mInputMap[GLFW_KEY_S] = false;
_mInputMap[GLFW_KEY_D] = false;
_mInputMap[GLFW_KEY_Q] = false;
_mInputMap[GLFW_KEY_E] = false;
_mInputMap[GLFW_MOUSE_BUTTON_RIGHT] = false;
// Other Input keys
_mInputMap[GLFW_KEY_H] = false;
// Register the options function into the UI
DevUI::RegisterOptionsFunc(&Scene::Options);
}
void App::Update(float dt)
{
glfwPollEvents();
_mCurrentScene->Update(dt);
}
void App::Render()
{
_mWindow->Clear();
_mCurrentScene->Render();
DevUI::Render();
_mWindow->Present();
}
void App::OpenGLInfo()
{
// OpenGL Basic Info
LogInfo("OpenGL Vendor: %s\n", glGetString(GL_VENDOR));
LogInfo("OpenGL Renderer: %s\n", glGetString(GL_RENDERER));
LogInfo("OpenGL Version: %s\n", glGetString(GL_VERSION));
LogInfo("GLSL Version: %s\n\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
// Anti-Aliasing
int samples;
glGetIntegerv(GL_SAMPLES, &samples);
LogInfo("Anti-Aliasing: %dx\n", samples);
// Binary Shader Formats
GLint formats = 0;
glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &formats);
LogInfo("Binary Shader Formats: %d\n", formats);
// Max UBO Size
int tmp;
glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &tmp);
LogInfo("Max UBO Size: %d\n", tmp);
// Max Vertex UBOs
glGetIntegerv(GL_MAX_VERTEX_UNIFORM_BLOCKS, &tmp);
LogInfo("Max Vertex UBOs: %d\n", tmp);
// Max Fragment UBOs
glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, &tmp);
LogInfo("Max Fragment UBOs: %d\n", tmp);
// Max Geometry UBOs
glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_BLOCKS, &tmp);
LogInfo("Max Geometry UBOs: %d\n", tmp);
// Max UBO Bindings
int maxBindings;
glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, &maxBindings);
LogInfo("Max UBO Bindings: %d\n", maxBindings);
}
void App::Screenshot()
{
std::vector<unsigned int> pixels(3 * GetWindow()->GetWidth() * GetWindow()->GetHeight());
glReadPixels(0, 0, GetWindow()->GetWidth(), GetWindow()->GetHeight(), GL_RGB, GL_UNSIGNED_BYTE, pixels.data());
stbi_flip_vertically_on_write(true);
time_t now = time(0);
tm* localtm = localtime(&now);
std::string name = "Screenshot " + std::to_string(localtm->tm_mon+1) + std::to_string(localtm->tm_mday) + std::to_string(localtm->tm_year+1900) + "_"
+ std::to_string(localtm->tm_hour) + std::to_string(localtm->tm_min) + std::to_string(localtm->tm_sec) + ".png";
LogVerbose("Date: %s, %s, %s, Time: %s:%s:%s\n", std::to_string(localtm->tm_mon+1), std::to_string(localtm->tm_mday), std::to_string(localtm->tm_year+1900)
, std::to_string(localtm->tm_hour), std::to_string(localtm->tm_min), std::to_string(localtm->tm_sec));
int screenshot = stbi_write_png(name.c_str(), GetWindow()->GetWidth(), GetWindow()->GetHeight(), 3, pixels.data(), 3 * GetWindow()->GetWidth());
if (screenshot)
LogInfo("Screenshot successful!\n");
else
LogInfo("Screenshot unsuccessful.\n");
}
void App::AddShader(std::string name, Shader* shader)
{
_mShaders[name] = shader;
}
Shader* App::GetShader(std::string name)
{
if (_mShaders.find(name) == _mShaders.end())
{
return nullptr;
}
return _mShaders[name];
}
void App::DeleteShaders()
{
// Destroy the shaders
for (auto& shader : _mShaders)
shader.second->Destroy();
// Clear shader vector
_mShaders.clear();
}
void App::ReloadShaders()
{
for (auto s : _mShaders)
s.second->Reload();
}
void App::HandleInput(float dt)
{
if (_mInputMap[GLFW_KEY_W])
_mCurrentCamera->HandleMovement(Direction::FORWARD, dt);
if (_mInputMap[GLFW_KEY_S])
_mCurrentCamera->HandleMovement(Direction::BACKWARD, dt);
if (_mInputMap[GLFW_KEY_A])
_mCurrentCamera->HandleMovement(Direction::LEFT, dt);
if (_mInputMap[GLFW_KEY_D])
_mCurrentCamera->HandleMovement(Direction::RIGHT, dt);
if (_mInputMap[GLFW_KEY_Q])
_mCurrentCamera->HandleMovement(Direction::UP, dt);
if (_mInputMap[GLFW_KEY_E])
_mCurrentCamera->HandleMovement(Direction::DOWN, dt);
}
void App::HandleGLFWKey(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (action == GLFW_RELEASE) {
if (_mInputMap.find(key) != _mInputMap.end()) {
_mInputMap[key] = false;
}
}
if (action == GLFW_PRESS)
{
if (_mInputMap.find(key) != _mInputMap.end()) {
_mInputMap[key] = true;
}
switch (key) {
case GLFW_KEY_F5: // Reloads shaders
{
std::cout << "\nReloading shaders!\n";
ReloadShaders();
break;
}
case GLFW_KEY_PRINT_SCREEN:
{
Screenshot();
break;
}
}
}
DevUI::HandleKeyEvent(key, scancode, action, mode);
ImGui_ImplGlfw_KeyCallback(window, key, scancode, action, mode);
}
void App::HandleGLFWMouseButton(GLFWwindow* window, int button, int action, int mode)
{
if (action == GLFW_RELEASE) {
if (_mInputMap.find(button) != _mInputMap.end()) {
_mInputMap[button] = false;
}
}
if (action == GLFW_PRESS)
{
if (_mInputMap.find(button) != _mInputMap.end()) {
_mInputMap[button] = true;
}
}
// Handle mouse button
ImGui_ImplGlfw_MouseButtonCallback(window, button, action, mode);
}
void App::HandleGLFWScroll(GLFWwindow* window, double xoffset, double yoffset)
{
//Camera::Inst().HandleFoV((float)xoffset, (float)yoffset);
// scroll
ImGui_ImplGlfw_ScrollCallback(window, xoffset, yoffset);
}
void App::HandleGLFWMousePos(GLFWwindow* window, double x, double y)
{
if (_mLastMX < 0 && _mLastMY < 0) {
_mLastMX = (float)x;
_mLastMY = (float)y;
}
float xoffset = (float)x - _mLastMX;
float yoffset = _mLastMY - (float)y;
_mLastMX = (float)x;
_mLastMY = (float)y;
// handle mouse pos
if (_mInputMap[GLFW_MOUSE_BUTTON_RIGHT]) {
_mCurrentCamera->HandleRotation(xoffset, yoffset);
}
}
// Not part of the class itself but used for key callback.
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
App::Inst()->HandleGLFWKey(window, key, scancode, action, mode);
}
void mouse_button_callback(GLFWwindow* window, int button, int action, int mode)
{
App::Inst()->HandleGLFWMouseButton(window, button, action, mode);
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
App::Inst()->HandleGLFWScroll(window, xoffset, yoffset);
}
void mouse_pos_callback(GLFWwindow* window, double x, double y)
{
App::Inst()->HandleGLFWMousePos(window, x, y);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: LabelPositionHelper.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 01:43: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
*
************************************************************************/
#ifndef _CHART2_VIEW_LABELPOSITIONHELPER_HXX
#define _CHART2_VIEW_LABELPOSITIONHELPER_HXX
#include "LabelAlignment.hxx"
#include "PropertyMapper.hxx"
#ifndef _COM_SUN_STAR_AWT_POINT_HPP_
#include <com/sun/star/awt/Point.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_
#include <com/sun/star/drawing/Position3D.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
//-----------------------------------------------------------------------------
/**
*/
class PlottingPositionHelper;
class ShapeFactory;
class LabelPositionHelper
{
public:
LabelPositionHelper(
PlottingPositionHelper* pPosHelper
, sal_Int32 nDimensionCount
, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xLogicTarget
, ShapeFactory* pShapeFactory );
virtual ~LabelPositionHelper();
::com::sun::star::awt::Point transformSceneToScreenPosition(
const ::com::sun::star::drawing::Position3D& rScenePosition3D ) const;
::com::sun::star::awt::Point transformLogicToScreenPosition(
const ::com::sun::star::drawing::Position3D& rScenePosition3D ) const;
static void changeTextAdjustment( tAnySequence& rPropValues, const tNameSequence& rPropNames, LabelAlignment eAlignment);
static void doDynamicFontResize( tAnySequence& rPropValues, const tNameSequence& rPropNames
, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xAxisModelProps
, const ::com::sun::star::awt::Size& rNewReferenceSize );
private:
LabelPositionHelper();
protected:
PlottingPositionHelper* m_pPosHelper;
sal_Int32 m_nDimensionCount;
private:
//these members are only necessary for transformation from 3D to 2D
::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShapes > m_xLogicTarget;
ShapeFactory* m_pShapeFactory;
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>INTEGRATION: CWS chart2mst3 (1.1.4); FILE MERGED 2005/10/07 12:20:26 bm 1.1.4.2: RESYNC: (1.1-1.2); FILE MERGED 2004/03/23 14:38:23 iha 1.1.4.1: renamed method getTransformation/Scaled/LogicToScene<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: LabelPositionHelper.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2007-05-22 19:18:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CHART2_VIEW_LABELPOSITIONHELPER_HXX
#define _CHART2_VIEW_LABELPOSITIONHELPER_HXX
#include "LabelAlignment.hxx"
#include "PropertyMapper.hxx"
#ifndef _COM_SUN_STAR_AWT_POINT_HPP_
#include <com/sun/star/awt/Point.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_
#include <com/sun/star/drawing/Position3D.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
//-----------------------------------------------------------------------------
/**
*/
class PlottingPositionHelper;
class ShapeFactory;
class LabelPositionHelper
{
public:
LabelPositionHelper(
PlottingPositionHelper* pPosHelper
, sal_Int32 nDimensionCount
, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xLogicTarget
, ShapeFactory* pShapeFactory );
virtual ~LabelPositionHelper();
::com::sun::star::awt::Point transformSceneToScreenPosition(
const ::com::sun::star::drawing::Position3D& rScenePosition3D ) const;
::com::sun::star::awt::Point transformScaledLogicToScreenPosition(
const ::com::sun::star::drawing::Position3D& rScenePosition3D ) const;
static void changeTextAdjustment( tAnySequence& rPropValues, const tNameSequence& rPropNames, LabelAlignment eAlignment);
static void doDynamicFontResize( tAnySequence& rPropValues, const tNameSequence& rPropNames
, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xAxisModelProps
, const ::com::sun::star::awt::Size& rNewReferenceSize );
private:
LabelPositionHelper();
protected:
PlottingPositionHelper* m_pPosHelper;
sal_Int32 m_nDimensionCount;
private:
//these members are only necessary for transformation from 3D to 2D
::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShapes > m_xLogicTarget;
ShapeFactory* m_pShapeFactory;
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013 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.
*/
// #define VERBOSE_DEBUG
#define LOG_TAG "Minikin"
#include <cutils/log.h>
#include "MinikinInternal.h"
#include <minikin/CmapCoverage.h>
#include <minikin/FontCollection.h>
using std::vector;
namespace android {
template <typename T>
static inline T max(T a, T b) {
return a>b ? a : b;
}
uint32_t FontCollection::sNextId = 0;
FontCollection::FontCollection(const vector<FontFamily*>& typefaces) :
mMaxChar(0) {
AutoMutex _l(gMinikinLock);
mId = sNextId++;
vector<uint32_t> lastChar;
size_t nTypefaces = typefaces.size();
#ifdef VERBOSE_DEBUG
ALOGD("nTypefaces = %d\n", nTypefaces);
#endif
const FontStyle defaultStyle;
for (size_t i = 0; i < nTypefaces; i++) {
FontFamily* family = typefaces[i];
MinikinFont* typeface = family->getClosestMatch(defaultStyle).font;
if (typeface == NULL) {
continue;
}
family->RefLocked();
FontInstance dummy;
mInstances.push_back(dummy); // emplace_back would be better
FontInstance* instance = &mInstances.back();
instance->mFamily = family;
instance->mCoverage = new SparseBitSet;
#ifdef VERBOSE_DEBUG
ALOGD("closest match = %p, family size = %d\n", typeface, family->getNumFonts());
#endif
const uint32_t cmapTag = MinikinFont::MakeTag('c', 'm', 'a', 'p');
size_t cmapSize = 0;
bool ok = typeface->GetTable(cmapTag, NULL, &cmapSize);
UniquePtr<uint8_t[]> cmapData(new uint8_t[cmapSize]);
ok = typeface->GetTable(cmapTag, cmapData.get(), &cmapSize);
CmapCoverage::getCoverage(*instance->mCoverage, cmapData.get(), cmapSize);
#ifdef VERBOSE_DEBUG
ALOGD("font coverage length=%d, first ch=%x\n", instance->mCoverage->length(),
instance->mCoverage->nextSetBit(0));
#endif
mMaxChar = max(mMaxChar, instance->mCoverage->length());
lastChar.push_back(instance->mCoverage->nextSetBit(0));
}
nTypefaces = mInstances.size();
LOG_ALWAYS_FATAL_IF(nTypefaces == 0,
"Font collection must have at least one valid typeface");
size_t nPages = (mMaxChar + kPageMask) >> kLogCharsPerPage;
size_t offset = 0;
for (size_t i = 0; i < nPages; i++) {
Range dummy;
mRanges.push_back(dummy);
Range* range = &mRanges.back();
#ifdef VERBOSE_DEBUG
ALOGD("i=%d: range start = %d\n", i, offset);
#endif
range->start = offset;
for (size_t j = 0; j < nTypefaces; j++) {
if (lastChar[j] < (i + 1) << kLogCharsPerPage) {
const FontInstance* instance = &mInstances[j];
mInstanceVec.push_back(instance);
offset++;
uint32_t nextChar = instance->mCoverage->nextSetBit((i + 1) << kLogCharsPerPage);
#ifdef VERBOSE_DEBUG
ALOGD("nextChar = %d (j = %d)\n", nextChar, j);
#endif
lastChar[j] = nextChar;
}
}
range->end = offset;
}
}
FontCollection::~FontCollection() {
for (size_t i = 0; i < mInstances.size(); i++) {
delete mInstances[i].mCoverage;
mInstances[i].mFamily->UnrefLocked();
}
}
// Implement heuristic for choosing best-match font. Here are the rules:
// 1. If first font in the collection has the character, it wins.
// 2. If a font matches both language and script, it gets a score of 4.
// 3. If a font matches just language, it gets a score of 2.
// 4. Matching the "compact" or "elegant" variant adds one to the score.
// 5. Highest score wins, with ties resolved to the first font.
const FontCollection::FontInstance* FontCollection::getInstanceForChar(uint32_t ch,
FontLanguage lang, int variant) const {
if (ch >= mMaxChar) {
return NULL;
}
const Range& range = mRanges[ch >> kLogCharsPerPage];
#ifdef VERBOSE_DEBUG
ALOGD("querying range %d:%d\n", range.start, range.end);
#endif
const FontInstance* bestInstance = NULL;
int bestScore = -1;
for (size_t i = range.start; i < range.end; i++) {
const FontInstance* instance = mInstanceVec[i];
if (instance->mCoverage->get(ch)) {
FontFamily* family = instance->mFamily;
// First font family in collection always matches
if (mInstances[0].mFamily == family) {
return instance;
}
int score = lang.match(family->lang()) * 2;
if (variant != 0 && variant == family->variant()) {
score++;
}
if (score > bestScore) {
bestScore = score;
bestInstance = instance;
}
}
}
if (bestInstance == NULL) {
bestInstance = &mInstances[0];
}
return bestInstance;
}
const uint32_t NBSP = 0xa0;
const uint32_t ZWJ = 0x200c;
const uint32_t ZWNJ = 0x200d;
const uint32_t KEYCAP = 0x20e3;
// Characters where we want to continue using existing font run instead of
// recomputing the best match in the fallback list.
static const uint32_t stickyWhitelist[] = { '!', ',', '.', ':', ';', '?', NBSP, ZWJ, ZWNJ, KEYCAP };
static bool isStickyWhitelisted(uint32_t c) {
for (size_t i = 0; i < sizeof(stickyWhitelist) / sizeof(stickyWhitelist[0]); i++) {
if (stickyWhitelist[i] == c) return true;
}
return false;
}
void FontCollection::itemize(const uint16_t *string, size_t string_size, FontStyle style,
vector<Run>* result) const {
FontLanguage lang = style.getLanguage();
int variant = style.getVariant();
const FontInstance* lastInstance = NULL;
Run* run = NULL;
int nShorts;
for (size_t i = 0; i < string_size; i += nShorts) {
nShorts = 1;
uint32_t ch = string[i];
// sigh, decode UTF-16 by hand here
if ((ch & 0xfc00) == 0xd800) {
if ((i + 1) < string_size) {
ch = 0x10000 + ((ch & 0x3ff) << 10) + (string[i + 1] & 0x3ff);
nShorts = 2;
}
}
// Continue using existing font as long as it has coverage and is whitelisted
if (lastInstance == NULL
|| !(isStickyWhitelisted(ch) && lastInstance->mCoverage->get(ch))) {
const FontInstance* instance = getInstanceForChar(ch, lang, variant);
if (i == 0 || instance != lastInstance) {
size_t start = i;
// Workaround for Emoji keycap until we implement per-cluster font
// selection: if keycap is found in a different font that also
// supports previous char, attach previous char to the new run.
// Only handles non-surrogate characters.
// Bug 7557244.
if (ch == KEYCAP && i && instance && instance->mCoverage->get(string[i - 1])) {
run->end--;
if (run->start == run->end) {
result->pop_back();
}
start--;
}
Run dummy;
result->push_back(dummy);
run = &result->back();
if (instance == NULL) {
run->fakedFont.font = NULL;
} else {
run->fakedFont = instance->mFamily->getClosestMatch(style);
}
lastInstance = instance;
run->start = start;
}
}
run->end = i + nShorts;
}
}
MinikinFont* FontCollection::baseFont(FontStyle style) {
return baseFontFaked(style).font;
}
FakedFont FontCollection::baseFontFaked(FontStyle style) {
if (mInstances.empty()) {
return FakedFont();
}
return mInstances[0].mFamily->getClosestMatch(style);
}
uint32_t FontCollection::getId() const {
return mId;
}
} // namespace android
<commit_msg>Try Unicode decomposition for selecting fallback font<commit_after>/*
* Copyright (C) 2013 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.
*/
// #define VERBOSE_DEBUG
#define LOG_TAG "Minikin"
#include <cutils/log.h>
#include "unicode/unistr.h"
#include "unicode/unorm2.h"
#include "MinikinInternal.h"
#include <minikin/CmapCoverage.h>
#include <minikin/FontCollection.h>
using std::vector;
namespace android {
template <typename T>
static inline T max(T a, T b) {
return a>b ? a : b;
}
uint32_t FontCollection::sNextId = 0;
FontCollection::FontCollection(const vector<FontFamily*>& typefaces) :
mMaxChar(0) {
AutoMutex _l(gMinikinLock);
mId = sNextId++;
vector<uint32_t> lastChar;
size_t nTypefaces = typefaces.size();
#ifdef VERBOSE_DEBUG
ALOGD("nTypefaces = %d\n", nTypefaces);
#endif
const FontStyle defaultStyle;
for (size_t i = 0; i < nTypefaces; i++) {
FontFamily* family = typefaces[i];
MinikinFont* typeface = family->getClosestMatch(defaultStyle).font;
if (typeface == NULL) {
continue;
}
family->RefLocked();
FontInstance dummy;
mInstances.push_back(dummy); // emplace_back would be better
FontInstance* instance = &mInstances.back();
instance->mFamily = family;
instance->mCoverage = new SparseBitSet;
#ifdef VERBOSE_DEBUG
ALOGD("closest match = %p, family size = %d\n", typeface, family->getNumFonts());
#endif
const uint32_t cmapTag = MinikinFont::MakeTag('c', 'm', 'a', 'p');
size_t cmapSize = 0;
bool ok = typeface->GetTable(cmapTag, NULL, &cmapSize);
UniquePtr<uint8_t[]> cmapData(new uint8_t[cmapSize]);
ok = typeface->GetTable(cmapTag, cmapData.get(), &cmapSize);
CmapCoverage::getCoverage(*instance->mCoverage, cmapData.get(), cmapSize);
#ifdef VERBOSE_DEBUG
ALOGD("font coverage length=%d, first ch=%x\n", instance->mCoverage->length(),
instance->mCoverage->nextSetBit(0));
#endif
mMaxChar = max(mMaxChar, instance->mCoverage->length());
lastChar.push_back(instance->mCoverage->nextSetBit(0));
}
nTypefaces = mInstances.size();
LOG_ALWAYS_FATAL_IF(nTypefaces == 0,
"Font collection must have at least one valid typeface");
size_t nPages = (mMaxChar + kPageMask) >> kLogCharsPerPage;
size_t offset = 0;
for (size_t i = 0; i < nPages; i++) {
Range dummy;
mRanges.push_back(dummy);
Range* range = &mRanges.back();
#ifdef VERBOSE_DEBUG
ALOGD("i=%d: range start = %d\n", i, offset);
#endif
range->start = offset;
for (size_t j = 0; j < nTypefaces; j++) {
if (lastChar[j] < (i + 1) << kLogCharsPerPage) {
const FontInstance* instance = &mInstances[j];
mInstanceVec.push_back(instance);
offset++;
uint32_t nextChar = instance->mCoverage->nextSetBit((i + 1) << kLogCharsPerPage);
#ifdef VERBOSE_DEBUG
ALOGD("nextChar = %d (j = %d)\n", nextChar, j);
#endif
lastChar[j] = nextChar;
}
}
range->end = offset;
}
}
FontCollection::~FontCollection() {
for (size_t i = 0; i < mInstances.size(); i++) {
delete mInstances[i].mCoverage;
mInstances[i].mFamily->UnrefLocked();
}
}
// Implement heuristic for choosing best-match font. Here are the rules:
// 1. If first font in the collection has the character, it wins.
// 2. If a font matches both language and script, it gets a score of 4.
// 3. If a font matches just language, it gets a score of 2.
// 4. Matching the "compact" or "elegant" variant adds one to the score.
// 5. Highest score wins, with ties resolved to the first font.
const FontCollection::FontInstance* FontCollection::getInstanceForChar(uint32_t ch,
FontLanguage lang, int variant) const {
if (ch >= mMaxChar) {
return NULL;
}
const Range& range = mRanges[ch >> kLogCharsPerPage];
#ifdef VERBOSE_DEBUG
ALOGD("querying range %d:%d\n", range.start, range.end);
#endif
const FontInstance* bestInstance = NULL;
int bestScore = -1;
for (size_t i = range.start; i < range.end; i++) {
const FontInstance* instance = mInstanceVec[i];
if (instance->mCoverage->get(ch)) {
FontFamily* family = instance->mFamily;
// First font family in collection always matches
if (mInstances[0].mFamily == family) {
return instance;
}
int score = lang.match(family->lang()) * 2;
if (variant != 0 && variant == family->variant()) {
score++;
}
if (score > bestScore) {
bestScore = score;
bestInstance = instance;
}
}
}
if (bestInstance == NULL && !mInstanceVec.empty()) {
UErrorCode errorCode = U_ZERO_ERROR;
const UNormalizer2* normalizer = unorm2_getNFDInstance(&errorCode);
if (U_SUCCESS(errorCode)) {
UChar decomposed[4];
int len = unorm2_getRawDecomposition(normalizer, ch, decomposed, 4, &errorCode);
if (U_SUCCESS(errorCode) && len > 0) {
int off = 0;
U16_NEXT_UNSAFE(decomposed, off, ch);
return getInstanceForChar(ch, lang, variant);
}
}
bestInstance = &mInstances[0];
}
return bestInstance;
}
const uint32_t NBSP = 0xa0;
const uint32_t ZWJ = 0x200c;
const uint32_t ZWNJ = 0x200d;
const uint32_t KEYCAP = 0x20e3;
// Characters where we want to continue using existing font run instead of
// recomputing the best match in the fallback list.
static const uint32_t stickyWhitelist[] = { '!', ',', '.', ':', ';', '?', NBSP, ZWJ, ZWNJ, KEYCAP };
static bool isStickyWhitelisted(uint32_t c) {
for (size_t i = 0; i < sizeof(stickyWhitelist) / sizeof(stickyWhitelist[0]); i++) {
if (stickyWhitelist[i] == c) return true;
}
return false;
}
void FontCollection::itemize(const uint16_t *string, size_t string_size, FontStyle style,
vector<Run>* result) const {
FontLanguage lang = style.getLanguage();
int variant = style.getVariant();
const FontInstance* lastInstance = NULL;
Run* run = NULL;
int nShorts;
for (size_t i = 0; i < string_size; i += nShorts) {
nShorts = 1;
uint32_t ch = string[i];
// sigh, decode UTF-16 by hand here
if ((ch & 0xfc00) == 0xd800) {
if ((i + 1) < string_size) {
ch = 0x10000 + ((ch & 0x3ff) << 10) + (string[i + 1] & 0x3ff);
nShorts = 2;
}
}
// Continue using existing font as long as it has coverage and is whitelisted
if (lastInstance == NULL
|| !(isStickyWhitelisted(ch) && lastInstance->mCoverage->get(ch))) {
const FontInstance* instance = getInstanceForChar(ch, lang, variant);
if (i == 0 || instance != lastInstance) {
size_t start = i;
// Workaround for Emoji keycap until we implement per-cluster font
// selection: if keycap is found in a different font that also
// supports previous char, attach previous char to the new run.
// Only handles non-surrogate characters.
// Bug 7557244.
if (ch == KEYCAP && i && instance && instance->mCoverage->get(string[i - 1])) {
run->end--;
if (run->start == run->end) {
result->pop_back();
}
start--;
}
Run dummy;
result->push_back(dummy);
run = &result->back();
if (instance == NULL) {
run->fakedFont.font = NULL;
} else {
run->fakedFont = instance->mFamily->getClosestMatch(style);
}
lastInstance = instance;
run->start = start;
}
}
run->end = i + nShorts;
}
}
MinikinFont* FontCollection::baseFont(FontStyle style) {
return baseFontFaked(style).font;
}
FakedFont FontCollection::baseFontFaked(FontStyle style) {
if (mInstances.empty()) {
return FakedFont();
}
return mInstances[0].mFamily->getClosestMatch(style);
}
uint32_t FontCollection::getId() const {
return mId;
}
} // namespace android
<|endoftext|> |
<commit_before>#include <map>
#include "CSE.h"
#include "IRMutator.h"
#include "IREquality.h"
#include "IROperator.h"
#include "Scope.h"
#include "Simplify.h"
namespace Halide {
namespace Internal {
using std::vector;
using std::string;
using std::map;
using std::pair;
namespace {
// Some expressions are not worth lifting out into lets, even if they
// occur redundantly many times. This list should mirror the list in
// the simplifier for lets, otherwise they'll just fight with each
// other pointlessly.
bool should_extract(Expr e) {
if (is_const(e)) {
return false;
}
if (e.as<Variable>()) {
return false;
}
if (const Broadcast *a = e.as<Broadcast>()) {
return should_extract(a->value);
}
if (const Cast *a = e.as<Cast>()) {
return should_extract(a->value);
}
if (const Add *a = e.as<Add>()) {
return !(is_const(a->a) || is_const(a->b));
}
if (const Sub *a = e.as<Sub>()) {
return !(is_const(a->a) || is_const(a->b));
}
if (const Mul *a = e.as<Mul>()) {
return !(is_const(a->a) || is_const(a->b));
}
if (const Div *a = e.as<Div>()) {
return !(is_const(a->a) || is_const(a->b));
}
if (const Ramp *a = e.as<Ramp>()) {
return !is_const(a->stride);
}
return true;
}
// A global-value-numbering of expressions. Returns canonical form of
// the Expr and writes out a global value numbering as a side-effect.
class GVN : public IRMutator {
public:
struct Entry {
Expr expr;
int use_count;
};
vector<Entry> entries;
typedef map<Expr, int, IRCachingDeepCompare<8> > CacheType;
CacheType numbering;
map<Expr, int, ExprCompare> shallow_numbering;
Scope<int> let_substitutions;
int number;
GVN() : number(0) {}
Stmt mutate(Stmt s) {
internal_error << "Can't call GVN on a Stmt: " << s << "\n";
return Stmt();
}
Expr mutate(Expr e) {
// Early out if we've already seen this exact Expr.
{
map<Expr, int, ExprCompare>::iterator iter = shallow_numbering.find(e);
if (iter != shallow_numbering.end()) {
number = iter->second;
entries[number].use_count++;
return entries[number].expr;
}
}
// If e is a var, check if it has been redirected to an existing numbering.
if (const Variable *var = e.as<Variable>()) {
if (let_substitutions.contains(var->name)) {
number = let_substitutions.get(var->name);
entries[number].use_count++;
return entries[number].expr;
}
}
// If e already has an entry, return that.
CacheType::iterator iter = numbering.find(e);
if (iter != numbering.end()) {
number = iter->second;
shallow_numbering[e] = number;
entries[number].use_count++;
return entries[number].expr;
}
// Rebuild using things already in the numbering.
Expr old_e = e;
e = IRMutator::mutate(e);
// See if it's there in another form after being rebuilt
// (e.g. because it was a let variable).
iter = numbering.find(e);
if (iter != numbering.end()) {
number = iter->second;
shallow_numbering[old_e] = number;
entries[number].use_count++;
return entries[number].expr;
}
// Add it to the numbering.
Entry entry = {e, 1};
number = (int)entries.size();
numbering[e] = number;
shallow_numbering[e] = number;
entries.push_back(entry);
return e;
}
using IRMutator::visit;
void visit(const Let *let) {
// Visit the value and add it to the numbering.
Expr value = mutate(let->value);
// Let values don't count in the use-count. They'll count each time the Var is used.
entries[number].use_count--;
// Make references to the variable point to the value instead.
let_substitutions.push(let->name, number);
// Visit the body and add it to the numbering.
Expr body = mutate(let->body);
let_substitutions.pop(let->name);
// Just return the body. We've removed the Let.
expr = body;
}
};
/** Rebuild an expression using a map of replacements. Works on graphs without exploding. */
class Replacer : public IRMutator {
public:
map<Expr, Expr, ExprCompare> replacements;
Replacer(const map<Expr, Expr, ExprCompare> &r) : replacements(r) {}
using IRMutator::mutate;
Expr mutate(Expr e) {
map<Expr, Expr, ExprCompare>::iterator iter = replacements.find(e);
if (iter != replacements.end()) {
return iter->second;
}
// Rebuild it, replacing children.
Expr new_e = IRMutator::mutate(e);
// In case we encounter this expr again.
replacements[e] = new_e;
return new_e;
}
};
} // namespace
Expr common_subexpression_elimination(Expr e) {
// Early-out for trivial cases.
if (!should_extract(e)) return e;
debug(4) << "\n\n\nInput to letify " << e << "\n";
GVN gvn;
e = gvn.mutate(e);
debug(4) << "Canonical form without lets " << e << "\n";
// Figure out which ones we'll pull out as lets and variables.
vector<pair<string, Expr> > lets;
vector<Expr> new_version(gvn.entries.size());
map<Expr, Expr, ExprCompare> replacements;
for (size_t i = 0; i < gvn.entries.size() - 1; i++) {
const GVN::Entry &e = gvn.entries[i];
Expr old = e.expr;
if (e.use_count > 1 && should_extract(e.expr)) {
string name = unique_name('t');
lets.push_back(make_pair(name, e.expr));
// Point references to this expr to the variable instead.
replacements[e.expr] = Variable::make(e.expr.type(), name);
}
debug(4) << i << ": " << e.expr << ", " << e.use_count << "\n";
}
// Rebuild the expr to include references to the variables:
Replacer replacer(replacements);
e = replacer.mutate(e);
debug(4) << "With variables " << e << "\n";
// Wrap the final expr in the lets.
for (size_t i = lets.size(); i > 0; i--) {
Expr value = lets[i-1].second;
// Drop this variable as an acceptible replacement for this expr.
replacer.replacements.erase(value);
// Use containing lets in the value.
value = replacer.mutate(lets[i-1].second);
e = Let::make(lets[i-1].first, value, e);
}
debug(4) << "With lets: " << e << "\n";
return e;
}
namespace {
class CSEEveryExprInStmt : public IRMutator {
public:
using IRMutator::mutate;
Expr mutate(Expr e) {
return common_subexpression_elimination(e);
}
};
} // namespace
Stmt common_subexpression_elimination(Stmt s) {
return CSEEveryExprInStmt().mutate(s);
}
// Testing code.
namespace {
// Normalize all names in an expr so that expr compares can be done
// without worrying about mere name differences.
class NormalizeVarNames : public IRMutator {
int counter = 0;
map<string, string> new_names;
using IRMutator::visit;
void visit(const Variable *var) {
map<string, string>::iterator iter = new_names.find(var->name);
if (iter == new_names.end()) {
expr = var;
} else {
expr = Variable::make(var->type, iter->second);
}
}
void visit(const Let *let) {
string new_name = "t" + int_to_string(counter++);
new_names[let->name] = new_name;
Expr value = mutate(let->value);
Expr body = mutate(let->body);
expr = Let::make(new_name, value, body);
}
};
void check(Expr in, Expr correct) {
Expr result = common_subexpression_elimination(in);
NormalizeVarNames n;
result = n.mutate(result);
internal_assert(equal(result, correct))
<< "Incorrect CSE:\n" << in
<< "\nbecame:\n" << result
<< "\ninstead of:\n" << correct << "\n";
}
// Construct a nested block of lets. Variables of the form "tn" refer
// to expr n in the vector.
Expr ssa_block(vector<Expr> exprs) {
Expr e = exprs.back();
for (size_t i = exprs.size() - 1; i > 0; i--) {
string name = "t" + int_to_string(i-1);
e = Let::make(name, exprs[i-1], e);
}
return e;
}
} // namespace
void cse_test() {
Expr x = Variable::make(Int(32), "x");
Expr t[32];
for (int i = 0; i < 32; i++) {
t[i] = Variable::make(Int(32), "t" + int_to_string(i));
}
Expr e, correct;
// Test a simple case.
e = ((x*x + x)*(x*x + x)) + x*x;
e += e;
correct = ssa_block(vec(x*x, // x*x
t[0] + x, // x*x + x
t[1] * t[1] + t[0], // (x*x + x)*(x*x + x) + x*x
t[2] + t[2]));
check(e, correct);
// Check for idempotence (also checks a case with lets)
check(correct, correct);
// Check a case with redundant lets
e = ssa_block(vec(x*x,
x*x,
t[0] / t[1],
t[1] / t[1],
t[2] % t[3],
(t[4] + x*x) + x*x));
correct = ssa_block(vec(x*x,
t[0] / t[0],
(t[1] % t[1] + t[0]) + t[0]));
check(e, correct);
// Check a case with nested lets with shared subexpressions
// between the lets, and repeated names.
Expr e1 = ssa_block(vec(x*x, // a = x*x
t[0] + x, // b = a + x
t[1] * t[1] * t[0])); // c = b * b * a
Expr e2 = ssa_block(vec(x*x, // a again
t[0] - x, // d = a - x
t[1] * t[1] * t[0])); // e = d * d * a
e = ssa_block(vec(e1 + x*x, // f = c + a
e1 + e2, // g = c + e
t[0] + t[0] * t[1])); // h = f + f * g
correct = ssa_block(vec(x*x, // t0 = a = x*x
t[0] + x, // t1 = b = a + x = t0 + x
t[1] * t[1] * t[0], // t2 = c = b * b * a = t1 * t1 * t0
t[2] + t[0], // t3 = f = c + a = t2 + t0
t[0] - x, // t4 = d = a - x = t0 - x
t[4] * t[4] * t[0], // t5 = e = d * d * a = t4 * t4 * t0
t[3] + t[3] * (t[2] + t[5]))); // h (with g substituted in)
check(e, correct);
// Test it scales OK.
e = x;
for (int i = 0; i < 100; i++) {
e = e*e + e + i;
e = e*e - e * i;
}
Expr result = common_subexpression_elimination(e);
debug(0) << "common_subexpression_elimination test passed\n";
}
}
}
<commit_msg>Remove C++11ism<commit_after>#include <map>
#include "CSE.h"
#include "IRMutator.h"
#include "IREquality.h"
#include "IROperator.h"
#include "Scope.h"
#include "Simplify.h"
namespace Halide {
namespace Internal {
using std::vector;
using std::string;
using std::map;
using std::pair;
namespace {
// Some expressions are not worth lifting out into lets, even if they
// occur redundantly many times. This list should mirror the list in
// the simplifier for lets, otherwise they'll just fight with each
// other pointlessly.
bool should_extract(Expr e) {
if (is_const(e)) {
return false;
}
if (e.as<Variable>()) {
return false;
}
if (const Broadcast *a = e.as<Broadcast>()) {
return should_extract(a->value);
}
if (const Cast *a = e.as<Cast>()) {
return should_extract(a->value);
}
if (const Add *a = e.as<Add>()) {
return !(is_const(a->a) || is_const(a->b));
}
if (const Sub *a = e.as<Sub>()) {
return !(is_const(a->a) || is_const(a->b));
}
if (const Mul *a = e.as<Mul>()) {
return !(is_const(a->a) || is_const(a->b));
}
if (const Div *a = e.as<Div>()) {
return !(is_const(a->a) || is_const(a->b));
}
if (const Ramp *a = e.as<Ramp>()) {
return !is_const(a->stride);
}
return true;
}
// A global-value-numbering of expressions. Returns canonical form of
// the Expr and writes out a global value numbering as a side-effect.
class GVN : public IRMutator {
public:
struct Entry {
Expr expr;
int use_count;
};
vector<Entry> entries;
typedef map<Expr, int, IRCachingDeepCompare<8> > CacheType;
CacheType numbering;
map<Expr, int, ExprCompare> shallow_numbering;
Scope<int> let_substitutions;
int number;
GVN() : number(0) {}
Stmt mutate(Stmt s) {
internal_error << "Can't call GVN on a Stmt: " << s << "\n";
return Stmt();
}
Expr mutate(Expr e) {
// Early out if we've already seen this exact Expr.
{
map<Expr, int, ExprCompare>::iterator iter = shallow_numbering.find(e);
if (iter != shallow_numbering.end()) {
number = iter->second;
entries[number].use_count++;
return entries[number].expr;
}
}
// If e is a var, check if it has been redirected to an existing numbering.
if (const Variable *var = e.as<Variable>()) {
if (let_substitutions.contains(var->name)) {
number = let_substitutions.get(var->name);
entries[number].use_count++;
return entries[number].expr;
}
}
// If e already has an entry, return that.
CacheType::iterator iter = numbering.find(e);
if (iter != numbering.end()) {
number = iter->second;
shallow_numbering[e] = number;
entries[number].use_count++;
return entries[number].expr;
}
// Rebuild using things already in the numbering.
Expr old_e = e;
e = IRMutator::mutate(e);
// See if it's there in another form after being rebuilt
// (e.g. because it was a let variable).
iter = numbering.find(e);
if (iter != numbering.end()) {
number = iter->second;
shallow_numbering[old_e] = number;
entries[number].use_count++;
return entries[number].expr;
}
// Add it to the numbering.
Entry entry = {e, 1};
number = (int)entries.size();
numbering[e] = number;
shallow_numbering[e] = number;
entries.push_back(entry);
return e;
}
using IRMutator::visit;
void visit(const Let *let) {
// Visit the value and add it to the numbering.
Expr value = mutate(let->value);
// Let values don't count in the use-count. They'll count each time the Var is used.
entries[number].use_count--;
// Make references to the variable point to the value instead.
let_substitutions.push(let->name, number);
// Visit the body and add it to the numbering.
Expr body = mutate(let->body);
let_substitutions.pop(let->name);
// Just return the body. We've removed the Let.
expr = body;
}
};
/** Rebuild an expression using a map of replacements. Works on graphs without exploding. */
class Replacer : public IRMutator {
public:
map<Expr, Expr, ExprCompare> replacements;
Replacer(const map<Expr, Expr, ExprCompare> &r) : replacements(r) {}
using IRMutator::mutate;
Expr mutate(Expr e) {
map<Expr, Expr, ExprCompare>::iterator iter = replacements.find(e);
if (iter != replacements.end()) {
return iter->second;
}
// Rebuild it, replacing children.
Expr new_e = IRMutator::mutate(e);
// In case we encounter this expr again.
replacements[e] = new_e;
return new_e;
}
};
} // namespace
Expr common_subexpression_elimination(Expr e) {
// Early-out for trivial cases.
if (!should_extract(e)) return e;
debug(4) << "\n\n\nInput to letify " << e << "\n";
GVN gvn;
e = gvn.mutate(e);
debug(4) << "Canonical form without lets " << e << "\n";
// Figure out which ones we'll pull out as lets and variables.
vector<pair<string, Expr> > lets;
vector<Expr> new_version(gvn.entries.size());
map<Expr, Expr, ExprCompare> replacements;
for (size_t i = 0; i < gvn.entries.size() - 1; i++) {
const GVN::Entry &e = gvn.entries[i];
Expr old = e.expr;
if (e.use_count > 1 && should_extract(e.expr)) {
string name = unique_name('t');
lets.push_back(make_pair(name, e.expr));
// Point references to this expr to the variable instead.
replacements[e.expr] = Variable::make(e.expr.type(), name);
}
debug(4) << i << ": " << e.expr << ", " << e.use_count << "\n";
}
// Rebuild the expr to include references to the variables:
Replacer replacer(replacements);
e = replacer.mutate(e);
debug(4) << "With variables " << e << "\n";
// Wrap the final expr in the lets.
for (size_t i = lets.size(); i > 0; i--) {
Expr value = lets[i-1].second;
// Drop this variable as an acceptible replacement for this expr.
replacer.replacements.erase(value);
// Use containing lets in the value.
value = replacer.mutate(lets[i-1].second);
e = Let::make(lets[i-1].first, value, e);
}
debug(4) << "With lets: " << e << "\n";
return e;
}
namespace {
class CSEEveryExprInStmt : public IRMutator {
public:
using IRMutator::mutate;
Expr mutate(Expr e) {
return common_subexpression_elimination(e);
}
};
} // namespace
Stmt common_subexpression_elimination(Stmt s) {
return CSEEveryExprInStmt().mutate(s);
}
// Testing code.
namespace {
// Normalize all names in an expr so that expr compares can be done
// without worrying about mere name differences.
class NormalizeVarNames : public IRMutator {
int counter;
map<string, string> new_names;
using IRMutator::visit;
void visit(const Variable *var) {
map<string, string>::iterator iter = new_names.find(var->name);
if (iter == new_names.end()) {
expr = var;
} else {
expr = Variable::make(var->type, iter->second);
}
}
void visit(const Let *let) {
string new_name = "t" + int_to_string(counter++);
new_names[let->name] = new_name;
Expr value = mutate(let->value);
Expr body = mutate(let->body);
expr = Let::make(new_name, value, body);
}
public:
NormalizeVarNames() : counter(0) {}
};
void check(Expr in, Expr correct) {
Expr result = common_subexpression_elimination(in);
NormalizeVarNames n;
result = n.mutate(result);
internal_assert(equal(result, correct))
<< "Incorrect CSE:\n" << in
<< "\nbecame:\n" << result
<< "\ninstead of:\n" << correct << "\n";
}
// Construct a nested block of lets. Variables of the form "tn" refer
// to expr n in the vector.
Expr ssa_block(vector<Expr> exprs) {
Expr e = exprs.back();
for (size_t i = exprs.size() - 1; i > 0; i--) {
string name = "t" + int_to_string(i-1);
e = Let::make(name, exprs[i-1], e);
}
return e;
}
} // namespace
void cse_test() {
Expr x = Variable::make(Int(32), "x");
Expr t[32];
for (int i = 0; i < 32; i++) {
t[i] = Variable::make(Int(32), "t" + int_to_string(i));
}
Expr e, correct;
// Test a simple case.
e = ((x*x + x)*(x*x + x)) + x*x;
e += e;
correct = ssa_block(vec(x*x, // x*x
t[0] + x, // x*x + x
t[1] * t[1] + t[0], // (x*x + x)*(x*x + x) + x*x
t[2] + t[2]));
check(e, correct);
// Check for idempotence (also checks a case with lets)
check(correct, correct);
// Check a case with redundant lets
e = ssa_block(vec(x*x,
x*x,
t[0] / t[1],
t[1] / t[1],
t[2] % t[3],
(t[4] + x*x) + x*x));
correct = ssa_block(vec(x*x,
t[0] / t[0],
(t[1] % t[1] + t[0]) + t[0]));
check(e, correct);
// Check a case with nested lets with shared subexpressions
// between the lets, and repeated names.
Expr e1 = ssa_block(vec(x*x, // a = x*x
t[0] + x, // b = a + x
t[1] * t[1] * t[0])); // c = b * b * a
Expr e2 = ssa_block(vec(x*x, // a again
t[0] - x, // d = a - x
t[1] * t[1] * t[0])); // e = d * d * a
e = ssa_block(vec(e1 + x*x, // f = c + a
e1 + e2, // g = c + e
t[0] + t[0] * t[1])); // h = f + f * g
correct = ssa_block(vec(x*x, // t0 = a = x*x
t[0] + x, // t1 = b = a + x = t0 + x
t[1] * t[1] * t[0], // t2 = c = b * b * a = t1 * t1 * t0
t[2] + t[0], // t3 = f = c + a = t2 + t0
t[0] - x, // t4 = d = a - x = t0 - x
t[4] * t[4] * t[0], // t5 = e = d * d * a = t4 * t4 * t0
t[3] + t[3] * (t[2] + t[5]))); // h (with g substituted in)
check(e, correct);
// Test it scales OK.
e = x;
for (int i = 0; i < 100; i++) {
e = e*e + e + i;
e = e*e - e * i;
}
Expr result = common_subexpression_elimination(e);
debug(0) << "common_subexpression_elimination test passed\n";
}
}
}
<|endoftext|> |
<commit_before>#ifdef NG_PYTHON
#include <boost/python.hpp>
#include <meshing.hpp>
#include <geometry2d.hpp>
using namespace netgen;
namespace bp = boost::python;
//////////////////////////////////////////////////////////////////////
// Lambda to function pointer conversion
template <typename Function>
struct function_traits
: public function_traits<decltype(&Function::operator())> {};
template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const> {
typedef ReturnType (*pointer)(Args...);
typedef ReturnType return_type;
};
template <typename Function>
typename function_traits<Function>::pointer
FunctionPointer (const Function& lambda) {
return static_cast<typename function_traits<Function>::pointer>(lambda);
}
template <class T>
inline string ToString (const T& t)
{
stringstream ss;
ss << t;
return ss.str();
}
void ExportGeom2d()
{
std::string nested_name = "geom2d";
if( bp::scope() )
nested_name = bp::extract<std::string>(bp::scope().attr("__name__") + ".geom2d");
bp::object module(bp::handle<>(bp::borrowed(PyImport_AddModule(nested_name.c_str()))));
cout << "exporting geom2d " << nested_name << endl;
bp::object parent = bp::scope() ? bp::scope() : bp::import("__main__");
parent.attr("geom2d") = module ;
bp::scope local_scope(module);
bp::class_<SplineGeometry2d, boost::noncopyable>("SplineGeometry")
.def("Load",&SplineGeometry2d::Load)
.def("AppendPoint", FunctionPointer([](SplineGeometry2d &self, double px, double py)
{
Point<2> p;
p(0) = px;
p(1) = py;
self.geompoints.Append(GeomPoint<2>(p,1));
return self.geompoints.Size()-1;
}))
.def("AppendSegment", FunctionPointer([](SplineGeometry2d &self, int point_index1, int point_index2)//, int leftdomain, int rightdomain)
{
LineSeg<2> * l = new LineSeg<2>(self.GetPoint(point_index1), self.GetPoint(point_index2));
SplineSegExt * seg = new SplineSegExt(*l);
seg->leftdom = 1;// leftdomain;
seg->rightdom = 0;// rightdomain;
seg->hmax = 1e99;
seg->reffak = 1;
seg->copyfrom = -1;
self.AppendSegment(seg);
}))//, (bp::arg("self"), bp::arg("point_index1"), bp::arg("point_index2"), bp::arg("leftdomain") = 1, bp::arg("rightdomain") = 0) )
.def("AppendSegment", FunctionPointer([](SplineGeometry2d &self, int point_index1, int point_index2, int point_index3)//, int leftdomain, int rightdomain)
{
SplineSeg3<2> * seg3 = new SplineSeg3<2>(self.GetPoint(point_index1), self.GetPoint(point_index2), self.GetPoint(point_index3));
SplineSegExt * seg = new SplineSegExt(*seg3);
seg->leftdom = 1;// leftdomain;
seg->rightdom = 0;// rightdomain;
seg->hmax = 1e99;
seg->reffak = 1;
seg->copyfrom = -1;
self.AppendSegment(seg);
}))//, (bp::arg("self"), bp::arg("point_index1"), bp::arg("point_index2"), bp::arg("point_index3"), bp::arg("leftdomain") = 1, bp::arg("rightdomain") = 0 ) )
.def("PlotData", FunctionPointer([](SplineGeometry2d &self)
{
Box<2> box(self.GetBoundingBox());
double xdist = box.PMax()(0) - box.PMin()(0);
double ydist = box.PMax()(1) - box.PMin()(1);
bp::tuple xlim = bp::make_tuple(box.PMin()(0) - 0.1*xdist, box.PMax()(0) + 0.1*xdist);
bp::tuple ylim = bp::make_tuple(box.PMin()(1) - 0.1*ydist, box.PMax()(1) + 0.1*ydist);
bp::list xpoints, ypoints;
GeomPoint<2> point = self.splines[0]->StartPI();
xpoints.append(point(0));
ypoints.append(point(1));
for (int i = 0; i < self.splines.Size(); i++)
{
if (self.splines[i]->GetType().compare("line")==0)
{
GeomPoint<2> point = self.splines[i]->EndPI();
xpoints.append(point(0));
ypoints.append(point(1));
}
else if (self.splines[i]->GetType().compare("spline3")==0)
{
double len = self.splines[i]->Length();
int n = floor(len/(0.05*min(xdist,ydist)));
//cout << n << endl;
for (int j = 1; j <= n; j++)
{
GeomPoint<2> point = self.splines[i]->GetPoint(j*1./n);
xpoints.append(point(0));
ypoints.append(point(1));
}
}
else
{
cout << "spline is neither line nor spline3" << endl;
}
}
return bp::tuple(bp::make_tuple(xlim, ylim, xpoints, ypoints));
}))
.def("PointData", FunctionPointer([](SplineGeometry2d &self)
{
bp::list xpoints, ypoints, pointindex;
for (int i = 0; i < self.geompoints.Size(); i++)
{
pointindex.append(i);
xpoints.append(self.geompoints[i][0]);
ypoints.append(self.geompoints[i][1]);
}
return bp::tuple(bp::make_tuple(xpoints, ypoints, pointindex));
}))
.def("SegmentData", FunctionPointer([](SplineGeometry2d &self)
{
bp::list leftpoints, rightpoints, leftdom, rightdom;
for (int i = 0; i < self.splines.Size(); i++)
{
GeomPoint<2> point = self.splines[i]->GetPoint(0.5);
Vec<2> normal = self.GetSpline(i).GetTangent(0.5);
double temp = normal(0);
normal(0) = normal(1);
normal(1) = -temp;
leftdom.append(self.GetSpline(i).leftdom);
rightdom.append(self.GetSpline(i).rightdom);
rightpoints.append(bp::make_tuple(point(0), point(1), normal(0)<0, normal(1)<0));
leftpoints.append(bp::make_tuple(point(0), point(1), normal(0)<0, normal(1)<0));
}
return bp::tuple(bp::make_tuple(leftpoints, rightpoints, leftdom, rightdom));
}))
.def("Print", FunctionPointer([](SplineGeometry2d &self)
{
for (int i = 0; i < self.geompoints.Size(); i++)
{
cout << i << " : " << self.geompoints[i][0] << " , " << self.geompoints[i][1] << endl;
}
//Box<2> box(self.GetBoundingBox());
//cout << box.PMin() << endl;
//cout << box.PMax() << endl;
cout << self.splines.Size() << endl;
for (int i = 0; i < self.splines.Size(); i++)
{
cout << self.splines[i]->GetType() << endl;
//cout << i << " : " << self.splines[i]->GetPoint(0.1) << " , " << self.splines[i]->GetPoint(0.5) << endl;
}
}))
.def("GenerateMesh", FunctionPointer([](SplineGeometry2d &self, MeshingParameters & mparam)
{
Mesh * mesh = NULL;
self.GenerateMesh(mesh, mparam, 0, 0);
return shared_ptr<Mesh>(mesh);
}))
;
}
#endif
<commit_msg>new method "Append" to add segments<commit_after>#ifdef NG_PYTHON
#include <boost/python.hpp>
#include <meshing.hpp>
#include <geometry2d.hpp>
using namespace netgen;
namespace bp = boost::python;
//////////////////////////////////////////////////////////////////////
// Lambda to function pointer conversion
template <typename Function>
struct function_traits
: public function_traits<decltype(&Function::operator())> {};
template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const> {
typedef ReturnType (*pointer)(Args...);
typedef ReturnType return_type;
};
template <typename Function>
typename function_traits<Function>::pointer
FunctionPointer (const Function& lambda) {
return static_cast<typename function_traits<Function>::pointer>(lambda);
}
template <class T>
inline string ToString (const T& t)
{
stringstream ss;
ss << t;
return ss.str();
}
void ExportGeom2d()
{
std::string nested_name = "geom2d";
if( bp::scope() )
nested_name = bp::extract<std::string>(bp::scope().attr("__name__") + ".geom2d");
bp::object module(bp::handle<>(bp::borrowed(PyImport_AddModule(nested_name.c_str()))));
cout << "exporting geom2d " << nested_name << endl;
bp::object parent = bp::scope() ? bp::scope() : bp::import("__main__");
parent.attr("geom2d") = module ;
bp::scope local_scope(module);
bp::class_<SplineGeometry2d, boost::noncopyable>("SplineGeometry")
.def("Load",&SplineGeometry2d::Load)
.def("AppendPoint", FunctionPointer([](SplineGeometry2d &self, double px, double py)
{
Point<2> p;
p(0) = px;
p(1) = py;
self.geompoints.Append(GeomPoint<2>(p,1));
return self.geompoints.Size()-1;
}))
.def("Append", FunctionPointer([](SplineGeometry2d &self, bp::list segment, int leftdomain, int rightdomain)
{
bp::extract<std::string> segtype(segment[0]);
SplineSegExt * seg;
if (segtype().compare("line") == 0)
{
bp::extract<int> point_index1(segment[1]);
bp::extract<int> point_index2(segment[2]);
//point_index1.check()
LineSeg<2> * l = new LineSeg<2>(self.GetPoint(point_index1()), self.GetPoint(point_index2()));
seg = new SplineSegExt(*l);
}
else if (segtype().compare("spline3") == 0)
{
bp::extract<int> point_index1(segment[1]);
bp::extract<int> point_index2(segment[2]);
bp::extract<int> point_index3(segment[3]);
SplineSeg3<2> * seg3 = new SplineSeg3<2>(self.GetPoint(point_index1()), self.GetPoint(point_index2()), self.GetPoint(point_index3()));
seg = new SplineSegExt(*seg3);
}
else
{
cout << "Appended segment is not a line or a spline3" << endl;
}
seg->leftdom = leftdomain;
seg->rightdom = rightdomain;
seg->hmax = 1e99;
seg->reffak = 1;
seg->copyfrom = -1;
self.AppendSegment(seg);
}), (bp::arg("self"), bp::arg("point_indices"), bp::arg("leftdomain") = 1, bp::arg("rightdomain") = 0))
.def("AppendSegment", FunctionPointer([](SplineGeometry2d &self, bp::list point_indices, int leftdomain, int rightdomain)
{
int npts = bp::len(point_indices);
SplineSegExt * seg;
//int a = bp::extract<int>(point_indices[0]);
if (npts == 2)
{
LineSeg<2> * l = new LineSeg<2>(self.GetPoint(bp::extract<int>(point_indices[0])), self.GetPoint(bp::extract<int>(point_indices[1])));
seg = new SplineSegExt(*l);
}
else if (npts == 3)
{
SplineSeg3<2> * seg3 = new SplineSeg3<2>(self.GetPoint(bp::extract<int>(point_indices[0])), self.GetPoint(bp::extract<int>(point_indices[1])), self.GetPoint(bp::extract<int>(point_indices[2])));
seg = new SplineSegExt(*seg3);
}
seg->leftdom = leftdomain;
seg->rightdom = rightdomain;
seg->hmax = 1e99;
seg->reffak = 1;
seg->copyfrom = -1;
self.AppendSegment(seg);
}), (bp::arg("self"), bp::arg("point_indices"), bp::arg("leftdomain") = 1, bp::arg("rightdomain") = 0) )
//.def("AppendSegment", FunctionPointer([](SplineGeometry2d &self, int point_index1, int point_index2)//, int leftdomain, int rightdomain)
// {
// LineSeg<2> * l = new LineSeg<2>(self.GetPoint(point_index1), self.GetPoint(point_index2));
// SplineSegExt * seg = new SplineSegExt(*l);
// seg->leftdom = 1;// leftdomain;
// seg->rightdom = 0;// rightdomain;
// seg->hmax = 1e99;
// seg->reffak = 1;
// seg->copyfrom = -1;
// self.AppendSegment(seg);
// }))//, (bp::arg("self"), bp::arg("point_index1"), bp::arg("point_index2"), bp::arg("leftdomain") = 1, bp::arg("rightdomain") = 0) )
//.def("AppendSegment", FunctionPointer([](SplineGeometry2d &self, int point_index1, int point_index2, int point_index3)//, int leftdomain, int rightdomain)
// {
// SplineSeg3<2> * seg3 = new SplineSeg3<2>(self.GetPoint(point_index1), self.GetPoint(point_index2), self.GetPoint(point_index3));
// SplineSegExt * seg = new SplineSegExt(*seg3);
// seg->leftdom = 1;// leftdomain;
// seg->rightdom = 0;// rightdomain;
// seg->hmax = 1e99;
// seg->reffak = 1;
// seg->copyfrom = -1;
// self.AppendSegment(seg);
// }))//, (bp::arg("self"), bp::arg("point_index1"), bp::arg("point_index2"), bp::arg("point_index3"), bp::arg("leftdomain") = 1, bp::arg("rightdomain") = 0 ) )
.def("PlotData", FunctionPointer([](SplineGeometry2d &self)
{
Box<2> box(self.GetBoundingBox());
double xdist = box.PMax()(0) - box.PMin()(0);
double ydist = box.PMax()(1) - box.PMin()(1);
bp::tuple xlim = bp::make_tuple(box.PMin()(0) - 0.1*xdist, box.PMax()(0) + 0.1*xdist);
bp::tuple ylim = bp::make_tuple(box.PMin()(1) - 0.1*ydist, box.PMax()(1) + 0.1*ydist);
bp::list xpoints, ypoints;
for (int i = 0; i < self.splines.Size(); i++)
{
bp::list xp, yp;
if (self.splines[i]->GetType().compare("line")==0)
{
GeomPoint<2> p1 = self.splines[i]->StartPI();
GeomPoint<2> p2 = self.splines[i]->EndPI();
xp.append(p1(0));
xp.append(p2(0));
yp.append(p1(1));
yp.append(p2(1));
}
else if (self.splines[i]->GetType().compare("spline3")==0)
{
double len = self.splines[i]->Length();
int n = floor(len/(0.05*min(xdist,ydist)));
for (int j = 0; j <= n; j++)
{
GeomPoint<2> point = self.splines[i]->GetPoint(j*1./n);
xp.append(point(0));
yp.append(point(1));
}
}
else
{
cout << "spline is neither line nor spline3" << endl;
}
xpoints.append(xp);
ypoints.append(yp);
}
return bp::tuple(bp::make_tuple(xlim, ylim, xpoints, ypoints));
}))
.def("PointData", FunctionPointer([](SplineGeometry2d &self)
{
bp::list xpoints, ypoints, pointindex;
for (int i = 0; i < self.geompoints.Size(); i++)
{
pointindex.append(i);
xpoints.append(self.geompoints[i][0]);
ypoints.append(self.geompoints[i][1]);
}
return bp::tuple(bp::make_tuple(xpoints, ypoints, pointindex));
}))
.def("SegmentData", FunctionPointer([](SplineGeometry2d &self)
{
bp::list leftpoints, rightpoints, leftdom, rightdom;
for (int i = 0; i < self.splines.Size(); i++)
{
GeomPoint<2> point = self.splines[i]->GetPoint(0.5);
Vec<2> normal = self.GetSpline(i).GetTangent(0.5);
double temp = normal(0);
normal(0) = normal(1);
normal(1) = -temp;
leftdom.append(self.GetSpline(i).leftdom);
rightdom.append(self.GetSpline(i).rightdom);
rightpoints.append(bp::make_tuple(point(0), point(1), normal(0)<0, normal(1)<0));
leftpoints.append(bp::make_tuple(point(0), point(1), normal(0)<0, normal(1)<0));
}
return bp::tuple(bp::make_tuple(leftpoints, rightpoints, leftdom, rightdom));
}))
.def("Print", FunctionPointer([](SplineGeometry2d &self)
{
for (int i = 0; i < self.geompoints.Size(); i++)
{
cout << i << " : " << self.geompoints[i][0] << " , " << self.geompoints[i][1] << endl;
}
//Box<2> box(self.GetBoundingBox());
//cout << box.PMin() << endl;
//cout << box.PMax() << endl;
cout << self.splines.Size() << endl;
for (int i = 0; i < self.splines.Size(); i++)
{
cout << self.splines[i]->GetType() << endl;
//cout << i << " : " << self.splines[i]->GetPoint(0.1) << " , " << self.splines[i]->GetPoint(0.5) << endl;
}
}))
.def("GenerateMesh", FunctionPointer([](SplineGeometry2d &self, MeshingParameters & mparam)
{
Mesh * mesh = NULL;
self.GenerateMesh(mesh, mparam, 0, 0);
return shared_ptr<Mesh>(mesh);
}))
;
}
#endif
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
using namespace fnord;
struct PosiInfo {
PosiInfo() : views(0), clicks(0) {}
uint64_t views;
uint64_t clicks;
};
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
HashMap<uint32_t, PosiInfo> click_posis;
auto start_time = std::numeric_limits<uint64_t>::max();
auto end_time = std::numeric_limits<uint64_t>::min();
auto eligibility = cm::ItemEligibility::DAWANDA_ALL_NOBOTS;
/* read input tables */
auto sstables = flags.getArgv();
int row_idx = 0;
for (int tbl_idx = 0; tbl_idx < sstables.size(); ++tbl_idx) {
const auto& sstable = sstables[tbl_idx];
fnord::logInfo("cm.ctrstats", "Importing sstable: $0", sstable);
/* read sstable header */
sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));
if (reader.bodySize() == 0) {
fnord::logCritical("cm.ctrstats", "unfinished sstable: $0", sstable);
exit(1);
}
/* read report header */
auto hdr = json::parseJSON(reader.readHeader());
auto tbl_start_time = json::JSONUtil::objectGetUInt64(
hdr.begin(),
hdr.end(),
"start_time").get();
auto tbl_end_time = json::JSONUtil::objectGetUInt64(
hdr.begin(),
hdr.end(),
"end_time").get();
if (tbl_start_time < start_time) {
start_time = tbl_start_time;
}
if (tbl_end_time > end_time) {
end_time = tbl_end_time;
}
/* get sstable cursor */
auto cursor = reader.getCursor();
auto body_size = reader.bodySize();
/* status line */
util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
fnord::logInfo(
"cm.ctrstats",
"[$1/$2] [$0%] Reading sstable... rows=$3",
(size_t) ((cursor->position() / (double) body_size) * 100),
tbl_idx + 1, sstables.size(), row_idx);
});
/* read sstable rows */
for (; cursor->valid(); ++row_idx) {
status_line.runMaybe();
auto val = cursor->getDataBuffer();
Option<cm::JoinedQuery> q;
try {
q = Some(json::fromJSON<cm::JoinedQuery>(val));
} catch (const Exception& e) {
//fnord::logWarning("cm.ctrstats", e, "invalid json: $0", val.toString());
}
if (!q.isEmpty() && isQueryEligible(eligibility, q.get())) {
for (auto& item : q.get().items) {
if (!isItemEligible(eligibility, q.get(), item) ||
item.position < 1) {
continue;
}
auto& pi = click_posis[item.position];
++pi.views;
pi.clicks += item.clicked;
}
}
if (!cursor->next()) {
break;
}
}
status_line.runForce();
}
uint64_t total_clicks = 0;
uint64_t total_views = 0;
Vector<Pair<uint64_t, PosiInfo>> posis;
for (const auto& p : click_posis) {
total_clicks += p.second.clicks;
total_views += p.second.views;
posis.emplace_back(p);
}
std::sort(posis.begin(), posis.end(), [] (
const Pair<uint64_t, PosiInfo>& a,
const Pair<uint64_t, PosiInfo>& b) {
return a.first < b.first;
});
for (const auto& p : posis) {
auto share = (p.second.clicks / (double) total_clicks) * 100;
auto ctr = p.second.clicks / (double) p.second.views;
fnord::iputs(" position $0 => views=$1 clicks=$2 share=$3 ctr=$4",
p.first,
p.second.views,
p.second.clicks,
share,
ctr);
}
return 0;
}
<commit_msg>better output in clickposihisto<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
using namespace fnord;
struct PosiInfo {
PosiInfo() : views(0), clicks(0) {}
uint64_t views;
uint64_t clicks;
};
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
HashMap<uint32_t, PosiInfo> click_posis;
auto start_time = std::numeric_limits<uint64_t>::max();
auto end_time = std::numeric_limits<uint64_t>::min();
auto eligibility = cm::ItemEligibility::DAWANDA_ALL_NOBOTS;
util::SimpleRateLimitedFn print_results(kMicrosPerSecond * 10, [&] () {
uint64_t total_clicks = 0;
uint64_t total_views = 0;
Vector<Pair<uint64_t, PosiInfo>> posis;
for (const auto& p : click_posis) {
total_clicks += p.second.clicks;
total_views += p.second.views;
posis.emplace_back(p);
}
std::sort(posis.begin(), posis.end(), [] (
const Pair<uint64_t, PosiInfo>& a,
const Pair<uint64_t, PosiInfo>& b) {
return a.first < b.first;
});
for (const auto& p : posis) {
auto share = (p.second.clicks / (double) total_clicks) * 100;
auto ctr = p.second.clicks / (double) p.second.views;
fnord::iputs(" position $0 => views=$1 clicks=$2 share=$3 ctr=$4",
p.first,
p.second.views,
p.second.clicks,
share,
ctr);
}
});
/* read input tables */
auto sstables = flags.getArgv();
int row_idx = 0;
for (int tbl_idx = 0; tbl_idx < sstables.size(); ++tbl_idx) {
const auto& sstable = sstables[tbl_idx];
fnord::logInfo("cm.ctrstats", "Importing sstable: $0", sstable);
/* read sstable header */
sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));
if (reader.bodySize() == 0) {
fnord::logCritical("cm.ctrstats", "unfinished sstable: $0", sstable);
exit(1);
}
/* read report header */
auto hdr = json::parseJSON(reader.readHeader());
auto tbl_start_time = json::JSONUtil::objectGetUInt64(
hdr.begin(),
hdr.end(),
"start_time").get();
auto tbl_end_time = json::JSONUtil::objectGetUInt64(
hdr.begin(),
hdr.end(),
"end_time").get();
if (tbl_start_time < start_time) {
start_time = tbl_start_time;
}
if (tbl_end_time > end_time) {
end_time = tbl_end_time;
}
/* get sstable cursor */
auto cursor = reader.getCursor();
auto body_size = reader.bodySize();
/* status line */
util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
fnord::logInfo(
"cm.ctrstats",
"[$1/$2] [$0%] Reading sstable... rows=$3",
(size_t) ((cursor->position() / (double) body_size) * 100),
tbl_idx + 1, sstables.size(), row_idx);
});
/* read sstable rows */
for (; cursor->valid(); ++row_idx) {
status_line.runMaybe();
print_results.runMaybe();
auto val = cursor->getDataBuffer();
Option<cm::JoinedQuery> q;
try {
q = Some(json::fromJSON<cm::JoinedQuery>(val));
} catch (const Exception& e) {
//fnord::logWarning("cm.ctrstats", e, "invalid json: $0", val.toString());
}
if (!q.isEmpty() && isQueryEligible(eligibility, q.get())) {
for (auto& item : q.get().items) {
if (!isItemEligible(eligibility, q.get(), item) ||
item.position < 1) {
continue;
}
auto& pi = click_posis[item.position];
++pi.views;
pi.clicks += item.clicked;
}
}
if (!cursor->next()) {
break;
}
}
status_line.runForce();
}
print_results.runForce();
return 0;
}
<|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 <iosfwd>
#include <sstream>
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/platform_thread.h"
#include "base/port.h"
#include "build/build_config.h"
#include "chrome/browser/sync/util/event_sys-inl.h"
#include "testing/gtest/include/gtest/gtest.h"
using std::endl;
using std::ostream;
using std::string;
using std::stringstream;
using std::vector;
namespace {
class Pair;
struct TestEvent {
Pair* source;
enum {
A_CHANGED, B_CHANGED, PAIR_BEING_DELETED,
} what_happened;
int old_value;
};
struct TestEventTraits {
typedef TestEvent EventType;
static bool IsChannelShutdownEvent(const TestEvent& event) {
return TestEvent::PAIR_BEING_DELETED == event.what_happened;
}
};
class Pair {
public:
typedef EventChannel<TestEventTraits> Channel;
explicit Pair(const string& name) : name_(name), a_(0), b_(0) {
TestEvent shutdown = { this, TestEvent::PAIR_BEING_DELETED, 0 };
event_channel_ = new Channel(shutdown);
}
~Pair() {
delete event_channel_;
}
void set_a(int n) {
TestEvent event = { this, TestEvent::A_CHANGED, a_ };
a_ = n;
event_channel_->NotifyListeners(event);
}
void set_b(int n) {
TestEvent event = { this, TestEvent::B_CHANGED, b_ };
b_ = n;
event_channel_->NotifyListeners(event);
}
int a() const { return a_; }
int b() const { return b_; }
const string& name() { return name_; }
Channel* event_channel() const { return event_channel_; }
protected:
const string name_;
int a_;
int b_;
Channel* event_channel_;
};
class EventLogger {
public:
explicit EventLogger(ostream& out) : out_(out) { }
~EventLogger() {
for (Hookups::iterator i = hookups_.begin(); i != hookups_.end(); ++i)
delete *i;
}
void Hookup(const string name, Pair::Channel* channel) {
hookups_.push_back(NewEventListenerHookup(channel, this,
&EventLogger::HandlePairEvent,
name));
}
void HandlePairEvent(const string& name, const TestEvent& event) {
const char* what_changed = NULL;
int new_value = 0;
Hookups::iterator dead;
switch (event.what_happened) {
case TestEvent::A_CHANGED:
what_changed = "A";
new_value = event.source->a();
break;
case TestEvent::B_CHANGED:
what_changed = "B";
new_value = event.source->b();
break;
case TestEvent::PAIR_BEING_DELETED:
out_ << name << " heard " << event.source->name() << " being deleted."
<< endl;
return;
default:
LOG(FATAL) << "Bad event.what_happened: " << event.what_happened;
break;
}
out_ << name << " heard " << event.source->name() << "'s " << what_changed
<< " change from "
<< event.old_value << " to " << new_value << endl;
}
typedef vector<EventListenerHookup*> Hookups;
Hookups hookups_;
ostream& out_;
};
const char golden_result[] = "Larry heard Sally's B change from 0 to 2\n"
"Larry heard Sally's A change from 1 to 3\n"
"Lewis heard Sam's B change from 0 to 5\n"
"Larry heard Sally's A change from 3 to 6\n"
"Larry heard Sally being deleted.\n";
TEST(EventSys, Basic) {
Pair sally("Sally"), sam("Sam");
sally.set_a(1);
stringstream log;
EventLogger logger(log);
logger.Hookup("Larry", sally.event_channel());
sally.set_b(2);
sally.set_a(3);
sam.set_a(4);
logger.Hookup("Lewis", sam.event_channel());
sam.set_b(5);
sally.set_a(6);
// Test that disconnect within callback doesn't deadlock.
TestEvent event = {&sally, TestEvent::PAIR_BEING_DELETED, 0 };
sally.event_channel()->NotifyListeners(event);
sally.set_a(7);
ASSERT_EQ(log.str(), golden_result);
}
// This goes pretty far beyond the normal use pattern, so don't use
// ThreadTester as an example of what to do.
class ThreadTester : public EventListener<TestEvent>,
public PlatformThread::Delegate {
public:
explicit ThreadTester(Pair* pair)
: pair_(pair), remove_event_(&remove_event_mutex_),
remove_event_bool_(false) {
pair_->event_channel()->AddListener(this);
}
~ThreadTester() {
pair_->event_channel()->RemoveListener(this);
for (size_t i = 0; i < threads_.size(); i++) {
PlatformThread::Join(threads_[i].thread);
}
}
struct ThreadInfo {
PlatformThreadHandle thread;
bool* completed;
};
struct ThreadArgs {
ConditionVariable* thread_running_cond;
Lock* thread_running_mutex;
bool thread_running;
bool completed;
};
void Go() {
Lock thread_running_mutex;
ConditionVariable thread_running_cond(&thread_running_mutex);
ThreadArgs args;
ThreadInfo info;
info.completed = false;
args.completed = info.completed;
args.thread_running_cond = &(thread_running_cond);
args.thread_running_mutex = &(thread_running_mutex);
args.thread_running = false;
args_ = args;
ASSERT_TRUE(PlatformThread::Create(0, this, &info.thread));
thread_running_mutex.Acquire();
while ((args_.thread_running) == false) {
thread_running_cond.Wait();
}
thread_running_mutex.Release();
threads_.push_back(info);
}
// PlatformThread::Delegate methods.
virtual void ThreadMain() {
// Make sure each thread gets a current MessageLoop in TLS.
// This test should use chrome threads for testing, but I'll leave it like
// this for the moment since it requires a big chunk of rewriting and I
// want the test passing while I checkpoint my CL. Technically speaking,
// there should be no functional difference.
MessageLoop message_loop;
args_.thread_running_mutex->Acquire();
args_.thread_running = true;
args_.thread_running_mutex->Release();
args_.thread_running_cond->Signal();
remove_event_mutex_.Acquire();
while (remove_event_bool_ == false) {
remove_event_.Wait();
}
remove_event_mutex_.Release();
// Normally, you'd just delete the hookup. This is very bad style, but
// necessary for the test.
pair_->event_channel()->RemoveListener(this);
args_.completed = true;
}
void HandleEvent(const TestEvent& event) {
remove_event_mutex_.Acquire();
remove_event_bool_ = true;
remove_event_mutex_.Release();
remove_event_.Broadcast();
PlatformThread::YieldCurrentThread();
for (size_t i = 0; i < threads_.size(); i++) {
if (threads_[i].completed)
LOG(FATAL) << "A test thread exited too early.";
}
}
Pair* pair_;
ConditionVariable remove_event_;
Lock remove_event_mutex_;
bool remove_event_bool_;
vector<ThreadInfo> threads_;
ThreadArgs args_;
};
TEST(EventSys, Multithreaded) {
Pair sally("Sally");
ThreadTester a(&sally);
for (int i = 0; i < 3; ++i)
a.Go();
sally.set_b(99);
}
class HookupDeleter {
public:
void HandleEvent(const TestEvent& event) {
delete hookup_;
hookup_ = NULL;
}
EventListenerHookup* hookup_;
};
TEST(EventSys, InHandlerDeletion) {
Pair sally("Sally");
HookupDeleter deleter;
deleter.hookup_ = NewEventListenerHookup(sally.event_channel(),
&deleter,
&HookupDeleter::HandleEvent);
sally.set_a(1);
ASSERT_TRUE(NULL == deleter.hookup_);
}
} // namespace
<commit_msg>Revert 31109 - Avoid calling PlatformThread::Sleep(1) from event_sys_unittests.cc<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 <iosfwd>
#include <sstream>
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/platform_thread.h"
#include "base/port.h"
#include "build/build_config.h"
#include "chrome/browser/sync/util/event_sys-inl.h"
#include "testing/gtest/include/gtest/gtest.h"
using std::endl;
using std::ostream;
using std::string;
using std::stringstream;
using std::vector;
namespace {
class Pair;
struct TestEvent {
Pair* source;
enum {
A_CHANGED, B_CHANGED, PAIR_BEING_DELETED,
} what_happened;
int old_value;
};
struct TestEventTraits {
typedef TestEvent EventType;
static bool IsChannelShutdownEvent(const TestEvent& event) {
return TestEvent::PAIR_BEING_DELETED == event.what_happened;
}
};
class Pair {
public:
typedef EventChannel<TestEventTraits> Channel;
explicit Pair(const string& name) : name_(name), a_(0), b_(0) {
TestEvent shutdown = { this, TestEvent::PAIR_BEING_DELETED, 0 };
event_channel_ = new Channel(shutdown);
}
~Pair() {
delete event_channel_;
}
void set_a(int n) {
TestEvent event = { this, TestEvent::A_CHANGED, a_ };
a_ = n;
event_channel_->NotifyListeners(event);
}
void set_b(int n) {
TestEvent event = { this, TestEvent::B_CHANGED, b_ };
b_ = n;
event_channel_->NotifyListeners(event);
}
int a() const { return a_; }
int b() const { return b_; }
const string& name() { return name_; }
Channel* event_channel() const { return event_channel_; }
protected:
const string name_;
int a_;
int b_;
Channel* event_channel_;
};
class EventLogger {
public:
explicit EventLogger(ostream& out) : out_(out) { }
~EventLogger() {
for (Hookups::iterator i = hookups_.begin(); i != hookups_.end(); ++i)
delete *i;
}
void Hookup(const string name, Pair::Channel* channel) {
hookups_.push_back(NewEventListenerHookup(channel, this,
&EventLogger::HandlePairEvent,
name));
}
void HandlePairEvent(const string& name, const TestEvent& event) {
const char* what_changed = NULL;
int new_value = 0;
Hookups::iterator dead;
switch (event.what_happened) {
case TestEvent::A_CHANGED:
what_changed = "A";
new_value = event.source->a();
break;
case TestEvent::B_CHANGED:
what_changed = "B";
new_value = event.source->b();
break;
case TestEvent::PAIR_BEING_DELETED:
out_ << name << " heard " << event.source->name() << " being deleted."
<< endl;
return;
default:
LOG(FATAL) << "Bad event.what_happened: " << event.what_happened;
break;
}
out_ << name << " heard " << event.source->name() << "'s " << what_changed
<< " change from "
<< event.old_value << " to " << new_value << endl;
}
typedef vector<EventListenerHookup*> Hookups;
Hookups hookups_;
ostream& out_;
};
const char golden_result[] = "Larry heard Sally's B change from 0 to 2\n"
"Larry heard Sally's A change from 1 to 3\n"
"Lewis heard Sam's B change from 0 to 5\n"
"Larry heard Sally's A change from 3 to 6\n"
"Larry heard Sally being deleted.\n";
TEST(EventSys, Basic) {
Pair sally("Sally"), sam("Sam");
sally.set_a(1);
stringstream log;
EventLogger logger(log);
logger.Hookup("Larry", sally.event_channel());
sally.set_b(2);
sally.set_a(3);
sam.set_a(4);
logger.Hookup("Lewis", sam.event_channel());
sam.set_b(5);
sally.set_a(6);
// Test that disconnect within callback doesn't deadlock.
TestEvent event = {&sally, TestEvent::PAIR_BEING_DELETED, 0 };
sally.event_channel()->NotifyListeners(event);
sally.set_a(7);
ASSERT_EQ(log.str(), golden_result);
}
// This goes pretty far beyond the normal use pattern, so don't use
// ThreadTester as an example of what to do.
class ThreadTester : public EventListener<TestEvent>,
public PlatformThread::Delegate {
public:
explicit ThreadTester(Pair* pair)
: pair_(pair), remove_event_(&remove_event_mutex_),
remove_event_bool_(false) {
pair_->event_channel()->AddListener(this);
}
~ThreadTester() {
pair_->event_channel()->RemoveListener(this);
for (size_t i = 0; i < threads_.size(); i++) {
PlatformThread::Join(threads_[i].thread);
}
}
struct ThreadInfo {
PlatformThreadHandle thread;
bool* completed;
};
struct ThreadArgs {
ConditionVariable* thread_running_cond;
Lock* thread_running_mutex;
bool thread_running;
bool completed;
};
void Go() {
Lock thread_running_mutex;
ConditionVariable thread_running_cond(&thread_running_mutex);
ThreadArgs args;
ThreadInfo info;
info.completed = false;
args.completed = info.completed;
args.thread_running_cond = &(thread_running_cond);
args.thread_running_mutex = &(thread_running_mutex);
args.thread_running = false;
args_ = args;
ASSERT_TRUE(PlatformThread::Create(0, this, &info.thread));
thread_running_mutex.Acquire();
while ((args_.thread_running) == false) {
thread_running_cond.Wait();
}
thread_running_mutex.Release();
threads_.push_back(info);
}
// PlatformThread::Delegate methods.
virtual void ThreadMain() {
// Make sure each thread gets a current MessageLoop in TLS.
// This test should use chrome threads for testing, but I'll leave it like
// this for the moment since it requires a big chunk of rewriting and I
// want the test passing while I checkpoint my CL. Technically speaking,
// there should be no functional difference.
MessageLoop message_loop;
args_.thread_running_mutex->Acquire();
args_.thread_running = true;
args_.thread_running_mutex->Release();
args_.thread_running_cond->Signal();
remove_event_mutex_.Acquire();
while (remove_event_bool_ == false) {
remove_event_.Wait();
}
remove_event_mutex_.Release();
// Normally, you'd just delete the hookup. This is very bad style, but
// necessary for the test.
pair_->event_channel()->RemoveListener(this);
args_.completed = true;
}
void HandleEvent(const TestEvent& event) {
remove_event_mutex_.Acquire();
remove_event_bool_ = true;
remove_event_mutex_.Release();
remove_event_.Broadcast();
PlatformThread::Sleep(1);
for (size_t i = 0; i < threads_.size(); i++) {
if (threads_[i].completed)
LOG(FATAL) << "A test thread exited too early.";
}
}
Pair* pair_;
ConditionVariable remove_event_;
Lock remove_event_mutex_;
bool remove_event_bool_;
vector<ThreadInfo> threads_;
ThreadArgs args_;
};
TEST(EventSys, Multithreaded) {
Pair sally("Sally");
ThreadTester a(&sally);
for (int i = 0; i < 3; ++i)
a.Go();
sally.set_b(99);
}
class HookupDeleter {
public:
void HandleEvent(const TestEvent& event) {
delete hookup_;
hookup_ = NULL;
}
EventListenerHookup* hookup_;
};
TEST(EventSys, InHandlerDeletion) {
Pair sally("Sally");
HookupDeleter deleter;
deleter.hookup_ = NewEventListenerHookup(sally.event_channel(),
&deleter,
&HookupDeleter::HandleEvent);
sally.set_a(1);
ASSERT_TRUE(NULL == deleter.hookup_);
}
} // namespace
<|endoftext|> |
<commit_before>/*
openfx-arena - https://github.com/olear/openfx-arena
Copyright (c) 2015, Ole-André Rodlie <olear@fxarena.net>
Copyright (c) 2015, FxArena DA <mail@fxarena.net>
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.
* Neither the name of FxArena DA nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
* 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 "Texture.h"
#include "ofxsMacros.h"
#include <Magick++.h>
#define kPluginName "Texture"
#define kPluginGrouping "Draw"
#define kPluginDescription "A simple texture generator. \n\nhttps://github.com/olear/openfx-arena"
#define kPluginIdentifier "net.fxarena.openfx.Texture"
#define kPluginVersionMajor 1
#define kPluginVersionMinor 0
#define kSupportsTiles 0
#define kSupportsMultiResolution 1
#define kSupportsRenderScale 1
#define kRenderThreadSafety eRenderInstanceSafe
#define kParamEffect "type"
#define kParamEffectLabel "Type"
#define kParamEffectHint "Texture type"
#define kParamEffectDefault 6
#define kParamSeed "seed"
#define kParamSeedLabel "Seed"
#define kParamSeedHint "Seed the random generator"
#define kParamSeedDefault 4321
using namespace OFX;
class TexturePlugin : public OFX::ImageEffect
{
public:
TexturePlugin(OfxImageEffectHandle handle);
virtual ~TexturePlugin();
virtual void render(const OFX::RenderArguments &args) OVERRIDE FINAL;
virtual bool getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) OVERRIDE FINAL;
private:
OFX::Clip *dstClip_;
OFX::ChoiceParam *effect_;
OFX::IntParam *seed_;
};
TexturePlugin::TexturePlugin(OfxImageEffectHandle handle)
: OFX::ImageEffect(handle)
, dstClip_(0)
{
Magick::InitializeMagick(NULL);
dstClip_ = fetchClip(kOfxImageEffectOutputClipName);
assert(dstClip_ && (dstClip_->getPixelComponents() == OFX::ePixelComponentRGBA || dstClip_->getPixelComponents() == OFX::ePixelComponentRGB));
effect_ = fetchChoiceParam(kParamEffect);
seed_ = fetchIntParam(kParamSeed);
assert(effect_ && seed_);
}
TexturePlugin::~TexturePlugin()
{
}
/* Override the render */
void TexturePlugin::render(const OFX::RenderArguments &args)
{
if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
if (!dstClip_) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
assert(dstClip_);
std::auto_ptr<OFX::Image> dstImg(dstClip_->fetchImage(args.time));
if (!dstImg.get()) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
if (dstImg->getRenderScale().x != args.renderScale.x ||
dstImg->getRenderScale().y != args.renderScale.y ||
dstImg->getField() != args.fieldToRender) {
setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties");
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
OFX::BitDepthEnum dstBitDepth = dstImg->getPixelDepth();
if (dstBitDepth != OFX::eBitDepthFloat && dstBitDepth != OFX::eBitDepthUShort && dstBitDepth != OFX::eBitDepthUByte) {
OFX::throwSuiteStatusException(kOfxStatErrFormat);
return;
}
OFX::PixelComponentEnum dstComponents = dstImg->getPixelComponents();
if ((dstComponents != OFX::ePixelComponentRGBA && dstComponents != OFX::ePixelComponentRGB && dstComponents != OFX::ePixelComponentAlpha)) {
OFX::throwSuiteStatusException(kOfxStatErrFormat);
return;
}
std::string channels;
switch (dstComponents) {
case ePixelComponentRGBA:
channels = "RGBA";
break;
case ePixelComponentRGB:
channels = "RGB";
break;
case ePixelComponentAlpha:
channels = "A";
break;
}
// are we in the image bounds
OfxRectI dstBounds = dstImg->getBounds();
OfxRectI dstRod = dstImg->getRegionOfDefinition();
if(args.renderWindow.x1 < dstBounds.x1 || args.renderWindow.x1 >= dstBounds.x2 || args.renderWindow.y1 < dstBounds.y1 || args.renderWindow.y1 >= dstBounds.y2 ||
args.renderWindow.x2 <= dstBounds.x1 || args.renderWindow.x2 > dstBounds.x2 || args.renderWindow.y2 <= dstBounds.y1 || args.renderWindow.y2 > dstBounds.y2) {
OFX::throwSuiteStatusException(kOfxStatErrValue);
return;
}
// Get params
int effect,seed;
effect_->getValueAtTime(args.time, effect);
seed_->getValueAtTime(args.time, seed);
// Generate empty image
int width = dstRod.x2-dstRod.x1;
int height = dstRod.y2-dstRod.y1;
Magick::Image image(Magick::Geometry(width,height),Magick::Color("rgba(0,0,0,0)"));
// set bg if rgb
if (channels=="RGB")
image.backgroundColor("black");
// Set seed
if (seed!=0)
Magick::SetRandomSeed(seed);
// generate background
switch (effect) {
case 0: // Plasma
image.read("plasma:");
break;
case 1: // Plasma
image.read("plasma:grey-grey");
break;
case 2: // Plasma
image.read("plasma:white-blue");
break;
case 3: // Plasma
image.read("plasma:green-yellow");
break;
case 4: // Plasma
image.read("plasma:red-blue");
break;
case 5: // Plasma
image.read("plasma:tomato-steelblue");
break;
case 6: // Plasma Fractal
image.read("plasma:fractal");
break;
case 7: // Noise
image.addNoise(Magick::GaussianNoise);
break;
}
// return image
switch (dstBitDepth) {
case eBitDepthUByte:
if (image.depth()>8)
image.depth(8);
image.write(0,0,width,height,channels,Magick::CharPixel,(float*)dstImg->getPixelData());
break;
case eBitDepthUShort:
if (image.depth()>16)
image.depth(16);
image.write(0,0,width,height,channels,Magick::ShortPixel,(float*)dstImg->getPixelData());
break;
case eBitDepthFloat:
image.write(0,0,width,height,channels,Magick::FloatPixel,(float*)dstImg->getPixelData());
break;
}
}
bool TexturePlugin::getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod)
{
if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return false;
}
rod.x1 = rod.y1 = kOfxFlagInfiniteMin;
rod.x2 = rod.y2 = kOfxFlagInfiniteMax;
return true;
}
mDeclarePluginFactory(TexturePluginFactory, {}, {});
/** @brief The basic describe function, passed a plugin descriptor */
void TexturePluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
// basic labels
desc.setLabel(kPluginName);
desc.setPluginGrouping(kPluginGrouping);
desc.setPluginDescription(kPluginDescription);
// add the supported contexts
desc.addSupportedContext(eContextGeneral);
desc.addSupportedContext(eContextGenerator);
// add supported pixel depths
desc.addSupportedBitDepth(eBitDepthUByte);
desc.addSupportedBitDepth(eBitDepthUShort);
desc.addSupportedBitDepth(eBitDepthFloat);
desc.setSupportsTiles(kSupportsTiles);
desc.setSupportsMultiResolution(kSupportsMultiResolution);
desc.setRenderThreadSafety(kRenderThreadSafety);
}
/** @brief The describe in context function, passed a plugin descriptor and a context */
void TexturePluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum /*context*/)
{
// there has to be an input clip, even for generators
ClipDescriptor* srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName);
srcClip->addSupportedComponent(ePixelComponentRGBA);
srcClip->addSupportedComponent(ePixelComponentRGB);
srcClip->setSupportsTiles(kSupportsTiles);
srcClip->setOptional(true);
// create the mandated output clip
ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName);
dstClip->addSupportedComponent(ePixelComponentRGBA);
dstClip->setSupportsTiles(kSupportsTiles);
// make some pages
PageParamDescriptor *page = desc.definePageParam(kPluginName);
{
ChoiceParamDescriptor *param = desc.defineChoiceParam(kParamEffect);
param->setLabel(kParamEffectLabel);
param->setHint(kParamEffectHint);
param->appendOption("Plasma");
param->appendOption("Plasma grey-grey");
param->appendOption("Plasma white-blue");
param->appendOption("Plasma green-yellow");
param->appendOption("Plasma red-blue");
param->appendOption("Plasma tomato-steelblue");
param->appendOption("Plasma Fractal");
param->appendOption("Noise");
param->setDefault(kParamEffectDefault);
param->setAnimates(true);
page->addChild(*param);
}
{
IntParamDescriptor *param = desc.defineIntParam(kParamSeed);
param->setLabel(kParamSeedLabel);
param->setHint(kParamSeedHint);
param->setRange(0, 10000);
param->setDisplayRange(0, 5000);
param->setDefault(kParamSeedDefault);
page->addChild(*param);
}
}
/** @brief The create instance function, the plugin must return an object derived from the \ref OFX::ImageEffect class */
ImageEffect* TexturePluginFactory::createInstance(OfxImageEffectHandle handle, ContextEnum /*context*/)
{
return new TexturePlugin(handle);
}
void getTexturePluginID(OFX::PluginFactoryArray &ids)
{
static TexturePluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);
ids.push_back(&p);
}
<commit_msg>Texture: added more generators, other minor<commit_after>/*
openfx-arena - https://github.com/olear/openfx-arena
Copyright (c) 2015, Ole-André Rodlie <olear@fxarena.net>
Copyright (c) 2015, FxArena DA <mail@fxarena.net>
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.
* Neither the name of FxArena DA nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
* 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 "Texture.h"
#include "ofxsMacros.h"
#include <Magick++.h>
#define kPluginName "Texture"
#define kPluginGrouping "Draw"
#define kPluginDescription "A simple texture generator. \n\nhttps://github.com/olear/openfx-arena"
#define kPluginIdentifier "net.fxarena.openfx.Texture"
#define kPluginVersionMajor 2
#define kPluginVersionMinor 0
#define kSupportsTiles 0
#define kSupportsMultiResolution 0
#define kSupportsRenderScale 1
#define kRenderThreadSafety eRenderInstanceSafe
#define kParamEffect "background"
#define kParamEffectLabel "Background"
#define kParamEffectHint "Background type"
#define kParamEffectDefault 6
#define kParamSeed "seed"
#define kParamSeedLabel "Seed"
#define kParamSeedHint "Seed the random generator"
#define kParamSeedDefault 4321
using namespace OFX;
class TexturePlugin : public OFX::ImageEffect
{
public:
TexturePlugin(OfxImageEffectHandle handle);
virtual ~TexturePlugin();
virtual void render(const OFX::RenderArguments &args) OVERRIDE FINAL;
virtual bool getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) OVERRIDE FINAL;
private:
OFX::Clip *dstClip_;
OFX::ChoiceParam *effect_;
OFX::IntParam *seed_;
};
TexturePlugin::TexturePlugin(OfxImageEffectHandle handle)
: OFX::ImageEffect(handle)
, dstClip_(0)
{
Magick::InitializeMagick(NULL);
dstClip_ = fetchClip(kOfxImageEffectOutputClipName);
assert(dstClip_ && (dstClip_->getPixelComponents() == OFX::ePixelComponentRGBA || dstClip_->getPixelComponents() == OFX::ePixelComponentRGB));
effect_ = fetchChoiceParam(kParamEffect);
seed_ = fetchIntParam(kParamSeed);
assert(effect_ && seed_);
}
TexturePlugin::~TexturePlugin()
{
}
/* Override the render */
void TexturePlugin::render(const OFX::RenderArguments &args)
{
if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
if (!dstClip_) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
assert(dstClip_);
std::auto_ptr<OFX::Image> dstImg(dstClip_->fetchImage(args.time));
if (!dstImg.get()) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
if (dstImg->getRenderScale().x != args.renderScale.x ||
dstImg->getRenderScale().y != args.renderScale.y ||
dstImg->getField() != args.fieldToRender) {
setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties");
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
OFX::BitDepthEnum dstBitDepth = dstImg->getPixelDepth();
if (dstBitDepth != OFX::eBitDepthFloat && dstBitDepth != OFX::eBitDepthUShort && dstBitDepth != OFX::eBitDepthUByte) {
OFX::throwSuiteStatusException(kOfxStatErrFormat);
return;
}
OFX::PixelComponentEnum dstComponents = dstImg->getPixelComponents();
if ((dstComponents != OFX::ePixelComponentRGBA && dstComponents != OFX::ePixelComponentRGB && dstComponents != OFX::ePixelComponentAlpha)) {
OFX::throwSuiteStatusException(kOfxStatErrFormat);
return;
}
// are we in the image bounds
OfxRectI dstBounds = dstImg->getBounds();
OfxRectI dstRod = dstImg->getRegionOfDefinition();
if(args.renderWindow.x1 < dstBounds.x1 || args.renderWindow.x1 >= dstBounds.x2 || args.renderWindow.y1 < dstBounds.y1 || args.renderWindow.y1 >= dstBounds.y2 ||
args.renderWindow.x2 <= dstBounds.x1 || args.renderWindow.x2 > dstBounds.x2 || args.renderWindow.y2 <= dstBounds.y1 || args.renderWindow.y2 > dstBounds.y2) {
OFX::throwSuiteStatusException(kOfxStatErrValue);
return;
}
// Get params
int effect,seed;
effect_->getValueAtTime(args.time, effect);
seed_->getValueAtTime(args.time, seed);
// Generate empty image
int width = dstRod.x2-dstRod.x1;
int height = dstRod.y2-dstRod.y1;
Magick::Image image(Magick::Geometry(width,height),Magick::Color("rgba(0,0,0,0)"));
// Set seed
if (seed!=0)
Magick::SetRandomSeed(seed);
// generate background
switch (effect) {
case 0: // Plasma
image.read("plasma:");
break;
case 1: // Plasma
image.read("plasma:grey-grey");
break;
case 2: // Plasma
image.read("plasma:white-blue");
break;
case 3: // Plasma
image.read("plasma:green-yellow");
break;
case 4: // Plasma
image.read("plasma:red-blue");
break;
case 5: // Plasma
image.read("plasma:tomato-steelblue");
break;
case 6: // Plasma Fractal
image.read("plasma:fractal");
break;
case 7: // GaussianNoise
image.addNoise(Magick::GaussianNoise);
break;
case 8: // ImpulseNoise
image.addNoise(Magick::ImpulseNoise);
break;
case 9: // LaplacianNoise
image.addNoise(Magick::LaplacianNoise);
break;
case 10: // checkerboard
image.read("pattern:checkerboard");
break;
case 11: // bricks
image.read("pattern:bricks");
break;
}
// return image
if (dstClip_ && dstClip_->isConnected()) {
switch (dstBitDepth) {
case eBitDepthUByte:
if (image.depth()>8)
image.depth(8);
image.write(0,0,width,height,"RGBA",Magick::CharPixel,(float*)dstImg->getPixelData());
break;
case eBitDepthUShort:
if (image.depth()>16)
image.depth(16);
image.write(0,0,width,height,"RGBA",Magick::ShortPixel,(float*)dstImg->getPixelData());
break;
case eBitDepthFloat:
image.write(0,0,width,height,"RGBA",Magick::FloatPixel,(float*)dstImg->getPixelData());
break;
}
}
}
bool TexturePlugin::getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod)
{
if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) {
OFX::throwSuiteStatusException(kOfxStatFailed);
return false;
}
rod.x1 = rod.y1 = kOfxFlagInfiniteMin;
rod.x2 = rod.y2 = kOfxFlagInfiniteMax;
return true;
}
mDeclarePluginFactory(TexturePluginFactory, {}, {});
/** @brief The basic describe function, passed a plugin descriptor */
void TexturePluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
// basic labels
desc.setLabel(kPluginName);
desc.setPluginGrouping(kPluginGrouping);
desc.setPluginDescription(kPluginDescription);
// add the supported contexts
desc.addSupportedContext(eContextGeneral);
desc.addSupportedContext(eContextGenerator);
// add supported pixel depths
/*desc.addSupportedBitDepth(eBitDepthUByte);
desc.addSupportedBitDepth(eBitDepthUShort);*/
desc.addSupportedBitDepth(eBitDepthFloat);
desc.setSupportsTiles(kSupportsTiles);
desc.setSupportsMultiResolution(kSupportsMultiResolution);
desc.setRenderThreadSafety(kRenderThreadSafety);
}
/** @brief The describe in context function, passed a plugin descriptor and a context */
void TexturePluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum /*context*/)
{
// there has to be an input clip, even for generators
ClipDescriptor* srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName);
srcClip->addSupportedComponent(ePixelComponentRGBA);
srcClip->setSupportsTiles(kSupportsTiles);
srcClip->setOptional(true);
// create the mandated output clip
ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName);
dstClip->addSupportedComponent(ePixelComponentRGBA);
dstClip->setSupportsTiles(kSupportsTiles);
// make some pages
PageParamDescriptor *page = desc.definePageParam(kPluginName);
{
ChoiceParamDescriptor *param = desc.defineChoiceParam(kParamEffect);
param->setLabel(kParamEffectLabel);
param->setHint(kParamEffectHint);
param->appendOption("Plasma");
param->appendOption("Plasma grey-grey");
param->appendOption("Plasma white-blue");
param->appendOption("Plasma green-yellow");
param->appendOption("Plasma red-blue");
param->appendOption("Plasma tomato-steelblue");
param->appendOption("Plasma Fractal");
param->appendOption("GaussianNoise");
param->appendOption("ImpulseNoise");
param->appendOption("LaplacianNoise");
param->appendOption("Checkerboard");
param->appendOption("Bricks");
param->setDefault(kParamEffectDefault);
param->setAnimates(true);
page->addChild(*param);
}
{
IntParamDescriptor *param = desc.defineIntParam(kParamSeed);
param->setLabel(kParamSeedLabel);
param->setHint(kParamSeedHint);
param->setRange(0, 10000);
param->setDisplayRange(0, 5000);
param->setDefault(kParamSeedDefault);
page->addChild(*param);
}
}
/** @brief The create instance function, the plugin must return an object derived from the \ref OFX::ImageEffect class */
ImageEffect* TexturePluginFactory::createInstance(OfxImageEffectHandle handle, ContextEnum /*context*/)
{
return new TexturePlugin(handle);
}
void getTexturePluginID(OFX::PluginFactoryArray &ids)
{
static TexturePluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);
ids.push_back(&p);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2012 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 "compilation_unit.h"
#include "compiled_method.h"
#include "file.h"
#include "instruction_set.h"
#include "ir_builder.h"
#include "logging.h"
#include "os.h"
#include "runtime_support_builder_arm.h"
#include "runtime_support_builder_x86.h"
#include <llvm/ADT/OwningPtr.h>
#include <llvm/ADT/StringSet.h>
#include <llvm/ADT/Triple.h>
#include <llvm/Analysis/CallGraph.h>
#include <llvm/Analysis/DebugInfo.h>
#include <llvm/Analysis/Dominators.h>
#include <llvm/Analysis/LoopInfo.h>
#include <llvm/Analysis/LoopPass.h>
#include <llvm/Analysis/RegionPass.h>
#include <llvm/Analysis/ScalarEvolution.h>
#include <llvm/Analysis/Verifier.h>
#include <llvm/Assembly/PrintModulePass.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/CallGraphSCCPass.h>
#include <llvm/CodeGen/MachineFrameInfo.h>
#include <llvm/CodeGen/MachineFunction.h>
#include <llvm/CodeGen/MachineFunctionPass.h>
#include <llvm/DerivedTypes.h>
#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/PassManager.h>
#include <llvm/Support/Debug.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Support/ManagedStatic.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/PassNameParser.h>
#include <llvm/Support/PluginLoader.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/Signals.h>
#include <llvm/Support/SystemUtils.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/ToolOutputFile.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/system_error.h>
#include <llvm/Target/TargetData.h>
#include <llvm/Target/TargetLibraryInfo.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
#include <llvm/Transforms/Scalar.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string>
namespace {
class UpdateFrameSizePass : public llvm::MachineFunctionPass {
public:
static char ID;
UpdateFrameSizePass() : llvm::MachineFunctionPass(ID), cunit_(NULL) {
LOG(FATAL) << "Unexpected instantiation of UpdateFrameSizePass";
// NOTE: We have to declare this constructor for llvm::RegisterPass, but
// this constructor won't work because we have no information on
// CompilationUnit. Thus, we should place a LOG(FATAL) here.
}
UpdateFrameSizePass(art::compiler_llvm::CompilationUnit* cunit)
: llvm::MachineFunctionPass(ID), cunit_(cunit) {
}
virtual bool runOnMachineFunction(llvm::MachineFunction &MF) {
cunit_->UpdateFrameSizeInBytes(MF.getFunction(),
MF.getFrameInfo()->getStackSize());
return false;
}
private:
art::compiler_llvm::CompilationUnit* cunit_;
};
char UpdateFrameSizePass::ID = 0;
llvm::RegisterPass<UpdateFrameSizePass> reg_update_frame_size_pass_(
"update-frame-size", "Update frame size pass", false, false);
// TODO: We may need something to manage these passes.
// TODO: We need high-level IR to analysis and do this at the IRBuilder level.
class AddSuspendCheckToLoopLatchPass : public llvm::LoopPass {
public:
static char ID;
AddSuspendCheckToLoopLatchPass() : llvm::LoopPass(ID), irb_(NULL) {
LOG(FATAL) << "Unexpected instantiation of AddSuspendCheckToLoopLatchPass";
// NOTE: We have to declare this constructor for llvm::RegisterPass, but
// this constructor won't work because we have no information on
// IRBuilder. Thus, we should place a LOG(FATAL) here.
}
AddSuspendCheckToLoopLatchPass(art::compiler_llvm::IRBuilder* irb)
: llvm::LoopPass(ID), irb_(irb) {
}
virtual void getAnalysisUsage(llvm::AnalysisUsage &AU) const {
AU.addRequiredID(llvm::LoopSimplifyID);
AU.addPreserved<llvm::DominatorTree>();
AU.addPreserved<llvm::LoopInfo>();
AU.addPreservedID(llvm::LoopSimplifyID);
AU.addPreserved<llvm::ScalarEvolution>();
AU.addPreservedID(llvm::BreakCriticalEdgesID);
}
virtual bool runOnLoop(llvm::Loop *loop, llvm::LPPassManager &lpm) {
CHECK_EQ(loop->getNumBackEdges(), 1U) << "Loop must be simplified!";
llvm::BasicBlock* bb = loop->getLoopLatch();
CHECK_NE(bb, static_cast<void*>(NULL)) << "A single loop latch must exist.";
irb_->SetInsertPoint(bb->getTerminator());
using art::compiler_llvm::runtime_support::TestSuspend;
llvm::Value* runtime_func = irb_->GetRuntime(TestSuspend);
irb_->CreateCall(runtime_func, irb_->getJNull());
return true;
}
private:
art::compiler_llvm::IRBuilder* irb_;
};
char AddSuspendCheckToLoopLatchPass::ID = 0;
llvm::RegisterPass<AddSuspendCheckToLoopLatchPass> reg_add_suspend_check_to_loop_latch_pass_(
"add-suspend-check-to-loop-latch", "Add suspend check to loop latch pass", false, false);
} // end anonymous namespace
namespace art {
namespace compiler_llvm {
llvm::Module* makeLLVMModuleContents(llvm::Module* module);
CompilationUnit::CompilationUnit(InstructionSet insn_set, size_t elf_idx)
: cunit_lock_("compilation_unit_lock"), insn_set_(insn_set), elf_idx_(elf_idx),
context_(new llvm::LLVMContext()), compiled_methods_map_(new CompiledMethodMap()),
mem_usage_(0), num_elf_funcs_(0) {
// Create the module and include the runtime function declaration
module_ = new llvm::Module("art", *context_);
makeLLVMModuleContents(module_);
// Create IRBuilder
irb_.reset(new IRBuilder(*context_, *module_));
// We always need a switch case, so just use a normal function.
switch(insn_set_) {
default:
runtime_support_.reset(new RuntimeSupportBuilder(*context_, *module_, *irb_));
break;
case kArm:
case kThumb2:
runtime_support_.reset(new RuntimeSupportBuilderARM(*context_, *module_, *irb_));
break;
case kX86:
runtime_support_.reset(new RuntimeSupportBuilderX86(*context_, *module_, *irb_));
break;
}
runtime_support_->OptimizeRuntimeSupport();
irb_->SetRuntimeSupport(runtime_support_.get());
}
CompilationUnit::~CompilationUnit() {
}
bool CompilationUnit::Materialize(size_t thread_count) {
MutexLock GUARD(cunit_lock_);
// Materialize the bitcode to elf_image_
llvm::raw_string_ostream str_os(elf_image_);
bool success = MaterializeToFile(str_os);
LOG(INFO) << "Compilation Unit: " << elf_idx_ << (success ? " (done)" : " (failed)");
// Free the resources
context_.reset(NULL);
irb_.reset(NULL);
module_ = NULL;
runtime_support_.reset(NULL);
compiled_methods_map_.reset(NULL);
return success;
}
void CompilationUnit::RegisterCompiledMethod(const llvm::Function* func,
CompiledMethod* compiled_method) {
MutexLock GUARD(cunit_lock_);
compiled_methods_map_->Put(func, compiled_method);
}
void CompilationUnit::UpdateFrameSizeInBytes(const llvm::Function* func,
size_t frame_size_in_bytes) {
MutexLock GUARD(cunit_lock_);
SafeMap<const llvm::Function*, CompiledMethod*>::iterator iter =
compiled_methods_map_->find(func);
if (iter != compiled_methods_map_->end()) {
CompiledMethod* compiled_method = iter->second;
compiled_method->SetFrameSizeInBytes(frame_size_in_bytes);
if (frame_size_in_bytes > 1728u) {
LOG(WARNING) << "Huge frame size: " << frame_size_in_bytes
<< " elf_idx=" << compiled_method->GetElfIndex()
<< " elf_func_idx=" << compiled_method->GetElfFuncIndex();
}
}
}
bool CompilationUnit::MaterializeToFile(llvm::raw_ostream& out_stream) {
// Lookup the LLVM target
char const* target_triple = NULL;
char const* target_attr = NULL;
switch (insn_set_) {
case kThumb2:
target_triple = "thumb-none-linux-gnueabi";
target_attr = "+thumb2,+neon,+neonfp,+vfp3";
break;
case kArm:
target_triple = "armv7-none-linux-gnueabi";
// TODO: Fix for Xoom.
target_attr = "+v7,+neon,+neonfp,+vfp3";
break;
case kX86:
target_triple = "i386-pc-linux-gnu";
target_attr = "";
break;
case kMips:
target_triple = "mipsel-unknown-linux";
target_attr = "mips32r2";
break;
default:
LOG(FATAL) << "Unknown instruction set: " << insn_set_;
}
std::string errmsg;
llvm::Target const* target =
llvm::TargetRegistry::lookupTarget(target_triple, errmsg);
CHECK(target != NULL) << errmsg;
// Target options
llvm::TargetOptions target_options;
target_options.FloatABIType = llvm::FloatABI::Soft;
target_options.NoFramePointerElim = true;
target_options.NoFramePointerElimNonLeaf = true;
target_options.UseSoftFloat = false;
target_options.EnableFastISel = false;
// Create the llvm::TargetMachine
llvm::OwningPtr<llvm::TargetMachine> target_machine(
target->createTargetMachine(target_triple, "", target_attr, target_options,
llvm::Reloc::Static, llvm::CodeModel::Small,
llvm::CodeGenOpt::Less));
CHECK(target_machine.get() != NULL) << "Failed to create target machine";
// Add target data
llvm::TargetData const* target_data = target_machine->getTargetData();
// PassManager for code generation passes
llvm::PassManager pm;
pm.add(new llvm::TargetData(*target_data));
// FunctionPassManager for optimization pass
llvm::FunctionPassManager fpm(module_);
fpm.add(new llvm::TargetData(*target_data));
if (bitcode_filename_.empty()) {
// If we don't need write the bitcode to file, add the AddSuspendCheckToLoopLatchPass to the
// regular FunctionPass.
fpm.add(new ::AddSuspendCheckToLoopLatchPass(irb_.get()));
} else {
// Run AddSuspendCheckToLoopLatchPass before we write the bitcode to file.
llvm::FunctionPassManager fpm2(module_);
fpm2.add(new ::AddSuspendCheckToLoopLatchPass(irb_.get()));
fpm2.doInitialization();
for (llvm::Module::iterator F = module_->begin(), E = module_->end();
F != E; ++F) {
fpm2.run(*F);
}
fpm2.doFinalization();
// Write bitcode to file
std::string errmsg;
llvm::OwningPtr<llvm::tool_output_file> out_file(
new llvm::tool_output_file(bitcode_filename_.c_str(), errmsg,
llvm::raw_fd_ostream::F_Binary));
if (!errmsg.empty()) {
LOG(ERROR) << "Failed to create bitcode output file: " << errmsg;
return false;
}
llvm::WriteBitcodeToFile(module_, out_file->os());
out_file->keep();
}
// Add optimization pass
llvm::PassManagerBuilder pm_builder;
//pm_builder.Inliner = llvm::createFunctionInliningPass();
pm_builder.Inliner = llvm::createAlwaysInlinerPass();
//pm_builder.Inliner = llvm::createPartialInliningPass();
pm_builder.OptLevel = 3;
pm_builder.DisableSimplifyLibCalls = 1;
pm_builder.DisableUnitAtATime = 1;
pm_builder.populateFunctionPassManager(fpm);
pm_builder.populateModulePassManager(pm);
pm.add(llvm::createStripDeadPrototypesPass());
// Add passes to emit ELF image
{
llvm::formatted_raw_ostream formatted_os(out_stream, false);
// Ask the target to add backend passes as necessary.
if (target_machine->addPassesToEmitFile(pm,
formatted_os,
llvm::TargetMachine::CGFT_ObjectFile,
true)) {
LOG(FATAL) << "Unable to generate ELF for this target";
return false;
}
// FIXME: Unable to run the UpdateFrameSizePass pass since it tries to
// update the value reside in the different address space.
// Add pass to update the frame_size_in_bytes_
//pm.add(new ::UpdateFrameSizePass(this));
// Run the per-function optimization
fpm.doInitialization();
for (llvm::Module::iterator F = module_->begin(), E = module_->end();
F != E; ++F) {
fpm.run(*F);
}
fpm.doFinalization();
// Run the code generation passes
pm.run(*module_);
}
return true;
}
} // namespace compiler_llvm
} // namespace art
<commit_msg>am dac5eb2d: Optimization experiment.<commit_after>/*
* Copyright (C) 2012 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 "compilation_unit.h"
#include "compiled_method.h"
#include "file.h"
#include "instruction_set.h"
#include "ir_builder.h"
#include "logging.h"
#include "os.h"
#include "runtime_support_builder_arm.h"
#include "runtime_support_builder_x86.h"
#include <llvm/ADT/OwningPtr.h>
#include <llvm/ADT/StringSet.h>
#include <llvm/ADT/Triple.h>
#include <llvm/Analysis/CallGraph.h>
#include <llvm/Analysis/DebugInfo.h>
#include <llvm/Analysis/Dominators.h>
#include <llvm/Analysis/LoopInfo.h>
#include <llvm/Analysis/LoopPass.h>
#include <llvm/Analysis/RegionPass.h>
#include <llvm/Analysis/ScalarEvolution.h>
#include <llvm/Analysis/Verifier.h>
#include <llvm/Assembly/PrintModulePass.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/CallGraphSCCPass.h>
#include <llvm/CodeGen/MachineFrameInfo.h>
#include <llvm/CodeGen/MachineFunction.h>
#include <llvm/CodeGen/MachineFunctionPass.h>
#include <llvm/DerivedTypes.h>
#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/PassManager.h>
#include <llvm/Support/Debug.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Support/ManagedStatic.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/PassNameParser.h>
#include <llvm/Support/PluginLoader.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/Signals.h>
#include <llvm/Support/SystemUtils.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/ToolOutputFile.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/system_error.h>
#include <llvm/Target/TargetData.h>
#include <llvm/Target/TargetLibraryInfo.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
#include <llvm/Transforms/Scalar.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string>
namespace {
class UpdateFrameSizePass : public llvm::MachineFunctionPass {
public:
static char ID;
UpdateFrameSizePass() : llvm::MachineFunctionPass(ID), cunit_(NULL) {
LOG(FATAL) << "Unexpected instantiation of UpdateFrameSizePass";
// NOTE: We have to declare this constructor for llvm::RegisterPass, but
// this constructor won't work because we have no information on
// CompilationUnit. Thus, we should place a LOG(FATAL) here.
}
UpdateFrameSizePass(art::compiler_llvm::CompilationUnit* cunit)
: llvm::MachineFunctionPass(ID), cunit_(cunit) {
}
virtual bool runOnMachineFunction(llvm::MachineFunction &MF) {
cunit_->UpdateFrameSizeInBytes(MF.getFunction(),
MF.getFrameInfo()->getStackSize());
return false;
}
private:
art::compiler_llvm::CompilationUnit* cunit_;
};
char UpdateFrameSizePass::ID = 0;
llvm::RegisterPass<UpdateFrameSizePass> reg_update_frame_size_pass_(
"update-frame-size", "Update frame size pass", false, false);
// TODO: We may need something to manage these passes.
// TODO: We need high-level IR to analysis and do this at the IRBuilder level.
class AddSuspendCheckToLoopLatchPass : public llvm::LoopPass {
public:
static char ID;
AddSuspendCheckToLoopLatchPass() : llvm::LoopPass(ID), irb_(NULL) {
LOG(FATAL) << "Unexpected instantiation of AddSuspendCheckToLoopLatchPass";
// NOTE: We have to declare this constructor for llvm::RegisterPass, but
// this constructor won't work because we have no information on
// IRBuilder. Thus, we should place a LOG(FATAL) here.
}
AddSuspendCheckToLoopLatchPass(art::compiler_llvm::IRBuilder* irb)
: llvm::LoopPass(ID), irb_(irb) {
}
virtual void getAnalysisUsage(llvm::AnalysisUsage &AU) const {
AU.addRequiredID(llvm::LoopSimplifyID);
AU.addPreserved<llvm::DominatorTree>();
AU.addPreserved<llvm::LoopInfo>();
AU.addPreservedID(llvm::LoopSimplifyID);
AU.addPreserved<llvm::ScalarEvolution>();
AU.addPreservedID(llvm::BreakCriticalEdgesID);
}
virtual bool runOnLoop(llvm::Loop *loop, llvm::LPPassManager &lpm) {
CHECK_EQ(loop->getNumBackEdges(), 1U) << "Loop must be simplified!";
llvm::BasicBlock* bb = loop->getLoopLatch();
CHECK_NE(bb, static_cast<void*>(NULL)) << "A single loop latch must exist.";
irb_->SetInsertPoint(bb->getTerminator());
using art::compiler_llvm::runtime_support::TestSuspend;
llvm::Value* runtime_func = irb_->GetRuntime(TestSuspend);
irb_->CreateCall(runtime_func, irb_->getJNull());
return true;
}
private:
art::compiler_llvm::IRBuilder* irb_;
};
char AddSuspendCheckToLoopLatchPass::ID = 0;
llvm::RegisterPass<AddSuspendCheckToLoopLatchPass> reg_add_suspend_check_to_loop_latch_pass_(
"add-suspend-check-to-loop-latch", "Add suspend check to loop latch pass", false, false);
} // end anonymous namespace
namespace art {
namespace compiler_llvm {
llvm::Module* makeLLVMModuleContents(llvm::Module* module);
CompilationUnit::CompilationUnit(InstructionSet insn_set, size_t elf_idx)
: cunit_lock_("compilation_unit_lock"), insn_set_(insn_set), elf_idx_(elf_idx),
context_(new llvm::LLVMContext()), compiled_methods_map_(new CompiledMethodMap()),
mem_usage_(0), num_elf_funcs_(0) {
// Create the module and include the runtime function declaration
module_ = new llvm::Module("art", *context_);
makeLLVMModuleContents(module_);
// Create IRBuilder
irb_.reset(new IRBuilder(*context_, *module_));
// We always need a switch case, so just use a normal function.
switch(insn_set_) {
default:
runtime_support_.reset(new RuntimeSupportBuilder(*context_, *module_, *irb_));
break;
case kArm:
case kThumb2:
runtime_support_.reset(new RuntimeSupportBuilderARM(*context_, *module_, *irb_));
break;
case kX86:
runtime_support_.reset(new RuntimeSupportBuilderX86(*context_, *module_, *irb_));
break;
}
runtime_support_->OptimizeRuntimeSupport();
irb_->SetRuntimeSupport(runtime_support_.get());
}
CompilationUnit::~CompilationUnit() {
}
bool CompilationUnit::Materialize(size_t thread_count) {
MutexLock GUARD(cunit_lock_);
// Materialize the bitcode to elf_image_
llvm::raw_string_ostream str_os(elf_image_);
bool success = MaterializeToFile(str_os);
LOG(INFO) << "Compilation Unit: " << elf_idx_ << (success ? " (done)" : " (failed)");
// Free the resources
context_.reset(NULL);
irb_.reset(NULL);
module_ = NULL;
runtime_support_.reset(NULL);
compiled_methods_map_.reset(NULL);
return success;
}
void CompilationUnit::RegisterCompiledMethod(const llvm::Function* func,
CompiledMethod* compiled_method) {
MutexLock GUARD(cunit_lock_);
compiled_methods_map_->Put(func, compiled_method);
}
void CompilationUnit::UpdateFrameSizeInBytes(const llvm::Function* func,
size_t frame_size_in_bytes) {
MutexLock GUARD(cunit_lock_);
SafeMap<const llvm::Function*, CompiledMethod*>::iterator iter =
compiled_methods_map_->find(func);
if (iter != compiled_methods_map_->end()) {
CompiledMethod* compiled_method = iter->second;
compiled_method->SetFrameSizeInBytes(frame_size_in_bytes);
if (frame_size_in_bytes > 1728u) {
LOG(WARNING) << "Huge frame size: " << frame_size_in_bytes
<< " elf_idx=" << compiled_method->GetElfIndex()
<< " elf_func_idx=" << compiled_method->GetElfFuncIndex();
}
}
}
bool CompilationUnit::MaterializeToFile(llvm::raw_ostream& out_stream) {
// Lookup the LLVM target
char const* target_triple = NULL;
char const* target_attr = NULL;
switch (insn_set_) {
case kThumb2:
target_triple = "thumb-none-linux-gnueabi";
target_attr = "+thumb2,+neon,+neonfp,+vfp3";
break;
case kArm:
target_triple = "armv7-none-linux-gnueabi";
// TODO: Fix for Xoom.
target_attr = "+v7,+neon,+neonfp,+vfp3";
break;
case kX86:
target_triple = "i386-pc-linux-gnu";
target_attr = "";
break;
case kMips:
target_triple = "mipsel-unknown-linux";
target_attr = "mips32r2";
break;
default:
LOG(FATAL) << "Unknown instruction set: " << insn_set_;
}
std::string errmsg;
llvm::Target const* target =
llvm::TargetRegistry::lookupTarget(target_triple, errmsg);
CHECK(target != NULL) << errmsg;
// Target options
llvm::TargetOptions target_options;
target_options.FloatABIType = llvm::FloatABI::Soft;
target_options.NoFramePointerElim = true;
target_options.NoFramePointerElimNonLeaf = true;
target_options.UseSoftFloat = false;
target_options.EnableFastISel = false;
// Create the llvm::TargetMachine
llvm::OwningPtr<llvm::TargetMachine> target_machine(
target->createTargetMachine(target_triple, "", target_attr, target_options,
llvm::Reloc::Static, llvm::CodeModel::Small,
llvm::CodeGenOpt::Aggressive));
CHECK(target_machine.get() != NULL) << "Failed to create target machine";
// Add target data
llvm::TargetData const* target_data = target_machine->getTargetData();
// PassManager for code generation passes
llvm::PassManager pm;
pm.add(new llvm::TargetData(*target_data));
// FunctionPassManager for optimization pass
llvm::FunctionPassManager fpm(module_);
fpm.add(new llvm::TargetData(*target_data));
if (bitcode_filename_.empty()) {
// If we don't need write the bitcode to file, add the AddSuspendCheckToLoopLatchPass to the
// regular FunctionPass.
fpm.add(new ::AddSuspendCheckToLoopLatchPass(irb_.get()));
} else {
// Run AddSuspendCheckToLoopLatchPass before we write the bitcode to file.
llvm::FunctionPassManager fpm2(module_);
fpm2.add(new ::AddSuspendCheckToLoopLatchPass(irb_.get()));
fpm2.doInitialization();
for (llvm::Module::iterator F = module_->begin(), E = module_->end();
F != E; ++F) {
fpm2.run(*F);
}
fpm2.doFinalization();
// Write bitcode to file
std::string errmsg;
llvm::OwningPtr<llvm::tool_output_file> out_file(
new llvm::tool_output_file(bitcode_filename_.c_str(), errmsg,
llvm::raw_fd_ostream::F_Binary));
if (!errmsg.empty()) {
LOG(ERROR) << "Failed to create bitcode output file: " << errmsg;
return false;
}
llvm::WriteBitcodeToFile(module_, out_file->os());
out_file->keep();
}
// Add optimization pass
llvm::PassManagerBuilder pm_builder;
//pm_builder.Inliner = llvm::createFunctionInliningPass();
pm_builder.Inliner = llvm::createAlwaysInlinerPass();
//pm_builder.Inliner = llvm::createPartialInliningPass();
pm_builder.OptLevel = 3;
pm_builder.DisableSimplifyLibCalls = 1;
pm_builder.DisableUnitAtATime = 1;
pm_builder.populateFunctionPassManager(fpm);
pm_builder.populateModulePassManager(pm);
pm.add(llvm::createStripDeadPrototypesPass());
// Add passes to emit ELF image
{
llvm::formatted_raw_ostream formatted_os(out_stream, false);
// Ask the target to add backend passes as necessary.
if (target_machine->addPassesToEmitFile(pm,
formatted_os,
llvm::TargetMachine::CGFT_ObjectFile,
true)) {
LOG(FATAL) << "Unable to generate ELF for this target";
return false;
}
// FIXME: Unable to run the UpdateFrameSizePass pass since it tries to
// update the value reside in the different address space.
// Add pass to update the frame_size_in_bytes_
//pm.add(new ::UpdateFrameSizePass(this));
// Run the per-function optimization
fpm.doInitialization();
for (llvm::Module::iterator F = module_->begin(), E = module_->end();
F != E; ++F) {
fpm.run(*F);
}
fpm.doFinalization();
// Run the code generation passes
pm.run(*module_);
}
return true;
}
} // namespace compiler_llvm
} // namespace art
<|endoftext|> |
<commit_before>
#include "itkImageFileReader.h"
#include "itkImage.h"
#include "itkAndImageFilter.h"
#include "itkImageRegionConstIterator.h"
#include "itkThresholdLabelerImageFilter.h"
#include "itkNumericTraits.h"
#include <map>
#include <iostream>
#include <string>
int main(int argc, char ** argv)
{
std::cout << "Warning: this program assumes 3d images with a pixeltype\
convertible to shorts!\n" << std::endl;
const unsigned int Dimension = 3;
typedef short PixelType;
typedef itk::Image<PixelType, Dimension> ImageType;
typedef ImageType::Pointer ImagePointer;
typedef itk::ImageFileReader<ImageType> ImageReaderType;
typedef ImageReaderType::Pointer ImageReaderPointer;
typedef itk::AndImageFilter<ImageType, ImageType, ImageType> AndFilterType;
typedef AndFilterType::Pointer AndFilterPointer;
typedef itk::ImageRegionConstIterator<ImageType> IteratorType;
typedef itk::ThresholdLabelerImageFilter<ImageType, ImageType> ThresholdFilterType;
typedef ThresholdFilterType::Pointer ThresholdFilterPointer;
typedef ThresholdFilterType::ThresholdVector ThresholdVectorType;
typedef std::map<std::string, std::string> ArgMapType;
ArgMapType argmap;
std::cout << "ComputeOverlap called with the following arguments:" << std::endl;
for (unsigned int i=1; i<argc; i+=2 )
{
std::string key=argv[i];
std::string value="";
if ( (i+1) < argc )
{
value=argv[i+1];
}
std::cout << " " << key << " " << value << std::endl;
argmap[key] = value;
}
std::cout << std::endl;
/** HELP */
if (argmap.count("-help") |
argmap.count("--help") |
argmap.count("-h") |
argmap.count("--h") |
argmap.count("-?") |
!argmap.count("-im1") |
!argmap.count("-im2") )
{
std::cerr << "Compute the overlap of two binary images. Masks of the valid region\n"
<< "in the images (for example an US beam) are also taken into account.\n"
<< "If the image are not binary, you must specify a threshold value.\n";
std::cerr << "\nUsage:\n";
std::cerr << "computeoverlap\n"
<< "\t-im1 <image> -im2 <image>\n"
<< "\t[ -mask1 <mask-image> ] [ -mask2 <mask-image> ]\n"
<< "\t[ -t1 <threshold value> ] [ -t2 <threshold value> ]\n";
std::cerr << "\nThe results is computed as:\n";
std::cerr << " 2 * L1( (im1 AND mask2) AND (im2 AND mask1) )\n";
std::cerr << "----------------------------------------------\n";
std::cerr << " L1(im1 AND mask2) + L1(im2 AND mask1) \n" << std::endl;
return 1;
}
/**
* Setup pipeline
*/
AndFilterPointer finalANDFilter = AndFilterType::New();
ImageReaderPointer imreader1 = ImageReaderType::New();
imreader1->SetFileName( argmap["-im1"].c_str() );
ImageReaderPointer imreader2 = ImageReaderType::New();
imreader2->SetFileName( argmap["-im2"].c_str() );
ImagePointer im1=0;
ImagePointer im2=0;
ThresholdFilterPointer im1Thresholder = 0;
ThresholdFilterPointer im2Thresholder = 0;
ThresholdVectorType im1thresholdvector(2);
ThresholdVectorType im2thresholdvector(2);
if ( argmap.count("-t1") )
{
im1Thresholder = ThresholdFilterType::New();
im1thresholdvector[0] = atoi( argmap[ "-t1" ].c_str() );
im1thresholdvector[1] = itk::NumericTraits<PixelType>::max();
im1Thresholder->SetThresholds(im1thresholdvector);
im1Thresholder->SetInput( imreader1->GetOutput() );
im1 = im1Thresholder->GetOutput();
}
else
{
im1 = imreader1->GetOutput();
}
if ( argmap.count("-t2") )
{
im2Thresholder = ThresholdFilterType::New();
im2thresholdvector[0] = atoi( argmap[ "-t2" ].c_str() );
im2thresholdvector[1] = itk::NumericTraits<PixelType>::max();
im2Thresholder->SetThresholds(im2thresholdvector);
im2Thresholder->SetInput( imreader2->GetOutput() );
im2 = im2Thresholder->GetOutput();
}
else
{
im2 = imreader2->GetOutput();
}
ImageReaderPointer maskreader1 = 0;
ImageReaderPointer maskreader2 = 0;
AndFilterPointer im2ANDmask1Filter = 0;
AndFilterPointer im1ANDmask2Filter = 0;
if ( argmap.count("-mask1") )
{
maskreader1 = ImageReaderType::New();
maskreader1->SetFileName( argmap["-mask1"].c_str() );
im2ANDmask1Filter = AndFilterType::New();
im2ANDmask1Filter->SetInput1( im2 );
im2ANDmask1Filter->SetInput2( maskreader1->GetOutput() );
finalANDFilter->SetInput1( im2ANDmask1Filter->GetOutput() );
}
else
{
finalANDFilter->SetInput1( im2 );
}
if ( argmap.count("-mask2") )
{
maskreader2 = ImageReaderType::New();
maskreader2->SetFileName( argmap["-mask2"].c_str() );
im1ANDmask2Filter = AndFilterType::New();
im1ANDmask2Filter->SetInput1( im1 );
im1ANDmask2Filter->SetInput2( maskreader2->GetOutput() );
finalANDFilter->SetInput2( im1ANDmask2Filter->GetOutput() );
}
else
{
finalANDFilter->SetInput2( im1 );
}
/** UPDATE! */
try
{
finalANDFilter->Update();
}
catch (itk::ExceptionObject & err)
{
std::cerr << err << std::endl;
throw err;
}
/** Now calculate the L1-norm. */
IteratorType iteratorA( finalANDFilter->GetInput(1),
finalANDFilter->GetInput(1)->GetLargestPossibleRegion() );
IteratorType iteratorB( finalANDFilter->GetInput(0),
finalANDFilter->GetInput(0)->GetLargestPossibleRegion() );
IteratorType iteratorC( finalANDFilter->GetOutput(),
finalANDFilter->GetOutput()->GetLargestPossibleRegion() );
long long sumA=0;
for (iteratorA.GoToBegin(); !iteratorA.IsAtEnd(); ++iteratorA)
{
if ( iteratorA.Value() )
{
++sumA;
}
}
std::cout << "Size of first object: " << sumA << std::endl;
long long sumB=0;
for (iteratorB.GoToBegin(); !iteratorB.IsAtEnd(); ++iteratorB)
{
if ( iteratorB.Value() )
{
++sumB;
}
}
std::cout << "Size of second object: " << sumB << std::endl;
long long sumC=0;
for (iteratorC.GoToBegin(); !iteratorC.IsAtEnd(); ++iteratorC)
{
if ( iteratorC.Value() )
{
++sumC;
}
}
std::cout << "Size of cross-section of both objects: " << sumC << std::endl;
double overlap;
if ((sumA+sumB) == 0)
{
overlap=0;
}
else
{
overlap = static_cast<double>( 2 * sumC)/static_cast<double>(sumA + sumB);
}
/** Format the output */
std::cout << std::fixed << std::showpoint;
std::cout << "Overlap: " << overlap << std::endl;
return 0;
}
<commit_msg>------------------------------------------------------------ MS:<commit_after>/** Include the right headers. */
#include "itkImageFileReader.h"
#include "itkImage.h"
#include "itkAndImageFilter.h"
#include "itkImageRegionConstIterator.h"
#include "itkThresholdLabelerImageFilter.h"
#include "itkNumericTraits.h"
#include <map>
#include <iostream>
#include <string>
/** \todo explain rationale.
*
*
*/
int main( int argc, char ** argv )
{
/** Warning. */
std::cout << "Warning: this program assumes 3d images with a pixeltype convertible to shorts!\n" << std::endl;
/** Define image type. */
const unsigned int Dimension = 3;
typedef short PixelType;
/** Some typedef's. */
typedef itk::Image<PixelType, Dimension> ImageType;
typedef ImageType::Pointer ImagePointer;
typedef itk::ImageFileReader<ImageType> ImageReaderType;
typedef ImageReaderType::Pointer ImageReaderPointer;
typedef itk::AndImageFilter<
ImageType, ImageType, ImageType> AndFilterType;
typedef AndFilterType::Pointer AndFilterPointer;
typedef itk::ImageRegionConstIterator<ImageType> IteratorType;
typedef itk::ThresholdLabelerImageFilter<
ImageType, ImageType> ThresholdFilterType;
typedef ThresholdFilterType::Pointer ThresholdFilterPointer;
typedef ThresholdFilterType::ThresholdVector ThresholdVectorType;
typedef std::map<std::string, std::string> ArgMapType;
/** Store the command line arguments. */
ArgMapType argmap;
/** Get and print the command line arguments. */
std::cout << "ComputeOverlap called with the following arguments:" << std::endl;
for ( unsigned int i = 1; i < argc; i += 2 )
{
std::string key = argv[ i ];
std::string value = "";
if ( ( i + 1 ) < argc )
{
value = argv[ i + 1 ];
}
std::cout << " " << key << "\t" << value << std::endl;
argmap[ key ] = value;
}
std::cout << std::endl;
/** Print HELP if needed. */
if (argmap.count("-help") |
argmap.count("--help") |
argmap.count("-h") |
argmap.count("--h") |
argmap.count("-?") |
!argmap.count("-im1") |
!argmap.count("-im2") )
{
std::cerr << "Compute the overlap of two binary images. Masks of the valid region\n"
<< "in the images (for example an US beam) are also taken into account.\n"
<< "If the image are not binary, you must specify a threshold value.\n";
std::cerr << "\nUsage:\n";
std::cerr << "computeoverlap\n"
<< "\t-im1 <image> -im2 <image>\n"
<< "\t[ -mask1 <mask-image> ] [ -mask2 <mask-image> ]\n"
<< "\t[ -t1 <threshold value> ] [ -t2 <threshold value> ]\n";
std::cerr << "\nThe results is computed as:\n";
std::cerr << " 2 * L1( (im1 AND mask2) AND (im2 AND mask1) )\n";
std::cerr << "----------------------------------------------\n";
std::cerr << " L1(im1 AND mask2) + L1(im2 AND mask1) \n" << std::endl;
return 1;
}
/**
* Setup pipeline
*/
/** Create readers and an AND filter. */
ImageReaderPointer imreader1 = ImageReaderType::New();
imreader1->SetFileName( argmap["-im1"].c_str() );
ImageReaderPointer imreader2 = ImageReaderType::New();
imreader2->SetFileName( argmap["-im2"].c_str() );
AndFilterPointer finalANDFilter = AndFilterType::New();
/** Create images, threshold filters, and threshold vectors. */
ImagePointer im1 = 0;
ImagePointer im2 = 0;
ThresholdFilterPointer im1Thresholder = 0;
ThresholdFilterPointer im2Thresholder = 0;
ThresholdVectorType im1thresholdvector( 2 );
ThresholdVectorType im2thresholdvector( 2 );
/** If there is a threshold given for image1, use it. */
if ( argmap.count("-t1") )
{
im1Thresholder = ThresholdFilterType::New();
im1thresholdvector[ 0 ] = atoi( argmap[ "-t1" ].c_str() );
im1thresholdvector[ 1 ] = itk::NumericTraits<PixelType>::max();
im1Thresholder->SetThresholds( im1thresholdvector );
im1Thresholder->SetInput( imreader1->GetOutput() );
im1 = im1Thresholder->GetOutput();
}
/** Otherwise, just take the input image1. */
else
{
im1 = imreader1->GetOutput();
}
/** If there is a threshold given for image2, use it. */
if ( argmap.count("-t2") )
{
im2Thresholder = ThresholdFilterType::New();
im2thresholdvector[ 0 ] = atoi( argmap[ "-t2" ].c_str() );
im2thresholdvector[ 1 ] = itk::NumericTraits<PixelType>::max();
im2Thresholder->SetThresholds( im2thresholdvector );
im2Thresholder->SetInput( imreader2->GetOutput() );
im2 = im2Thresholder->GetOutput();
}
/** Otherwise, just take the input image2. */
else
{
im2 = imreader2->GetOutput();
}
/** Create readers for the masks and AND filters. */
ImageReaderPointer maskreader1 = 0;
ImageReaderPointer maskreader2 = 0;
AndFilterPointer im2ANDmask1Filter = 0;
AndFilterPointer im1ANDmask2Filter = 0;
/** If there is a mask given for image1, use it on image2. */
if ( argmap.count("-mask1") )
{
maskreader1 = ImageReaderType::New();
maskreader1->SetFileName( argmap["-mask1"].c_str() );
im2ANDmask1Filter = AndFilterType::New();
im2ANDmask1Filter->SetInput1( im2 );
im2ANDmask1Filter->SetInput2( maskreader1->GetOutput() );
finalANDFilter->SetInput1( im2ANDmask1Filter->GetOutput() );
}
/** Otherwise, just use image2. */
else
{
finalANDFilter->SetInput1( im2 );
}
/** If there is a mask given for image2, use it on image1. */
if ( argmap.count("-mask2") )
{
maskreader2 = ImageReaderType::New();
maskreader2->SetFileName( argmap["-mask2"].c_str() );
im1ANDmask2Filter = AndFilterType::New();
im1ANDmask2Filter->SetInput1( im1 );
im1ANDmask2Filter->SetInput2( maskreader2->GetOutput() );
finalANDFilter->SetInput2( im1ANDmask2Filter->GetOutput() );
}
/** Otherwise, just use image1. */
else
{
finalANDFilter->SetInput2( im1 );
}
/** UPDATE!
*
* Call the update of the final filter, in order to execute the whole pipeline.
*/
try
{
finalANDFilter->Update();
}
catch (itk::ExceptionObject & err)
{
std::cerr << err << std::endl;
throw err;
}
/**
* Now calculate the L1-norm.
*/
/** Create iterators. */
IteratorType iteratorA( finalANDFilter->GetInput(1),
finalANDFilter->GetInput(1)->GetLargestPossibleRegion() );
IteratorType iteratorB( finalANDFilter->GetInput(0),
finalANDFilter->GetInput(0)->GetLargestPossibleRegion() );
IteratorType iteratorC( finalANDFilter->GetOutput(),
finalANDFilter->GetOutput()->GetLargestPossibleRegion() );
/** Determine size of first object. */
long long sumA = 0;
for ( iteratorA.GoToBegin(); !iteratorA.IsAtEnd(); ++iteratorA )
{
if ( iteratorA.Value() )
{
++sumA;
}
}
std::cout << "Size of first object: " << sumA << std::endl;
/** Determine size of second object. */
long long sumB = 0;
for ( iteratorB.GoToBegin(); !iteratorB.IsAtEnd(); ++iteratorB )
{
if ( iteratorB.Value() )
{
++sumB;
}
}
std::cout << "Size of second object: " << sumB << std::endl;
/** Determine size of cross-section. */
long long sumC = 0;
for ( iteratorC.GoToBegin(); !iteratorC.IsAtEnd(); ++iteratorC )
{
if ( iteratorC.Value() )
{
++sumC;
}
}
std::cout << "Size of cross-section of both objects: " << sumC << std::endl;
/** Calculate the overlap. */
double overlap;
if ( ( sumA + sumB ) == 0 )
{
overlap = 0;
}
else
{
overlap = static_cast<double>( 2 * sumC ) / static_cast<double>( sumA + sumB );
}
/** Format the output and show overlap. */
std::cout << std::fixed << std::showpoint;
std::cout << "Overlap: " << overlap << std::endl;
/** Return a value. */
return 0;
} // end main
<|endoftext|> |
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_ver_info.h"
extern char *mySubSystem;
extern "C" char *CondorVersion(void);
CondorVersionInfo::CondorVersionInfo(char *versionstring, char *subsystem)
{
myversion.MajorVer = 0;
mysubsys = NULL;
string_to_VersionData(versionstring,myversion);
if ( subsystem ) {
mysubsys = strdup(subsystem);
} else {
mysubsys = strdup(mySubSystem);
}
}
CondorVersionInfo::~CondorVersionInfo()
{
if (mysubsys) free(mysubsys);
}
int
CondorVersionInfo::compare_versions(const char* VersionString1)
{
VersionData_t ver1;
ver1.Scalar = 0;
string_to_VersionData(VersionString1,ver1);
if ( ver1.Scalar < myversion.Scalar )
return -1;
if ( ver1.Scalar > myversion.Scalar )
return 1;
return 0;
}
int
CondorVersionInfo::compare_build_dates(const char* VersionString1)
{
VersionData_t ver1;
ver1.BuildDate = 0;
string_to_VersionData(VersionString1,ver1);
if ( ver1.BuildDate < myversion.BuildDate )
return -1;
if ( ver1.BuildDate > myversion.BuildDate )
return 1;
return 0;
}
bool
CondorVersionInfo::is_compatible(const char* other_version_string,
const char* other_subsys)
{
VersionData_t other_ver;
if ( !(string_to_VersionData(other_version_string,other_ver)) ) {
// say not compatible if we cannot even grok the version
// string!
return false;
}
/*********************************************************
Add any logic on specific compatibilty issues right
here!
*********************************************************/
// This version is not compatible with this for that, blah, blah
/*********************************************************
Now that specific rule checks are over, and we still have
not made a decision, we fall back upon generalized rules.
The general rule is within a given stable series, anything
is both forwards and backwards compatible. Other than that,
everything is assumed to be backwards compatible but _not_
forwards compatible. We only check version numbers, not
build dates, when performing these checks.
*********************************************************/
// check if both in same stable series
if ( is_stable_series() && (myversion.MajorVer == other_ver.MajorVer)
&& (myversion.MinorVer == other_ver.MinorVer) ) {
return true;
}
// check if other version is older (or same) than we are; if so,
// we are compatible because the assumption is we are
// backwards compatible.
if ( other_ver.Scalar <= myversion.Scalar ) {
return true;
}
return false;
}
bool
CondorVersionInfo::built_since_version(int MajorVer, int MinorVer,
int SubMinorVer)
{
int Scalar = MajorVer * 1000000 + MinorVer * 1000
+ SubMinorVer;
return ( Scalar >= myversion.Scalar );
}
bool
CondorVersionInfo::built_since_date(int month, int day, int year)
{
// Make a struct tm
struct tm build_date;
time_t BuildDate;
build_date.tm_hour = 0;
build_date.tm_isdst = 1;
build_date.tm_mday = day;
build_date.tm_min = 0;
build_date.tm_mon = month - 1;
build_date.tm_sec = 0;
build_date.tm_year = year - 1900;
if ( (BuildDate = mktime(&build_date)) == -1 ) {
return false;
}
return ( myversion.BuildDate >= BuildDate );
}
bool
CondorVersionInfo::is_valid(const char* VersionString)
{
bool ret_value;
VersionData_t ver1;
if ( !VersionString ) {
return (myversion.MajorVer > 5);
}
ret_value = string_to_VersionData(VersionString,ver1);
return ret_value;
}
char *
CondorVersionInfo::get_version_from_file(const char* filename,
char *ver, int maxlen)
{
bool must_free = false;
if (!filename)
return NULL;
if (ver && maxlen < 40 )
return NULL;
maxlen--; // save room for the NULL character at the end
#ifdef WIN32
static const char *readonly = "rb"; // need binary-mode on NT
#else
static const char *readonly = "r";
#endif
FILE *fp = fopen(filename,readonly);
if ( !fp ) {
// file not found
return NULL;
}
if (!ver) {
if ( !(ver = (char *)malloc(100)) ) {
// out of memory
return NULL;
}
must_free = true;
maxlen = 100;
}
int i = 0;
bool got_verstring = false;
const char* verprefix = CondorVersion();
int ch;
while( (ch=fgetc(fp)) != EOF ) {
if ( ch != verprefix[i] ) {
i = 0;
if ( ch != verprefix[0] ) {
continue;
}
}
ver[i++] = ch;
if ( ch == ':' ) {
while ( (i < maxlen) && ((ch=fgetc(fp)) != EOF) ) {
ver[i++] = ch;
if ( ch == '$' ) {
got_verstring = true;
ver[i] = '\0';
break;
}
}
break;
}
}
fclose(fp);
if ( got_verstring ) {
return ver;
} else {
// could not find it
if ( must_free ) {
free( ver );
}
return NULL;
}
}
bool
CondorVersionInfo::string_to_VersionData(const char *verstring,
VersionData_t & ver)
{
// verstring looks like "$CondorVersion: 6.1.10 Nov 23 1999 $"
if ( !verstring ) {
// Use our own version number.
verstring = CondorVersion();
// If we already computed myversion, we're done.
if ( myversion.MajorVer ) {
ver = myversion;
return true;
}
}
if ( strncmp(verstring,"$CondorVersion: ",16) != 0 ) {
return false;
}
char *ptr = strchr(verstring,' ');
ptr++; // skip space after the colon
sscanf(ptr,"%d.%d.%d ",&ver.MajorVer,&ver.MinorVer,&ver.SubMinorVer);
// Sanity check: the world starts with Condor V6 !
if (ver.MajorVer < 6 || ver.MinorVer > 99 || ver.SubMinorVer > 99) {
myversion.MajorVer = 0;
return false;
}
ver.Scalar = ver.MajorVer * 1000000 + ver.MinorVer * 1000
+ ver.SubMinorVer;
// Now move ptr the next space, which should be
// right before the build date string.
ptr = strchr(ptr,' ');
if ( !ptr ) {
myversion.MajorVer = 0;
return false;
}
ptr++; // skip space after the version numbers
// Convert month to a number
const char *monthNames[] = { "Jan", "Feb", "Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
int month = -1;
for (int i=0; i<12; i++) {
if (strncmp(monthNames[i],ptr,3) == 0) {
month = i;
break;
}
}
ptr+= 4; //skip month and space
// Grab day of the month and year
int date, year;
date = year = -1;
sscanf(ptr,"%d %d",&date,&year);
// Sanity checks
if ( month < 0 || month > 11 || date < 0 || date > 31 || year < 1997
|| year > 2036 ) {
myversion.MajorVer = 0;
return false;
}
// Make a struct tm
struct tm build_date;
build_date.tm_hour = 0;
build_date.tm_isdst = 1;
build_date.tm_mday = date;
build_date.tm_min = 0;
build_date.tm_mon = month;
build_date.tm_sec = 0;
build_date.tm_year = year - 1900;
if ( (ver.BuildDate = mktime(&build_date)) == -1 ) {
myversion.MajorVer = 0;
return false;
}
return true;
}
<commit_msg>fixed bug in method built_since_version()<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_ver_info.h"
extern char *mySubSystem;
extern "C" char *CondorVersion(void);
CondorVersionInfo::CondorVersionInfo(char *versionstring, char *subsystem)
{
myversion.MajorVer = 0;
mysubsys = NULL;
string_to_VersionData(versionstring,myversion);
if ( subsystem ) {
mysubsys = strdup(subsystem);
} else {
mysubsys = strdup(mySubSystem);
}
}
CondorVersionInfo::~CondorVersionInfo()
{
if (mysubsys) free(mysubsys);
}
int
CondorVersionInfo::compare_versions(const char* VersionString1)
{
VersionData_t ver1;
ver1.Scalar = 0;
string_to_VersionData(VersionString1,ver1);
if ( ver1.Scalar < myversion.Scalar )
return -1;
if ( ver1.Scalar > myversion.Scalar )
return 1;
return 0;
}
int
CondorVersionInfo::compare_build_dates(const char* VersionString1)
{
VersionData_t ver1;
ver1.BuildDate = 0;
string_to_VersionData(VersionString1,ver1);
if ( ver1.BuildDate < myversion.BuildDate )
return -1;
if ( ver1.BuildDate > myversion.BuildDate )
return 1;
return 0;
}
bool
CondorVersionInfo::is_compatible(const char* other_version_string,
const char* other_subsys)
{
VersionData_t other_ver;
if ( !(string_to_VersionData(other_version_string,other_ver)) ) {
// say not compatible if we cannot even grok the version
// string!
return false;
}
/*********************************************************
Add any logic on specific compatibilty issues right
here!
*********************************************************/
// This version is not compatible with this for that, blah, blah
/*********************************************************
Now that specific rule checks are over, and we still have
not made a decision, we fall back upon generalized rules.
The general rule is within a given stable series, anything
is both forwards and backwards compatible. Other than that,
everything is assumed to be backwards compatible but _not_
forwards compatible. We only check version numbers, not
build dates, when performing these checks.
*********************************************************/
// check if both in same stable series
if ( is_stable_series() && (myversion.MajorVer == other_ver.MajorVer)
&& (myversion.MinorVer == other_ver.MinorVer) ) {
return true;
}
// check if other version is older (or same) than we are; if so,
// we are compatible because the assumption is we are
// backwards compatible.
if ( other_ver.Scalar <= myversion.Scalar ) {
return true;
}
return false;
}
bool
CondorVersionInfo::built_since_version(int MajorVer, int MinorVer,
int SubMinorVer)
{
int Scalar = MajorVer * 1000000 + MinorVer * 1000
+ SubMinorVer;
return ( myversion.Scalar >= Scalar );
}
bool
CondorVersionInfo::built_since_date(int month, int day, int year)
{
// Make a struct tm
struct tm build_date;
time_t BuildDate;
build_date.tm_hour = 0;
build_date.tm_isdst = 1;
build_date.tm_mday = day;
build_date.tm_min = 0;
build_date.tm_mon = month - 1;
build_date.tm_sec = 0;
build_date.tm_year = year - 1900;
if ( (BuildDate = mktime(&build_date)) == -1 ) {
return false;
}
return ( myversion.BuildDate >= BuildDate );
}
bool
CondorVersionInfo::is_valid(const char* VersionString)
{
bool ret_value;
VersionData_t ver1;
if ( !VersionString ) {
return (myversion.MajorVer > 5);
}
ret_value = string_to_VersionData(VersionString,ver1);
return ret_value;
}
char *
CondorVersionInfo::get_version_from_file(const char* filename,
char *ver, int maxlen)
{
bool must_free = false;
if (!filename)
return NULL;
if (ver && maxlen < 40 )
return NULL;
maxlen--; // save room for the NULL character at the end
#ifdef WIN32
static const char *readonly = "rb"; // need binary-mode on NT
#else
static const char *readonly = "r";
#endif
FILE *fp = fopen(filename,readonly);
if ( !fp ) {
// file not found
return NULL;
}
if (!ver) {
if ( !(ver = (char *)malloc(100)) ) {
// out of memory
return NULL;
}
must_free = true;
maxlen = 100;
}
int i = 0;
bool got_verstring = false;
const char* verprefix = CondorVersion();
int ch;
while( (ch=fgetc(fp)) != EOF ) {
if ( ch != verprefix[i] ) {
i = 0;
if ( ch != verprefix[0] ) {
continue;
}
}
ver[i++] = ch;
if ( ch == ':' ) {
while ( (i < maxlen) && ((ch=fgetc(fp)) != EOF) ) {
ver[i++] = ch;
if ( ch == '$' ) {
got_verstring = true;
ver[i] = '\0';
break;
}
}
break;
}
}
fclose(fp);
if ( got_verstring ) {
return ver;
} else {
// could not find it
if ( must_free ) {
free( ver );
}
return NULL;
}
}
bool
CondorVersionInfo::string_to_VersionData(const char *verstring,
VersionData_t & ver)
{
// verstring looks like "$CondorVersion: 6.1.10 Nov 23 1999 $"
if ( !verstring ) {
// Use our own version number.
verstring = CondorVersion();
// If we already computed myversion, we're done.
if ( myversion.MajorVer ) {
ver = myversion;
return true;
}
}
if ( strncmp(verstring,"$CondorVersion: ",16) != 0 ) {
return false;
}
char *ptr = strchr(verstring,' ');
ptr++; // skip space after the colon
sscanf(ptr,"%d.%d.%d ",&ver.MajorVer,&ver.MinorVer,&ver.SubMinorVer);
// Sanity check: the world starts with Condor V6 !
if (ver.MajorVer < 6 || ver.MinorVer > 99 || ver.SubMinorVer > 99) {
myversion.MajorVer = 0;
return false;
}
ver.Scalar = ver.MajorVer * 1000000 + ver.MinorVer * 1000
+ ver.SubMinorVer;
// Now move ptr the next space, which should be
// right before the build date string.
ptr = strchr(ptr,' ');
if ( !ptr ) {
myversion.MajorVer = 0;
return false;
}
ptr++; // skip space after the version numbers
// Convert month to a number
const char *monthNames[] = { "Jan", "Feb", "Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
int month = -1;
for (int i=0; i<12; i++) {
if (strncmp(monthNames[i],ptr,3) == 0) {
month = i;
break;
}
}
ptr+= 4; //skip month and space
// Grab day of the month and year
int date, year;
date = year = -1;
sscanf(ptr,"%d %d",&date,&year);
// Sanity checks
if ( month < 0 || month > 11 || date < 0 || date > 31 || year < 1997
|| year > 2036 ) {
myversion.MajorVer = 0;
return false;
}
// Make a struct tm
struct tm build_date;
build_date.tm_hour = 0;
build_date.tm_isdst = 1;
build_date.tm_mday = date;
build_date.tm_min = 0;
build_date.tm_mon = month;
build_date.tm_sec = 0;
build_date.tm_year = year - 1900;
if ( (ver.BuildDate = mktime(&build_date)) == -1 ) {
myversion.MajorVer = 0;
return false;
}
return true;
}
<|endoftext|> |
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#define _FILE_OFFSET_BITS 64
#include "condor_common.h"
#include "condor_debug.h"
#include <dirent.h>
static int access_euid_dir(char const *path,int mode,struct stat *statbuf)
{
errno = 0;
if ((R_OK == 0) || (mode & R_OK)) {
DIR *d = opendir(path);
if (d == NULL) {
if( ! errno ) {
dprintf( D_ALWAYS, "WARNING: opendir() failed, but "
"errno is still 0! Beware of misleading "
"error messages\n" );
}
return -1;
}
closedir(d);
}
if ((W_OK == 0) || (mode & W_OK)) {
int success = 0;
char *pathbuf = (char *)malloc(strlen(path) + 100);
ASSERT( pathbuf );
for(int cnt=0;cnt<100;cnt++) {
sprintf(pathbuf,"%s%caccess-test-%d-%d-%d",path,DIR_DELIM_CHAR,getpid(),(int)time(NULL),cnt);
if( mkdir(pathbuf,0700) == 0 ) {
rmdir( pathbuf );
success = 1;
break;
}
if( errno == EEXIST ) {
continue;
}
break;
}
free( pathbuf );
if( !success ) {
if( errno == EEXIST ) {
dprintf(D_ALWAYS, "Failed to test write access to %s, because too many access-test sub-directories exist.\n", path);
return -1;
}
return -1;
}
}
if ((X_OK == 0) || (mode & X_OK)) {
int back;
back = open(".", O_RDONLY);
if (chdir(path) != 0) {
int save_errno = errno;
close(back);
errno = save_errno;
return -1;
}
/* chdir succeeded, so this effective user has access */
fchdir(back);
close(back);
}
return 0;
}
/* This function access a file with the access() interface, but with stat()
semantics so that the access doesn't occur with the real uid, but the
effective uid instead. */
int
access_euid(const char *path, int mode)
{
#if defined(HAVE_EUIDACCESS)
return euidaccess(path, mode);
#else
FILE *f;
struct stat buf;
int already_stated = 0;
/* clear errno before we begin, so we can ensure we set it to
the right thing. if we return without touching it again,
we want it to be 0 (success).
*/
errno = 0;
/* are the arguments valid? */
if (path == NULL || (mode & ~(R_OK|W_OK|X_OK|F_OK)) != 0) {
errno = EINVAL;
return -1;
}
/* here we are going to sanity check the constants to make sure that we
use them correctly if they happen to be a zero value(WHICH USUALLY F_OK
IS). If it is zero, then by the semantics of the bitwise or of a zeroed
value against a number, which is idempotent, it automatically needs to
happen. */
if ((F_OK == 0) || (mode & F_OK)) {
if (stat(path, &buf) < 0) {
if( ! errno ) {
/* evil! stat() failed but there's no errno! */
dprintf( D_ALWAYS, "WARNING: stat() failed, but "
"errno is still 0! Beware of misleading "
"error messages\n" );
}
return -1;
}
already_stated = 1;
if( buf.st_mode & S_IFDIR ) {
return access_euid_dir(path,mode,&buf);
}
}
if ((R_OK == 0) || (mode & R_OK)) {
f = safe_fopen_wrapper_follow(path, "r", 0644);
if (f == NULL) {
if( errno == EISDIR ) {
return access_euid_dir(path,mode,NULL);
}
if( ! errno ) {
dprintf( D_ALWAYS, "WARNING: safe_fopen_wrapper() failed, but "
"errno is still 0! Beware of misleading "
"error messages\n" );
}
return -1;
}
fclose(f);
}
if ((W_OK == 0) || (mode & W_OK)) {
f = safe_fopen_wrapper_follow(path, "a", 0644); /* don't truncate the file! */
if (f == NULL) {
if( errno == EISDIR ) {
return access_euid_dir(path,mode,NULL);
}
if( ! errno ) {
dprintf( D_ALWAYS, "WARNING: safe_fopen_wrapper() failed, but "
"errno is still 0! Beware of misleading "
"error messages\n" );
}
return -1;
}
fclose(f);
}
if ((X_OK == 0) || (mode & X_OK)) {
if (!already_stated) {
/* stats are expensive, so only do it if I have to */
if (stat(path, &buf) < 0) {
if( ! errno ) {
dprintf( D_ALWAYS, "WARNING: stat() failed, but "
"errno is still 0! Beware of misleading "
"error messages\n" );
}
return -1;
}
if( buf.st_mode & S_IFDIR ) {
return access_euid_dir(path,mode,&buf);
}
}
if (!(buf.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) {
/* since() stat worked, errno will still be 0. that's
no good, since access_euid() is about to return
failure. set errno here to the right thing. */
errno = EACCES;
return -1;
}
}
return 0;
#endif
}
<commit_msg>Fix some warnings caused by changes in access_euid(). #4402<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#define _FILE_OFFSET_BITS 64
#include "condor_common.h"
#include "condor_debug.h"
#include <dirent.h>
#if !defined(HAVE_EUIDACCESS)
static int access_euid_dir(char const *path,int mode)
{
errno = 0;
if ((R_OK == 0) || (mode & R_OK)) {
DIR *d = opendir(path);
if (d == NULL) {
if( ! errno ) {
dprintf( D_ALWAYS, "WARNING: opendir() failed, but "
"errno is still 0! Beware of misleading "
"error messages\n" );
}
return -1;
}
closedir(d);
}
if ((W_OK == 0) || (mode & W_OK)) {
int success = 0;
char *pathbuf = (char *)malloc(strlen(path) + 100);
ASSERT( pathbuf );
for(int cnt=0;cnt<100;cnt++) {
sprintf(pathbuf,"%s%caccess-test-%d-%d-%d",path,DIR_DELIM_CHAR,getpid(),(int)time(NULL),cnt);
if( mkdir(pathbuf,0700) == 0 ) {
rmdir( pathbuf );
success = 1;
break;
}
if( errno == EEXIST ) {
continue;
}
break;
}
free( pathbuf );
if( !success ) {
if( errno == EEXIST ) {
dprintf(D_ALWAYS, "Failed to test write access to %s, because too many access-test sub-directories exist.\n", path);
return -1;
}
return -1;
}
}
if ((X_OK == 0) || (mode & X_OK)) {
int back;
back = open(".", O_RDONLY);
if (chdir(path) != 0) {
int save_errno = errno;
close(back);
errno = save_errno;
return -1;
}
/* chdir succeeded, so this effective user has access */
fchdir(back);
close(back);
}
return 0;
}
#endif
/* This function access a file with the access() interface, but with stat()
semantics so that the access doesn't occur with the real uid, but the
effective uid instead. */
int
access_euid(const char *path, int mode)
{
#if defined(HAVE_EUIDACCESS)
return euidaccess(path, mode);
#else
FILE *f;
struct stat buf;
int already_stated = 0;
/* clear errno before we begin, so we can ensure we set it to
the right thing. if we return without touching it again,
we want it to be 0 (success).
*/
errno = 0;
/* are the arguments valid? */
if (path == NULL || (mode & ~(R_OK|W_OK|X_OK|F_OK)) != 0) {
errno = EINVAL;
return -1;
}
/* here we are going to sanity check the constants to make sure that we
use them correctly if they happen to be a zero value(WHICH USUALLY F_OK
IS). If it is zero, then by the semantics of the bitwise or of a zeroed
value against a number, which is idempotent, it automatically needs to
happen. */
if ((F_OK == 0) || (mode & F_OK)) {
if (stat(path, &buf) < 0) {
if( ! errno ) {
/* evil! stat() failed but there's no errno! */
dprintf( D_ALWAYS, "WARNING: stat() failed, but "
"errno is still 0! Beware of misleading "
"error messages\n" );
}
return -1;
}
already_stated = 1;
if( buf.st_mode & S_IFDIR ) {
return access_euid_dir(path,mode);
}
}
if ((R_OK == 0) || (mode & R_OK)) {
f = safe_fopen_wrapper_follow(path, "r", 0644);
if (f == NULL) {
if( errno == EISDIR ) {
return access_euid_dir(path,mode);
}
if( ! errno ) {
dprintf( D_ALWAYS, "WARNING: safe_fopen_wrapper() failed, but "
"errno is still 0! Beware of misleading "
"error messages\n" );
}
return -1;
}
fclose(f);
}
if ((W_OK == 0) || (mode & W_OK)) {
f = safe_fopen_wrapper_follow(path, "a", 0644); /* don't truncate the file! */
if (f == NULL) {
if( errno == EISDIR ) {
return access_euid_dir(path,mode);
}
if( ! errno ) {
dprintf( D_ALWAYS, "WARNING: safe_fopen_wrapper() failed, but "
"errno is still 0! Beware of misleading "
"error messages\n" );
}
return -1;
}
fclose(f);
}
if ((X_OK == 0) || (mode & X_OK)) {
if (!already_stated) {
/* stats are expensive, so only do it if I have to */
if (stat(path, &buf) < 0) {
if( ! errno ) {
dprintf( D_ALWAYS, "WARNING: stat() failed, but "
"errno is still 0! Beware of misleading "
"error messages\n" );
}
return -1;
}
if( buf.st_mode & S_IFDIR ) {
return access_euid_dir(path,mode);
}
}
if (!(buf.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) {
/* since() stat worked, errno will still be 0. that's
no good, since access_euid() is about to return
failure. set errno here to the right thing. */
errno = EACCES;
return -1;
}
}
return 0;
#endif
}
<|endoftext|> |
<commit_before>#include "Rndm.h"
using namespace std;
Rndm::Rndm() : _mt(_rd())
{
}
Rndm & Rndm::rndm()
{
static Rndm rndm;
return rndm;
}
std::mt19937 & Rndm::mt()
{
return Rndm::rndm()._mt;
}
int Rndm::number(int from, int to)
{
uniform_int_distribution<int> num(from, to);
return num(Rndm::mt());
}
<commit_msg>Remove use of std namespace<commit_after>#include "Rndm.h"
Rndm::Rndm() : _mt(_rd())
{
}
Rndm & Rndm::rndm()
{
static Rndm rndm;
return rndm;
}
std::mt19937 & Rndm::mt()
{
return Rndm::rndm()._mt;
}
int Rndm::number(int from, int to)
{
std::uniform_int_distribution<int> num(from, to);
return num(Rndm::mt());
}
<|endoftext|> |
<commit_before>//
// Created by fred.nicolson on 23/05/17.
//
#include <stdexcept>
#include <algorithm>
#include <iostream>
#include "frnetlib/URL.h"
std::unordered_map<std::string, URL::Scheme> URL::scheme_string_map = {
{"http", URL::HTTP},
{"https", URL::HTTPS},
{"sftp", URL::FTP},
{"mailto", URL::MAILTO},
{"irc", URL::IRC},
{"sftp", URL::SFTP},
{"unknown", URL::Unknown}
};
URL::URL(const std::string &url)
{
parse(url);
}
void URL::parse(std::string url)
{
size_t parse_offset = 0;
size_t pos = 0;
//Check to see if a scheme exists
pos = url.find("://");
if(pos != std::string::npos)
{
auto scheme_pos = scheme_string_map.find(to_lower(url.substr(0, pos)));
scheme = (scheme_pos == scheme_string_map.end()) ? URL::Unknown : scheme_pos->second;
parse_offset = pos + 3;
}
//Check to see if there's a port
pos = url.find(":", parse_offset);
if(pos != std::string::npos)
{
//Store host
host = url.substr(parse_offset, pos - parse_offset);
parse_offset += host.size();
//Find end of port
size_t port_end = url.find("/", parse_offset);
port_end = (port_end == std::string::npos) ? url.size() : port_end;
port = url.substr(pos + 1, port_end - pos - 1);
parse_offset = port_end + 1;
}
else
{
//Store host
pos = url.find("/", parse_offset);
pos = (pos != std::string::npos) ? pos : url.find("?", parse_offset);
pos = (pos != std::string::npos) ? pos : url.find("#", parse_offset);
pos = (pos != std::string::npos) ? pos : url.size();
host = url.substr(parse_offset, pos - parse_offset);
parse_offset = pos + 1;
}
//Exit if done
if(parse_offset >= url.size())
return;
//Extract the path
pos = url.find("?", parse_offset);
if(pos != std::string::npos)
{
path = url.substr(parse_offset, pos - parse_offset);
parse_offset = pos + 1;
}
else
{
pos = url.find("#", parse_offset);
pos = (pos != std::string::npos) ? pos : url.find("?", parse_offset);
pos = (pos != std::string::npos) ? pos : url.size();
path = url.substr(parse_offset, pos - parse_offset);
parse_offset = pos + 1;
}
//Extract the query
pos = url.find("#", parse_offset - 1);
if(pos != std::string::npos)
{
if(pos + 1 != parse_offset)
query = url.substr(parse_offset, pos - parse_offset);
fragment = url.substr(pos + 1, url.size() - pos - 1);
}
else
{
if(parse_offset >= url.size())
return;
query = url.substr(parse_offset, url.size() - parse_offset);
}
return;
}
URL::Scheme URL::string_to_scheme(const std::string &scheme)
{
auto iter = scheme_string_map.find(to_lower(scheme));
if(iter == scheme_string_map.end())
return URL::Unknown;
return iter->second;
}
std::string URL::to_lower(const std::string &str)
{
std::string out = str;
std::transform(out.begin(), out.end(), out.begin(), ::tolower);
return out;
}
const std::string &URL::scheme_to_string(URL::Scheme scheme)
{
auto iter = std::find_if(scheme_string_map.begin(), scheme_string_map.end(), [](const auto &i){
return i->second == scheme;
});
if(iter == scheme_string_map.end())
throw std::logic_error("Unknown URL::Scheme value " + std::to_string(scheme));
return iter->first;
}
<commit_msg>Compilation error fixed<commit_after>//
// Created by fred.nicolson on 23/05/17.
//
#include <stdexcept>
#include <algorithm>
#include <iostream>
#include "frnetlib/URL.h"
std::unordered_map<std::string, URL::Scheme> URL::scheme_string_map = {
{"http", URL::HTTP},
{"https", URL::HTTPS},
{"sftp", URL::FTP},
{"mailto", URL::MAILTO},
{"irc", URL::IRC},
{"sftp", URL::SFTP},
{"unknown", URL::Unknown}
};
URL::URL(const std::string &url)
{
parse(url);
}
void URL::parse(std::string url)
{
size_t parse_offset = 0;
size_t pos = 0;
//Check to see if a scheme exists
pos = url.find("://");
if(pos != std::string::npos)
{
auto scheme_pos = scheme_string_map.find(to_lower(url.substr(0, pos)));
scheme = (scheme_pos == scheme_string_map.end()) ? URL::Unknown : scheme_pos->second;
parse_offset = pos + 3;
}
//Check to see if there's a port
pos = url.find(":", parse_offset);
if(pos != std::string::npos)
{
//Store host
host = url.substr(parse_offset, pos - parse_offset);
parse_offset += host.size();
//Find end of port
size_t port_end = url.find("/", parse_offset);
port_end = (port_end == std::string::npos) ? url.size() : port_end;
port = url.substr(pos + 1, port_end - pos - 1);
parse_offset = port_end + 1;
}
else
{
//Store host
pos = url.find("/", parse_offset);
pos = (pos != std::string::npos) ? pos : url.find("?", parse_offset);
pos = (pos != std::string::npos) ? pos : url.find("#", parse_offset);
pos = (pos != std::string::npos) ? pos : url.size();
host = url.substr(parse_offset, pos - parse_offset);
parse_offset = pos + 1;
}
//Exit if done
if(parse_offset >= url.size())
return;
//Extract the path
pos = url.find("?", parse_offset);
if(pos != std::string::npos)
{
path = url.substr(parse_offset, pos - parse_offset);
parse_offset = pos + 1;
}
else
{
pos = url.find("#", parse_offset);
pos = (pos != std::string::npos) ? pos : url.find("?", parse_offset);
pos = (pos != std::string::npos) ? pos : url.size();
path = url.substr(parse_offset, pos - parse_offset);
parse_offset = pos + 1;
}
//Extract the query
pos = url.find("#", parse_offset - 1);
if(pos != std::string::npos)
{
if(pos + 1 != parse_offset)
query = url.substr(parse_offset, pos - parse_offset);
fragment = url.substr(pos + 1, url.size() - pos - 1);
}
else
{
if(parse_offset >= url.size())
return;
query = url.substr(parse_offset, url.size() - parse_offset);
}
return;
}
URL::Scheme URL::string_to_scheme(const std::string &scheme)
{
auto iter = scheme_string_map.find(to_lower(scheme));
if(iter == scheme_string_map.end())
return URL::Unknown;
return iter->second;
}
std::string URL::to_lower(const std::string &str)
{
std::string out = str;
std::transform(out.begin(), out.end(), out.begin(), ::tolower);
return out;
}
const std::string &URL::scheme_to_string(URL::Scheme scheme)
{
auto iter = std::find_if(scheme_string_map.begin(), scheme_string_map.end(), [&](const auto &i){
return i.second == scheme;
});
if(iter == scheme_string_map.end())
throw std::logic_error("Unknown URL::Scheme value " + std::to_string(scheme));
return iter->first;
}
<|endoftext|> |
<commit_before><commit_msg>edited files<commit_after>#include "rshell.h"
#include "../header/and.h"
using namespace std;
void And::execute(string cmd, bool &prev_cmd)
{
}
<|endoftext|> |
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team 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.
*******************************************************************************/
//==============================================================================
// SampleWindow plugin
//==============================================================================
#include "guiutils.h"
#include "samplewindowplugin.h"
#include "samplewindowwindow.h"
//==============================================================================
#include <QMainWindow>
#include <QSettings>
//==============================================================================
namespace OpenCOR {
namespace SampleWindow {
//==============================================================================
PLUGININFO_FUNC SampleWindowPluginInfo()
{
Descriptions descriptions;
descriptions.insert("en", QString::fromUtf8("a plugin that provides a simple addition window."));
descriptions.insert("fr", QString::fromUtf8("une extension qui fournit une simple fentre d'addition."));
return new PluginInfo(PluginInfo::Sample, true, false,
QStringList() << "Core" << "Sample",
descriptions);
}
//==============================================================================
// I18n interface
//==============================================================================
void SampleWindowPlugin::retranslateUi()
{
// Retranslate our sample window action
retranslateAction(mSampleWindowAction,
tr("Sample"),
tr("Show/hide the Sample window"));
}
//==============================================================================
// Plugin interface
//==============================================================================
void SampleWindowPlugin::initializePlugin(QMainWindow *pMainWindow)
{
// Create an action to show/hide our sample window
mSampleWindowAction = Core::newAction(true, pMainWindow);
// Create our sample window
mSampleWindowWindow = new SampleWindowWindow(pMainWindow);
}
//==============================================================================
void SampleWindowPlugin::finalizePlugin()
{
// We don't handle this interface...
}
//==============================================================================
void SampleWindowPlugin::pluginInitialized(const Plugins &pLoadedPlugins)
{
Q_UNUSED(pLoadedPlugins);
// We don't handle this interface...
}
//==============================================================================
void SampleWindowPlugin::loadSettings(QSettings *pSettings)
{
// Retrieve our sample window settings
pSettings->beginGroup(mSampleWindowWindow->objectName());
mSampleWindowWindow->loadSettings(pSettings);
pSettings->endGroup();
}
//==============================================================================
void SampleWindowPlugin::saveSettings(QSettings *pSettings) const
{
// Keep track of our sample window settings
pSettings->beginGroup(mSampleWindowWindow->objectName());
mSampleWindowWindow->saveSettings(pSettings);
pSettings->endGroup();
}
//==============================================================================
void SampleWindowPlugin::handleAction(const QUrl &pUrl)
{
Q_UNUSED(pUrl);
// We don't handle this interface...
}
//==============================================================================
// Window interface
//==============================================================================
Qt::DockWidgetArea SampleWindowPlugin::windowDefaultDockArea() const
{
// Return our default dock area
return Qt::TopDockWidgetArea;
}
//==============================================================================
QDockWidget * SampleWindowPlugin::windowWidget() const
{
// Return our window widget
return mSampleWindowWindow;
}
//==============================================================================
QAction * SampleWindowPlugin::windowAction() const
{
// Return our window action
return mSampleWindowAction;
}
//==============================================================================
} // namespace SampleWindow
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up [ci skip].<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team 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.
*******************************************************************************/
//==============================================================================
// SampleWindow plugin
//==============================================================================
#include "guiutils.h"
#include "samplewindowplugin.h"
#include "samplewindowwindow.h"
//==============================================================================
#include <QMainWindow>
#include <QSettings>
//==============================================================================
namespace OpenCOR {
namespace SampleWindow {
//==============================================================================
PLUGININFO_FUNC SampleWindowPluginInfo()
{
Descriptions descriptions;
descriptions.insert("en", QString::fromUtf8("a plugin that provides a simple addition window."));
descriptions.insert("fr", QString::fromUtf8("une extension qui fournit une simple fenêtre d'addition."));
return new PluginInfo(PluginInfo::Sample, true, false,
QStringList() << "Core" << "Sample",
descriptions);
}
//==============================================================================
// I18n interface
//==============================================================================
void SampleWindowPlugin::retranslateUi()
{
// Retranslate our sample window action
retranslateAction(mSampleWindowAction,
tr("Sample"),
tr("Show/hide the Sample window"));
}
//==============================================================================
// Plugin interface
//==============================================================================
void SampleWindowPlugin::initializePlugin(QMainWindow *pMainWindow)
{
// Create an action to show/hide our sample window
mSampleWindowAction = Core::newAction(true, pMainWindow);
// Create our sample window
mSampleWindowWindow = new SampleWindowWindow(pMainWindow);
}
//==============================================================================
void SampleWindowPlugin::finalizePlugin()
{
// We don't handle this interface...
}
//==============================================================================
void SampleWindowPlugin::pluginInitialized(const Plugins &pLoadedPlugins)
{
Q_UNUSED(pLoadedPlugins);
// We don't handle this interface...
}
//==============================================================================
void SampleWindowPlugin::loadSettings(QSettings *pSettings)
{
// Retrieve our sample window settings
pSettings->beginGroup(mSampleWindowWindow->objectName());
mSampleWindowWindow->loadSettings(pSettings);
pSettings->endGroup();
}
//==============================================================================
void SampleWindowPlugin::saveSettings(QSettings *pSettings) const
{
// Keep track of our sample window settings
pSettings->beginGroup(mSampleWindowWindow->objectName());
mSampleWindowWindow->saveSettings(pSettings);
pSettings->endGroup();
}
//==============================================================================
void SampleWindowPlugin::handleAction(const QUrl &pUrl)
{
Q_UNUSED(pUrl);
// We don't handle this interface...
}
//==============================================================================
// Window interface
//==============================================================================
Qt::DockWidgetArea SampleWindowPlugin::windowDefaultDockArea() const
{
// Return our default dock area
return Qt::TopDockWidgetArea;
}
//==============================================================================
QDockWidget * SampleWindowPlugin::windowWidget() const
{
// Return our window widget
return mSampleWindowWindow;
}
//==============================================================================
QAction * SampleWindowPlugin::windowAction() const
{
// Return our window action
return mSampleWindowAction;
}
//==============================================================================
} // namespace SampleWindow
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>/*
Copyright (C) 2002 by Norman Krmer
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "cssys/thread.h"
#include <sys/time.h>
/**
* A pthread implementation of the CS thread interface.
*/
uint32 csThreadInit (csThread *thread, csThreadFunc func, void* param, uint32 /*threadAttributes*/)
{
pthread_attr_t attr;
int rc;
uint32 ret;
/*
Force thread to be joinable, in later pthread implementations this is default already
Thread cancellation state is _assumed_ to be PTHREAD_CANCEL_ENABLE and cancellation type is PTHREAD_CANCEL_DEFERRED
*/
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
rc = pthread_create((pthread_t*)thread, &attr, func, param);
switch (rc)
{
case EAGAIN:
ret = CS_THREAD_OUT_OF_RESOURCES;
break;
case EINVAL:
ret = CS_THREAD_ERR_ATTRIBUTE;
break;
case EPERM:
ret = CS_THREAD_NO_PERMISSION;
break;
case 0:
ret = CS_THREAD_NO_ERROR;
pthread_attr_destroy(&attr);
break;
default:
ret = CS_THREAD_UNKNOWN_ERROR;
break;
}
return ret;
}
void csThreadExit (void* exitValue)
{
pthread_exit (exitValue);
}
uint32 csThreadJoin (csThread *thread, void** retValue)
{
int rc = pthread_join (*(pthread_t*)thread, retValue);
uint32 ret;
switch (rc)
{
case ESRCH:
ret = CS_THREAD_UNKNOWN_THREAD;
break;
case EDEADLK:
ret = CS_THREAD_DEADLOCK;
break;
case 0:
ret = CS_THREAD_NO_ERROR;
break;
default:
ret = CS_THREAD_UNKNOWN_ERROR;
break;
}
return ret;
}
uint32 csThreadKill (csThread *thread, csThreadSignal signal)
{
uint32 ret = CS_THREAD_NO_ERROR;
int sig = 0;
if (signal == csThreadSignalTerminate)
sig = SIGTERM;
else if (signal == csThreadSignalKill)
sig = SIGKILL;
else
ret = CS_THREAD_SIGNAL_UNKNOWN;
if (ret == CS_THREAD_NO_ERROR)
{
int rc;
rc = pthread_kill (*(pthread_t*)thread, sig);
switch (rc)
{
case ESRCH:
ret = CS_THREAD_UNKNOWN_THREAD;
break;
case EINVAL:
ret = CS_THREAD_SIGNAL_UNKNOWN;
break;
case 0:
ret = CS_THREAD_NO_ERROR;
break;
default:
ret = CS_THREAD_UNKNOWN_ERROR;
break;
}
}
return ret;
}
uint32 csThreadCancel (csThread *thread)
{
int rc = pthread_cancel (*(pthread_t*)thread);
uint32 ret;
switch (rc)
{
case ESRCH:
ret = CS_THREAD_UNKNOWN_THREAD;
break;
case 0:
ret = CS_THREAD_NO_ERROR;
break;
default:
ret = CS_THREAD_UNKNOWN_ERROR;
break;
}
return ret;
}
uint32 csMutexInit (csMutex* mutex)
{
/*
Create an 'fast' mutex, that is a deadlock occurs if a thread
tries to LockWait a mutex it already owns.
*/
pthread_mutex_init ((pthread_mutex_t*)mutex, NULL);
return CS_THREAD_NO_ERROR;
}
uint32 csMutexLockWait (csMutex* mutex)
{
uint32 ret;
int rc = pthread_mutex_lock ((pthread_mutex_t*)mutex);
switch (rc)
{
case EINVAL:
ret = CS_THREAD_MUTEX_NOT_INITIALIZED;
break;
case EDEADLK:
ret = CS_THREAD_DEADLOCK;
break;
case 0:
ret = CS_THREAD_NO_ERROR;
break;
default:
ret = CS_THREAD_UNKNOWN_ERROR;
break;
}
return ret;
}
uint32 csMutexLockTry (csMutex* mutex)
{
uint32 ret;
int rc = pthread_mutex_trylock ((pthread_mutex_t*)mutex);
switch (rc)
{
case EINVAL:
ret = CS_THREAD_MUTEX_NOT_INITIALIZED;
break;
case EBUSY:
ret = CS_THREAD_MUTEX_BUSY;
break;
case 0:
ret = CS_THREAD_NO_ERROR;
break;
default:
ret = CS_THREAD_UNKNOWN_ERROR;
break;
}
return ret;
}
uint32 csMutexRelease (csMutex* mutex)
{
uint32 ret;
int rc = pthread_mutex_unlock ((pthread_mutex_t*)mutex);
switch (rc)
{
case EINVAL:
ret = CS_THREAD_MUTEX_NOT_INITIALIZED;
break;
case EPERM:
ret = CS_THREAD_NO_PERMISSION;
break;
case 0:
ret = CS_THREAD_NO_ERROR;
break;
default:
ret = CS_THREAD_UNKNOWN_ERROR;
break;
}
return ret;
}
uint32 csMutexDestroy (csMutex* mutex)
{
uint32 ret;
int rc = pthread_mutex_destroy ((pthread_mutex_t*)mutex);
switch (rc)
{
case EBUSY:
ret = CS_THREAD_MUTEX_BUSY;
break;
case 0:
ret = CS_THREAD_NO_ERROR;
break;
default:
ret = CS_THREAD_UNKNOWN_ERROR;
break;
}
return ret;
}
uint32 csSemaphoreInit (csSemaphore* sem, uint32 value)
{
int rc = sem_init ((sem_t*)sem, 0, (unsigned int)value);
uint32 ret = CS_THREAD_NO_ERROR;
if (rc)
{
if (errno == EINVAL)
ret = CS_THREAD_SEMA_VALUE_TOO_LARGE;
}
else
ret = CS_THREAD_NO_ERROR;
return ret;
}
uint32 csSemaphoreLock (csSemaphore* sem)
{
sem_wait ((sem_t*)sem);
return CS_THREAD_NO_ERROR;
}
uint32 csSemaphoreLockTry (csSemaphore* sem)
{
int rc = sem_trywait ((sem_t*)sem);
uint32 ret;
if (rc)
switch (errno)
{
case EAGAIN:
ret = CS_THREAD_SEMA_BUSY;
break;
default:
ret = CS_THREAD_UNKNOWN_ERROR;
break;
}
else
ret = CS_THREAD_NO_ERROR;
return ret;
}
uint32 csSemaphoreRelease (csSemaphore* sem)
{
int rc = sem_post ((sem_t*)sem);
uint32 ret;
if (rc)
ret = CS_THREAD_UNKNOWN_ERROR;
else
ret = CS_THREAD_NO_ERROR;
return ret;
}
uint32 csSemaphoreValue (csSemaphore* sem)
{
int val;
sem_getvalue ((sem_t*)sem, &val);
return (uint32)val;
}
uint32 csSemaphoreDestroy (csSemaphore* sem)
{
int rc = sem_destroy ((sem_t*)sem);
uint32 ret;
if (rc)
switch (errno)
{
case EBUSY:
ret = CS_THREAD_SEMA_BUSY;
break;
default:
ret = CS_THREAD_UNKNOWN_ERROR;
break;
}
else
ret = CS_THREAD_NO_ERROR;
return ret;
}
uint32 csConditionInit (csCondition *cond, uint32 /*conditionAttributes*/)
{
pthread_cond_init ((pthread_cond_t*)cond, NULL);
return CS_THREAD_NO_ERROR;
}
uint32 csConditionSignalOne (csCondition *cond)
{
pthread_cond_signal ((pthread_cond_t*)cond);
return CS_THREAD_NO_ERROR;
}
uint32 csConditionSignalAll (csCondition *cond)
{
pthread_cond_broadcast ((pthread_cond_t*)cond);
return CS_THREAD_NO_ERROR;
}
uint32 csConditionWait (csCondition *cond, csMutex *mutex)
{
pthread_cond_wait ((pthread_cond_t*)cond, (pthread_mutex_t*)mutex);
return CS_THREAD_NO_ERROR;
}
uint32 csConditionWait (csCondition *cond, csMutex *mutex, csTicks timeout)
{
uint32 ret;
struct timeval now;
struct timezone tz;
struct timespec to;
gettimeofday (&now, &tz);
to.tv_sec = now.tv_sec + (timeout / 1000);
to.tv_nsec = (now.tv_usec + (timeout % 1000)*1000)*1000;
int rc = pthread_cond_timedwait ((pthread_cond_t*)cond, (pthread_mutex_t*)mutex, &to);
switch (rc)
{
case ETIMEDOUT:
ret = CS_THREAD_CONDITION_TIMEOUT;
break;
case EINTR:
ret = CS_THREAD_CONDITION_WAIT_INTERRUPTED;
break;
case 0:
ret = CS_THREAD_NO_ERROR;
break;
default:
ret = CS_THREAD_UNKNOWN_ERROR;
break;
}
return ret;
}
uint32 csConditionDestroy (csCondition *cond)
{
int rc = pthread_cond_destroy ((pthread_cond_t*)cond);
uint32 ret;
switch (rc)
{
case EBUSY:
ret = CS_THREAD_CONDITION_BUSY;
break;
case 0:
ret = CS_THREAD_NO_ERROR;
break;
default:
ret = CS_THREAD_UNKNOWN_ERROR;
break;
}
return ret;
}
<commit_msg>class interface to threading<commit_after>/*
Copyright (C) 2002 by Norman Krmer
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "cssys/thread.h"
#include <sys/time.h>
#ifdef CS_DEBUG
#define CS_SHOW_ERROR if (lasterr) printf ("%s\n",lasterr)
#else
#define CS_SHOW_ERROR
#endif
csPosixMutex::csPosixMutex ()
{
lasterr = NULL;
/*
Create an 'fast' mutex, that is a deadlock occurs if a thread
tries to LockWait a mutex it already owns.
*/
pthread_mutex_init (&mutex, NULL);
}
csPosixMutex::~csPosixMutex ()
{
#ifdef CS_DEBUG
// CS_ASSERT (Destroy ());
Destroy ();
#else
Destroy ();
#endif
}
bool csPosixMutex::Destroy ()
{
int rc = pthread_mutex_destroy (&mutex);
switch (rc)
{
case EBUSY:
lasterr = "Mutex busy";
break;
case 0:
lasterr = NULL;
break;
default:
lasterr = "Unknown error while destroying mutex";
break;
}
CS_SHOW_ERROR;
return rc == 0;
}
bool csPosixMutex::LockWait()
{
int rc = pthread_mutex_lock (&mutex);
switch (rc)
{
case EINVAL:
lasterr = "Mutex not initialized";
break;
case EDEADLK:
lasterr = "Deadlock";
break;
case 0:
lasterr = NULL;
break;
default:
lasterr = "Unknown error while locking mutex";
break;
}
CS_SHOW_ERROR;
return rc == 0;
}
bool csPosixMutex::LockTry ()
{
uint32 ret;
int rc = pthread_mutex_trylock (&mutex);
switch (rc)
{
case EINVAL:
lasterr = "Mutex not initialized";
break;
case EDEADLK:
lasterr = "Deadlock";
break;
case 0:
lasterr = NULL;
break;
default:
lasterr = "Unknown error while trying to lock mutex";
break;
}
CS_SHOW_ERROR;
return ret;
}
bool csPosixMutex::Release ()
{
int rc = pthread_mutex_unlock (&mutex);
switch (rc)
{
case EINVAL:
lasterr = "Mutex not initialized";
break;
case EPERM:
lasterr = "No permission";
break;
case 0:
lasterr = NULL;
break;
default:
lasterr = "Unknown error while releasing mutex";
break;
}
CS_SHOW_ERROR;
return rc == 0;
}
void csPosixMutex::Cleanup (void *arg)
{
((csPosixMutex*)arg)->Release ();
}
const char* csPosixMutex::GetLastError ()
{
return lasterr;
}
csPosixSemaphore::csPosixSemaphore (uint32 value)
{
int rc = sem_init (&sem, 0, (unsigned int)value);
if (rc)
lasterr = sys_errlist[errno];
else
lasterr = NULL;
CS_SHOW_ERROR;
}
csPosixSemaphore::~csPosixSemaphore ()
{
Destroy ();
}
bool csPosixSemaphore::LockWait ()
{
sem_wait (&sem);
return true;
}
bool csPosixSemaphore::LockTry ()
{
int rc = sem_trywait (&sem);
if (rc)
lasterr = sys_errlist[errno];
else
lasterr = NULL;
CS_SHOW_ERROR;
return rc == 0;
}
bool csPosixSemaphore::Release ()
{
int rc = sem_post (&sem);
if (rc)
lasterr = sys_errlist[errno];
else
lasterr = NULL;
CS_SHOW_ERROR;
return rc == 0;
}
uint32 csPosixSemaphore::Value ()
{
int val;
sem_getvalue (&sem, &val);
return (uint32)val;
}
bool csPosixSemaphore::Destroy ()
{
int rc = sem_destroy (&sem);
if (rc)
lasterr = sys_errlist[errno];
else
lasterr = NULL;
CS_SHOW_ERROR;
return rc == 0;
}
csPosixCondition::csPosixCondition (uint32 /*conditionAttributes*/)
{
pthread_cond_init (&cond, NULL);
lasterr = NULL;
}
csPosixCondition::~csPosixCondition ()
{
Destroy ();
}
void csPosixCondition::Signal (bool bAll)
{
if (bAll)
pthread_cond_broadcast (&cond);
else
pthread_cond_signal (&cond);
}
bool csPosixCondition::Wait (csPosixMutex *mutex, csTicks timeout)
{
int rc = 0;
if (timeout > 0)
{
struct timeval now;
struct timezone tz;
struct timespec to;
gettimeofday (&now, &tz);
to.tv_sec = now.tv_sec + (timeout / 1000);
to.tv_nsec = (now.tv_usec + (timeout % 1000)*1000)*1000;
rc = pthread_cond_timedwait (&cond, &mutex->mutex, &to);
switch (rc)
{
case ETIMEDOUT:
lasterr = "Timeout";
break;
case EINTR:
lasterr = "Wait interrupted";
break;
case 0:
lasterr = NULL;
break;
default:
lasterr = "Unknown error while timed waiting for condition";
break;
}
}
else
pthread_cond_wait (&cond, &mutex->mutex);
CS_SHOW_ERROR;
return rc == 0;
}
bool csPosixCondition::Destroy ()
{
int rc = pthread_cond_destroy (&cond);
switch (rc)
{
case EBUSY:
lasterr = "Condition busy";
break;
case 0:
lasterr = NULL;
break;
default:
lasterr = "Unknown error while destroying mutex";
break;
}
CS_SHOW_ERROR;
return rc == 0;
}
csPosixThread::csPosixThread (iRunnable *runnable, uint32 /*options*/)
{
csPosixThread::runnable = runnable;
running = false;
created = false;
lasterr = NULL;
}
csPosixThread::~csPosixThread ()
{
if (running)
Kill ();
// if (created)
// pthread_join (thread, NULL); // clean up resources
}
bool csPosixThread::Start ()
{
if (!running && runnable)
{
if (created)
{
pthread_join (thread, NULL); // clean up resources
created = false;
}
pthread_attr_t attr;
int rc;
/*
Force thread to be joinable, in later pthread implementations this is default already
Thread cancellation state is _assumed_ to be PTHREAD_CANCEL_ENABLE and cancellation type is PTHREAD_CANCEL_DEFERRED
*/
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
rc = pthread_create(&thread, &attr, ThreadRun, (void*)this);
switch (rc)
{
case EAGAIN:
lasterr = "Out of system resources.";
break;
case EINVAL:
lasterr = "Tried to create thread with wrong attributes";
break;
case EPERM:
lasterr = "No permission to create thread";
break;
case 0:
lasterr = NULL;
running = true;
created = true;
break;
default:
lasterr = "Unknown error while creating thread";
break;
}
pthread_attr_destroy(&attr);
}
CS_SHOW_ERROR;
return running;
}
bool csPosixThread::Stop ()
{
if (running)
{
int rc = pthread_cancel (thread);
switch (rc)
{
case ESRCH:
lasterr = "Trying to stop unknown thread";
break;
case 0:
lasterr = NULL;
running = false;
break;
default:
lasterr = "Unknown error while cancelling thread";
break;
}
}
CS_SHOW_ERROR;
return !running;
}
bool csPosixThread::Wait ()
{
if (running)
{
int rc = pthread_join (thread,NULL);
switch (rc)
{
case ESRCH:
lasterr = "Trying to wait for unknown thread";
break;
case 0:
lasterr = NULL;
running = false;
created=false;
break;
default:
// lasterr = "Unknown error while waiting for thread";
lasterr = sys_errlist[errno];
break;
}
}
CS_SHOW_ERROR;
return !running;
}
bool csPosixThread::Kill ()
{
if (running)
{
int rc;
rc = pthread_kill (thread, SIGKILL);
switch (rc)
{
case ESRCH:
lasterr = "Thread does not exist";
created = false;
break;
case EINVAL:
lasterr = "Unknown signal sent to thread";
break;
case 0:
lasterr = NULL;
running = false;
break;
default:
lasterr = "Unknown error while killing thread";;
break;
}
}
CS_SHOW_ERROR;
return !running;
}
const char *csPosixThread::GetLastError ()
{
return lasterr;
}
void* csPosixThread::ThreadRun (void *param)
{
csPosixThread *thread = (csPosixThread *)param;
thread->runnable->Run ();
thread->running = false;
pthread_exit (NULL);
}
#undef CS_SHOW_ERROR
<|endoftext|> |
<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 "testapplet.h"
#include "testwidget.h"
#include "testbrief.h"
#include <MTheme>
#include <MAction>
#undef DEBUG
#include "../debug.h"
Q_EXPORT_PLUGIN2(testapplet, TestApplet)
TestApplet::TestApplet()
{
}
TestApplet::~TestApplet()
{
}
void
TestApplet::init()
{
//MTheme::loadCSS(cssDir + "themeapplet.css");
}
DcpWidget *
TestApplet::pageMain(
int Id)
{
static int i = 0;
SYS_DEBUG ("Entering %dnth times for id %d", i, Id);
++i;
switch (Id) {
case 0:
if (m_MainWidget == NULL) {
m_MainWidget = new TestWidget (Id);
SYS_DEBUG ("Widget created");
}
return m_MainWidget;
case 1:
if (m_Page1 == NULL) {
m_Page1 = new TestWidget (Id);
SYS_DEBUG ("Widget created");
}
return m_Page1;
case 2:
if (m_Page2 == NULL) {
m_Page2 = new TestWidget (Id);
SYS_DEBUG ("Widget created");
}
return m_Page2;
case 3:
if (m_Page3 == NULL) {
m_Page3 = new TestWidget (Id);
SYS_DEBUG ("Widget created");
}
return m_Page3;
case 4:
if (m_Page4 == NULL) {
m_Page4 = new TestWidget (Id);
SYS_DEBUG ("Widget created");
}
return m_Page4;
case 5:
if (m_Page5 == NULL) {
m_Page5 = new TestWidget (Id);
SYS_DEBUG ("Widget created");
}
return m_Page5;
default:
SYS_WARNING ("Invalid Id: %d", Id);
Q_ASSERT (false);
}
return m_MainWidget;
}
DcpWidget *
TestApplet::constructWidget (
int widgetId)
{
Q_ASSERT (widgetId >= 0);
Q_ASSERT (widgetId <= 5);
SYS_DEBUG ("-----------------------------------");
SYS_DEBUG ("*** widgetId = %d", widgetId);
if (widgetId == 0 && m_MainWidget != 0) {
SYS_WARNING ("m_MainWidget already exists!");
} else if (widgetId == 1 && m_Page1 != 0) {
SYS_WARNING ("m_Page1 already exists");
} else if (widgetId == 2 && m_Page2 != 0) {
SYS_WARNING ("m_Page2 already exists");
} else if (widgetId == 3 && m_Page3 != 0) {
SYS_WARNING ("m_Page3 already exists");
} else if (widgetId == 4 && m_Page4 != 0) {
SYS_WARNING ("m_Page4 already exists");
} else if (widgetId == 5 && m_Page5 != 0) {
SYS_WARNING ("m_Page5 already exists");
}
return pageMain (widgetId);
}
QString
TestApplet::title() const
{
//% "Test"
return qtTrId ("qtn_test_test"); // This is not official logical id
}
QVector<MAction*>
TestApplet::viewMenuItems()
{
QVector<MAction*> vector;
//% "User guide"
MAction* helpAction = new MAction (qtTrId ("qtn_comm_userguide"),
pageMain (0));
vector.append(helpAction);
helpAction->setLocation(MAction::ApplicationMenuLocation);
return vector;
}
DcpBrief *
TestApplet::constructBrief (
int partId)
{
Q_UNUSED (partId);
return new TestBrief ();
}
<commit_msg>Changes: Drop some uncommented code<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 "testapplet.h"
#include "testwidget.h"
#include "testbrief.h"
#include <MAction>
#undef DEBUG
#include "../debug.h"
Q_EXPORT_PLUGIN2(testapplet, TestApplet)
TestApplet::TestApplet()
{
}
TestApplet::~TestApplet()
{
}
void
TestApplet::init()
{
}
DcpWidget *
TestApplet::pageMain(
int Id)
{
static int i = 0;
SYS_DEBUG ("Entering %dnth times for id %d", i, Id);
++i;
switch (Id) {
case 0:
if (m_MainWidget == NULL) {
m_MainWidget = new TestWidget (Id);
SYS_DEBUG ("Widget created");
}
return m_MainWidget;
case 1:
if (m_Page1 == NULL) {
m_Page1 = new TestWidget (Id);
SYS_DEBUG ("Widget created");
}
return m_Page1;
case 2:
if (m_Page2 == NULL) {
m_Page2 = new TestWidget (Id);
SYS_DEBUG ("Widget created");
}
return m_Page2;
case 3:
if (m_Page3 == NULL) {
m_Page3 = new TestWidget (Id);
SYS_DEBUG ("Widget created");
}
return m_Page3;
case 4:
if (m_Page4 == NULL) {
m_Page4 = new TestWidget (Id);
SYS_DEBUG ("Widget created");
}
return m_Page4;
case 5:
if (m_Page5 == NULL) {
m_Page5 = new TestWidget (Id);
SYS_DEBUG ("Widget created");
}
return m_Page5;
default:
SYS_WARNING ("Invalid Id: %d", Id);
Q_ASSERT (false);
}
return m_MainWidget;
}
DcpWidget *
TestApplet::constructWidget (
int widgetId)
{
Q_ASSERT (widgetId >= 0);
Q_ASSERT (widgetId <= 5);
SYS_DEBUG ("-----------------------------------");
SYS_DEBUG ("*** widgetId = %d", widgetId);
if (widgetId == 0 && m_MainWidget != 0) {
SYS_WARNING ("m_MainWidget already exists!");
} else if (widgetId == 1 && m_Page1 != 0) {
SYS_WARNING ("m_Page1 already exists");
} else if (widgetId == 2 && m_Page2 != 0) {
SYS_WARNING ("m_Page2 already exists");
} else if (widgetId == 3 && m_Page3 != 0) {
SYS_WARNING ("m_Page3 already exists");
} else if (widgetId == 4 && m_Page4 != 0) {
SYS_WARNING ("m_Page4 already exists");
} else if (widgetId == 5 && m_Page5 != 0) {
SYS_WARNING ("m_Page5 already exists");
}
return pageMain (widgetId);
}
QString
TestApplet::title() const
{
//% "Test"
return qtTrId ("qtn_test_test"); // This is not official logical id
}
QVector<MAction*>
TestApplet::viewMenuItems()
{
QVector<MAction*> vector;
//% "User guide"
MAction* helpAction = new MAction (qtTrId ("qtn_comm_userguide"),
pageMain (0));
vector.append(helpAction);
helpAction->setLocation(MAction::ApplicationMenuLocation);
return vector;
}
DcpBrief *
TestApplet::constructBrief (
int partId)
{
Q_UNUSED (partId);
return new TestBrief ();
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.