commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
2723bb855450ec4a3181fc43ba0b890eed10187d
|
src/TEMUtilityFunctions.cpp
|
src/TEMUtilityFunctions.cpp
|
//
// TEMUtilityFunctions.cpp
// dvm-dos-tem
//
// Created by Tobey Carman on 4/10/14.
// Copyright (c) 2014 Spatial Ecology Lab. All rights reserved.
//
#include <string>
#include <stdexcept>
#include <fstream>
#include <cerrno>
#include <netcdfcpp.h>
#include <json/reader.h>
#include <json/value.h>
#include "TEMLogger.h"
#include "TEMUtilityFunctions.h"
extern src::severity_logger< severity_level > glg;
namespace temutil {
/** Returns true for 'on' and false for 'off'.
* Throws exception if s is not "on" or "off".
* might want to inherit from std exception or do something else?
*/
bool onoffstr2bool(const std::string &s) {
if (s.compare("on") == 0) {
return true;
} else if (s.compare("off") == 0) {
return false;
} else {
throw std::runtime_error("Invalid string! Must be 'on' or 'off'.");
}
}
/** Read a file into a string. Return the string.
* Throws exceptions if there is an error reading the file. Poached from:
* http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html
*/
std::string file2string(const char *filename) {
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in) {
std::string contents;
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
return(contents);
}
throw(errno);
}
/** Reads a json foramtted "control file", returning a json data object.
*/
Json::Value parse_control_file(const std::string &filepath) {
BOOST_LOG_SEV(glg, debug) << "Read the control file ('" << filepath << "') into a string...";
std::string datastring = file2string(filepath.c_str());
BOOST_LOG_SEV(glg, debug) << "Creating Json Value and Reader objects...";
Json::Value root; // will contain the root value after parsing
Json::Reader reader;
BOOST_LOG_SEV(glg, debug) << "Trying to parse the json data string...";
bool parsingSuccessful = reader.parse( datastring, root );
BOOST_LOG_SEV(glg, debug) << "Parsing successful?: " << parsingSuccessful;
if ( !parsingSuccessful ) {
BOOST_LOG_SEV(glg, fatal) << "Failed to parse configuration file! "
<< reader.getFormatedErrorMessages();
exit(-1);
}
return root;
}
/** Opens a netcdf file for reading, returns NcFile object.
*
* NetCDF library error mode in set to silent (no printing to std::out), and
* non-fatal.
* If the file open fails, it logs a message and exits the program with a
* non-zero exit code.
*/
NcFile open_ncfile(std::string filename) {
NcError err(NcError::silent_nonfatal);
BOOST_LOG_SEV(glg, info) << "Opening NetCDF file: " << filename;
NcFile file(filename.c_str(), NcFile::ReadOnly);
if( !file.is_valid() ) {
BOOST_LOG_SEV(glg, fatal) << "Problem opening/reading " << filename;
exit(-1);
}
return file;
}
/** Given an NcFile object and dimension name, reutrns a pointer to the NcDim.
*
* If the dimension-read is not valid, then an error message is logged and
* the program exits with a non-zero status.
*/
NcDim* get_ncdim(const NcFile& file, std::string dimname) {
NcDim* dim = file.get_dim(dimname.c_str());
if ( !dim->is_valid() ) {
BOOST_LOG_SEV(glg, fatal) << "Problem with '" << dimname << "' out of NetCDF file.";
exit(-1);
}
return dim;
}
}
|
//
// TEMUtilityFunctions.cpp
// dvm-dos-tem
//
// Created by Tobey Carman on 4/10/14.
// Copyright (c) 2014 Spatial Ecology Lab. All rights reserved.
//
#include <string>
#include <stdexcept>
#include <fstream>
#include <cerrno>
#include <netcdfcpp.h>
#include <json/reader.h>
#include <json/value.h>
#include "TEMLogger.h"
#include "TEMUtilityFunctions.h"
extern src::severity_logger< severity_level > glg;
namespace temutil {
/** Returns true for 'on' and false for 'off'.
* Throws exception if s is not "on" or "off".
* might want to inherit from std exception or do something else?
*/
bool onoffstr2bool(const std::string &s) {
if (s.compare("on") == 0) {
return true;
} else if (s.compare("off") == 0) {
return false;
} else {
throw std::runtime_error("Invalid string! Must be 'on' or 'off'.");
}
}
/** Read a file into a string. Return the string.
* Throws exceptions if there is an error reading the file. Poached from:
* http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html
*/
std::string file2string(const char *filename) {
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in) {
std::string contents;
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
return(contents);
}
throw(errno);
}
/** Reads a json foramtted "control file", returning a json data object.
*/
Json::Value parse_control_file(const std::string &filepath) {
BOOST_LOG_SEV(glg, debug) << "Read the control file ('" << filepath << "') into a string...";
std::string datastring = file2string(filepath.c_str());
BOOST_LOG_SEV(glg, debug) << "Creating Json Value and Reader objects...";
Json::Value root; // will contain the root value after parsing
Json::Reader reader;
BOOST_LOG_SEV(glg, debug) << "Trying to parse the json data string...";
bool parsingSuccessful = reader.parse( datastring, root );
BOOST_LOG_SEV(glg, debug) << "Parsing successful?: " << parsingSuccessful;
if ( !parsingSuccessful ) {
BOOST_LOG_SEV(glg, fatal) << "Failed to parse configuration file! "
<< reader.getFormatedErrorMessages();
exit(-1);
}
return root;
}
/** Opens a netcdf file for reading, returns NcFile object.
*
* NetCDF library error mode is set to silent (no printing to std::out), and
* non-fatal. If the file open fails, it logs a message and exits the program
* with a non-zero exit code.
*/
NcFile open_ncfile(std::string filename) {
BOOST_LOG_SEV(glg, info) << "Opening NetCDF file: " << filename;
NcError err(NcError::silent_nonfatal);
NcFile file(filename.c_str(), NcFile::ReadOnly);
if( !file.is_valid() ) {
BOOST_LOG_SEV(glg, fatal) << "Problem opening/reading " << filename;
exit(-1);
}
return file;
}
/** Given an NcFile object and dimension name, reutrns a pointer to the NcDim.
*
* If the dimension-read is not valid, then an error message is logged and
* the program exits with a non-zero status.
*/
NcDim* get_ncdim(const NcFile& file, std::string dimname) {
BOOST_LOG_SEV(glg, debug) << "Looking for dimension '" << dimname << "' in NetCDF file...";
NcDim* dim = file.get_dim(dimname.c_str());
BOOST_LOG_SEV(glg, debug) << "'" << dimname <<"' is valid?: " << dim->is_valid();
if ( !dim->is_valid() ) {
BOOST_LOG_SEV(glg, fatal) << "Problem with '" << dimname << "' in NetCDF file.";
exit(-1);
}
return dim;
}
}
|
fix comments and log messages in utility functions.
|
fix comments and log messages in utility functions.
|
C++
|
mit
|
tobeycarman/dvm-dos-tem,tobeycarman/dvm-dos-tem,tobeycarman/dvm-dos-tem,tobeycarman/dvm-dos-tem,tobeycarman/dvm-dos-tem,tobeycarman/dvm-dos-tem
|
623fe43afda448cd673daea79eec68ff0a61c9a5
|
Siv3D/src/Siv3D-Platform/WindowsDesktop/Siv3D/MessageBox/SivMessageBox_Windows.cpp
|
Siv3D/src/Siv3D-Platform/WindowsDesktop/Siv3D/MessageBox/SivMessageBox_Windows.cpp
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2021 Ryo Suzuki
// Copyright (c) 2016-2021 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/MessageBox.hpp>
# include <Siv3D/AsyncTask.hpp>
# include <Siv3D/Window.hpp>
# include <Siv3D/Windows/Windows.hpp>
namespace s3d
{
namespace detail
{
static constexpr int32 MessageBoxStyleFlags[5] =
{
0,
MB_ICONINFORMATION,
MB_ICONWARNING,
MB_ICONERROR,
MB_ICONQUESTION,
};
static MessageBoxResult ShowMessageBox(const StringView title, const StringView text, const MessageBoxStyle style, const int32 buttons)
{
if (Window::GetState().fullscreen)
{
return MessageBoxResult::Cancel;
}
const int32 flag = (MessageBoxStyleFlags[static_cast<int32>(style)] | buttons);
const int32 result = Async([=]()
{
return ::MessageBoxW(nullptr, text.toWstr().c_str(), title.toWstr().c_str(), flag);
}).get();
switch (result)
{
case IDOK:
return MessageBoxResult::OK;
case IDCANCEL:
default:
return MessageBoxResult::Cancel;
case IDYES:
return MessageBoxResult::Yes;
case IDNO:
return MessageBoxResult::No;
}
}
}
namespace System
{
MessageBoxResult MessageBoxOK(const StringView title, const StringView text, const MessageBoxStyle style)
{
return detail::ShowMessageBox(title, text, style, MB_OK);
}
MessageBoxResult MessageBoxOKCancel(const StringView title, const StringView text, const MessageBoxStyle style)
{
return detail::ShowMessageBox(title, text, style, MB_OKCANCEL);
}
MessageBoxResult MessageBoxYesNo(const StringView title, const StringView text, const MessageBoxStyle style)
{
return detail::ShowMessageBox(title, text, style, MB_YESNO);
}
}
}
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2021 Ryo Suzuki
// Copyright (c) 2016-2021 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/MessageBox.hpp>
# include <Siv3D/AsyncTask.hpp>
# include <Siv3D/Window.hpp>
# include <Siv3D/Windows/Windows.hpp>
# include <Siv3D/Window/IWindow.hpp>
# include <Siv3D/Common/Siv3DEngine.hpp>
namespace s3d
{
namespace detail
{
static constexpr int32 MessageBoxStyleFlags[5] =
{
0,
MB_ICONINFORMATION,
MB_ICONWARNING,
MB_ICONERROR,
MB_ICONQUESTION,
};
static MessageBoxResult ShowMessageBox(const StringView title, const StringView text, const MessageBoxStyle style, const int32 buttons)
{
if (Window::GetState().fullscreen)
{
return MessageBoxResult::Cancel;
}
const int32 flag = (MessageBoxStyleFlags[static_cast<int32>(style)] | buttons);
const int32 result = Async([=]()
{
const HWND hWnd = static_cast<HWND>(SIV3D_ENGINE(Window)->getHandle());
return ::MessageBoxW(hWnd, text.toWstr().c_str(), title.toWstr().c_str(), flag);
}).get();
switch (result)
{
case IDOK:
return MessageBoxResult::OK;
case IDCANCEL:
default:
return MessageBoxResult::Cancel;
case IDYES:
return MessageBoxResult::Yes;
case IDNO:
return MessageBoxResult::No;
}
}
}
namespace System
{
MessageBoxResult MessageBoxOK(const StringView title, const StringView text, const MessageBoxStyle style)
{
return detail::ShowMessageBox(title, text, style, MB_OK);
}
MessageBoxResult MessageBoxOKCancel(const StringView title, const StringView text, const MessageBoxStyle style)
{
return detail::ShowMessageBox(title, text, style, MB_OKCANCEL);
}
MessageBoxResult MessageBoxYesNo(const StringView title, const StringView text, const MessageBoxStyle style)
{
return detail::ShowMessageBox(title, text, style, MB_YESNO);
}
}
}
|
fix #706
|
[Windows] fix #706
|
C++
|
mit
|
Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D
|
5519059009749a0357e95751cdde3b00d1f7f2b3
|
modules/gui/qt4/components/epg/EPGView.cpp
|
modules/gui/qt4/components/epg/EPGView.cpp
|
/*****************************************************************************
* EPGView.cpp: EPGView
****************************************************************************
* Copyright © 2009-2010 VideoLAN
* $Id$
*
* Authors: Ludovic Fauvet <[email protected]>
*
* 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 "EPGView.hpp"
#include "EPGItem.hpp"
#include <QDateTime>
#include <QMatrix>
#include <QtDebug>
EPGView::EPGView( QWidget *parent ) : QGraphicsView( parent )
{
setContentsMargins( 0, 0, 0, 0 );
setFrameStyle( QFrame::NoFrame );
setAlignment( Qt::AlignLeft | Qt::AlignTop );
m_startTime = QDateTime::currentDateTime();
//tmp
setSceneRect( 0, 0, 20000, 200 );
QGraphicsScene *EPGscene = new QGraphicsScene( this );
setScene( EPGscene );
}
void EPGView::setScale( double scaleFactor )
{
m_scaleFactor = scaleFactor;
QMatrix matrix;
matrix.scale( scaleFactor, 1 );
setMatrix( matrix );
}
void EPGView::setStartTime( const QDateTime& startTime )
{
QList<QGraphicsItem*> itemList = items();
int diff = startTime.secsTo( m_startTime );
for ( int i = 0; i < itemList.count(); ++i )
{
EPGItem* item = static_cast<EPGItem*>( itemList.at( i ) );
item->setStart( item->start().addSecs( diff ) );
}
m_startTime = startTime;
// Our start time has changed
emit startTimeChanged( startTime );
}
const QDateTime& EPGView::startTime()
{
return m_startTime;
}
void EPGView::addEvent( EPGEvent* event )
{
if ( !m_channels.contains( event->channelName ) )
m_channels.append( event->channelName );
EPGItem* item = new EPGItem( this );
item->setChannel( m_channels.indexOf( event->channelName ) );
item->setStart( event->start );
item->setDuration( event->duration );
item->setName( event->name );
item->setDescription( event->description );
item->setShortDescription( event->shortDescription );
item->setCurrent( event->current );
scene()->addItem( item );
}
void EPGView::updateEvent( EPGEvent* event )
{
//qDebug() << "Update event: " << event->name;
}
void EPGView::delEvent( EPGEvent* event )
{
//qDebug() << "Del event: " << event->name;
}
void EPGView::drawBackground( QPainter *painter, const QRectF &rect )
{
painter->setPen( QPen( QColor( 72, 72, 72 ) ) );
QPointF p = mapToScene( width(), 0 );
int y = 0;
for ( int i = 0; i < m_channels.count() + 1; ++i )
{
painter->drawLine( 0,
y * TRACKS_HEIGHT,
p.x(),
y * TRACKS_HEIGHT );
++y;
}
}
void EPGView::updateDuration()
{
QDateTime lastItem;
QList<QGraphicsItem*> list = items();
for ( int i = 0; i < list.count(); ++i )
{
EPGItem* item = static_cast<EPGItem*>( list.at( i ) );
QDateTime itemEnd = item->start().addSecs( item->duration() );
if ( itemEnd > lastItem )
lastItem = itemEnd;
}
m_duration = m_startTime.secsTo( lastItem );
emit durationChanged( m_duration );
}
void EPGView::eventFocused( EPGEvent *ev )
{
emit eventFocusedChanged( ev );
}
|
/*****************************************************************************
* EPGView.cpp: EPGView
****************************************************************************
* Copyright © 2009-2010 VideoLAN
* $Id$
*
* Authors: Ludovic Fauvet <[email protected]>
*
* 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 "EPGView.hpp"
#include "EPGItem.hpp"
#include <QDateTime>
#include <QMatrix>
#include <QtDebug>
EPGView::EPGView( QWidget *parent ) : QGraphicsView( parent )
{
setContentsMargins( 0, 0, 0, 0 );
setFrameStyle( QFrame::NoFrame );
setAlignment( Qt::AlignLeft | Qt::AlignTop );
m_startTime = QDateTime::currentDateTime();
QGraphicsScene *EPGscene = new QGraphicsScene( this );
setScene( EPGscene );
}
void EPGView::setScale( double scaleFactor )
{
m_scaleFactor = scaleFactor;
QMatrix matrix;
matrix.scale( scaleFactor, 1 );
setMatrix( matrix );
}
void EPGView::setStartTime( const QDateTime& startTime )
{
QList<QGraphicsItem*> itemList = items();
int diff = startTime.secsTo( m_startTime );
for ( int i = 0; i < itemList.count(); ++i )
{
EPGItem* item = static_cast<EPGItem*>( itemList.at( i ) );
item->setStart( item->start().addSecs( diff ) );
}
m_startTime = startTime;
// Our start time has changed
emit startTimeChanged( startTime );
}
const QDateTime& EPGView::startTime()
{
return m_startTime;
}
void EPGView::addEvent( EPGEvent* event )
{
if ( !m_channels.contains( event->channelName ) )
m_channels.append( event->channelName );
EPGItem* item = new EPGItem( this );
item->setChannel( m_channels.indexOf( event->channelName ) );
item->setStart( event->start );
item->setDuration( event->duration );
item->setName( event->name );
item->setDescription( event->description );
item->setShortDescription( event->shortDescription );
item->setCurrent( event->current );
scene()->addItem( item );
}
void EPGView::updateEvent( EPGEvent* event )
{
//qDebug() << "Update event: " << event->name;
}
void EPGView::delEvent( EPGEvent* event )
{
//qDebug() << "Del event: " << event->name;
}
void EPGView::drawBackground( QPainter *painter, const QRectF &rect )
{
painter->setPen( QPen( QColor( 72, 72, 72 ) ) );
QPointF p = mapToScene( width(), 0 );
int y = 0;
for ( int i = 0; i < m_channels.count() + 1; ++i )
{
painter->drawLine( 0,
y * TRACKS_HEIGHT,
p.x(),
y * TRACKS_HEIGHT );
++y;
}
}
void EPGView::updateDuration()
{
QDateTime lastItem;
QList<QGraphicsItem*> list = items();
for ( int i = 0; i < list.count(); ++i )
{
EPGItem* item = static_cast<EPGItem*>( list.at( i ) );
QDateTime itemEnd = item->start().addSecs( item->duration() );
if ( itemEnd > lastItem )
lastItem = itemEnd;
}
m_duration = m_startTime.secsTo( lastItem );
emit durationChanged( m_duration );
}
void EPGView::eventFocused( EPGEvent *ev )
{
emit eventFocusedChanged( ev );
}
|
remove debug in epg
|
epg: remove debug in epg
Signed-off-by: Jean-Baptiste Kempf <[email protected]>
|
C++
|
lgpl-2.1
|
jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.2,krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,krichter722/vlc,krichter722/vlc,krichter722/vlc,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,krichter722/vlc,xkfz007/vlc,xkfz007/vlc,xkfz007/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,xkfz007/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,krichter722/vlc,shyamalschandra/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2
|
25c4c0ab46b46c8968c69f22101edb74b089c5de
|
tests/kdb/testkdb_allplugins.cpp
|
tests/kdb/testkdb_allplugins.cpp
|
/**
* @file
*
* @brief Tests for the Backend builder class
*
* @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*
*/
#define ELEKTRA_PLUGINSPEC_WITH_COMPARE
#include <backend.hpp>
#include <backends.hpp>
#include <plugindatabase.hpp>
#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
#include <gtest/gtest.h>
#include <kdb.hpp>
std::vector<std::string> getAllPlugins ()
{
using namespace kdb;
using namespace kdb::tools;
ModulesPluginDatabase mpd;
std::vector<std::string> plugins = mpd.listAllPlugins ();
// remove known problems
plugins.erase (std::remove (plugins.begin (), plugins.end (), "jni"), plugins.end ());
plugins.erase (std::remove (plugins.begin (), plugins.end (), "crypto_gcrypt"), plugins.end ());
return plugins;
}
class AllPlugins : public ::testing::TestWithParam<std::string>
{
protected:
};
TEST_P (AllPlugins, backend)
{
using namespace kdb;
using namespace kdb::tools;
std::string p = GetParam ();
std::cout << p << std::endl;
try
{
Backend b;
b.addPlugin (PluginSpec (p));
}
catch (std::exception const & e)
{
EXPECT_TRUE (true) << p;
}
}
TEST_P (AllPlugins, modules)
{
using namespace kdb;
using namespace kdb::tools;
std::string p = GetParam ();
std::cout << p << std::endl;
try
{
Modules m;
m.load (p);
}
catch (std::exception const & e)
{
EXPECT_TRUE (true) << p;
}
}
INSTANTIATE_TEST_CASE_P (AllPlugins, AllPlugins, testing::ValuesIn (getAllPlugins ()));
|
/**
* @file
*
* @brief Tests for the Backend builder class
*
* @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*
*/
#define ELEKTRA_PLUGINSPEC_WITH_COMPARE
#include <backend.hpp>
#include <backends.hpp>
#include <plugindatabase.hpp>
#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
#include <gtest/gtest.h>
#include <kdb.hpp>
std::vector<std::string> getAllPlugins ()
{
using namespace kdb;
using namespace kdb::tools;
ModulesPluginDatabase mpd;
std::vector<std::string> plugins = mpd.listAllPlugins ();
// remove known problems
plugins.erase (std::remove (plugins.begin (), plugins.end (), "jni"), plugins.end ());
plugins.erase (std::remove (plugins.begin (), plugins.end (), "semlock"), plugins.end ());
plugins.erase (std::remove (plugins.begin (), plugins.end (), "crypto_gcrypt"), plugins.end ());
return plugins;
}
class AllPlugins : public ::testing::TestWithParam<std::string>
{
protected:
};
TEST_P (AllPlugins, backend)
{
using namespace kdb;
using namespace kdb::tools;
std::string p = GetParam ();
std::cout << p << std::endl;
try
{
Backend b;
b.addPlugin (PluginSpec (p));
}
catch (std::exception const & e)
{
EXPECT_TRUE (true) << p;
}
}
TEST_P (AllPlugins, modules)
{
using namespace kdb;
using namespace kdb::tools;
std::string p = GetParam ();
std::cout << p << std::endl;
try
{
Modules m;
m.load (p);
}
catch (std::exception const & e)
{
EXPECT_TRUE (true) << p;
}
}
INSTANTIATE_TEST_CASE_P (AllPlugins, AllPlugins, testing::ValuesIn (getAllPlugins ()));
|
exclude semlock from shared memtests
|
exclude semlock from shared memtests
|
C++
|
bsd-3-clause
|
mpranj/libelektra,BernhardDenner/libelektra,BernhardDenner/libelektra,BernhardDenner/libelektra,e1528532/libelektra,petermax2/libelektra,petermax2/libelektra,e1528532/libelektra,e1528532/libelektra,mpranj/libelektra,BernhardDenner/libelektra,petermax2/libelektra,petermax2/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,BernhardDenner/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,BernhardDenner/libelektra,petermax2/libelektra,petermax2/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,mpranj/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,ElektraInitiative/libelektra,BernhardDenner/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,e1528532/libelektra,BernhardDenner/libelektra,mpranj/libelektra,e1528532/libelektra,mpranj/libelektra,BernhardDenner/libelektra,mpranj/libelektra,e1528532/libelektra
|
e9e9a6033ad7ce2690e510932cc8074909cfef7b
|
src/osvr/Client/VRPNContext.cpp
|
src/osvr/Client/VRPNContext.cpp
|
/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<[email protected]>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include "VRPNContext.h"
#include "display_json.h"
#include "RouterPredicates.h"
#include "RouterTransforms.h"
#include "VRPNAnalogRouter.h"
#include "VRPNButtonRouter.h"
#include "VRPNTrackerRouter.h"
#include <osvr/Util/ClientCallbackTypesC.h>
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/ClientInterface.h>
#include <osvr/Util/Verbosity.h>
#include <osvr/Transform/JSONTransformVisitor.h>
#include <osvr/Transform/ChangeOfBasis.h>
#include <osvr/Util/MessageKeys.h>
// Library/third-party includes
#include <json/value.h>
#include <json/reader.h>
// Standard includes
#include <cstring>
namespace osvr {
namespace client {
RouterEntry::~RouterEntry() {}
static inline transform::Transform getTransform(const char *data,
size_t len) {
std::string json(data, len);
Json::Value root;
Json::Reader reader;
if (!reader.parse(json, root)) {
throw std::runtime_error("JSON parse error: " +
reader.getFormattedErrorMessages());
}
transform::JSONTransformVisitor xform(root);
return xform.getTransform();
}
VRPNContext::VRPNContext(const char appId[], const char host[])
: ::OSVR_ClientContextObject(appId), m_host(host) {
std::string contextDevice =
std::string(util::messagekeys::systemSender()) + "@" + m_host;
/// Get connection, forcing a re-open for improved thread-safety.
m_conn =
vrpn_get_connection_by_name(contextDevice.c_str(), nullptr, nullptr,
nullptr, nullptr, nullptr, true);
setParameter("/display",
std::string(reinterpret_cast<char *>(display_json),
display_json_len));
m_conn->register_handler(
m_conn->register_message_type(util::messagekeys::routingData()),
&VRPNContext::m_handleRoutingMessage, static_cast<void *>(this));
}
VRPNContext::~VRPNContext() {}
int VRPNContext::m_handleRoutingMessage(void *userdata,
vrpn_HANDLERPARAM p) {
VRPNContext *self = static_cast<VRPNContext *>(userdata);
self->m_replaceRoutes(std::string(p.buffer, p.payload_len));
return 0;
}
static const char SOURCE_KEY[] = "source";
static const char DESTINATION_KEY[] = "destination";
static const char SENSOR_KEY[] = "sensor";
static const char TRACKER_KEY[] = "tracker";
void VRPNContext::m_replaceRoutes(std::string const &routes) {
Json::Value root;
Json::Reader reader;
if (!reader.parse(routes, root)) {
throw std::runtime_error("JSON parse error: " +
reader.getFormattedErrorMessages());
}
OSVR_DEV_VERBOSE("Replacing routes: had "
<< m_routers.size() << ", received " << root.size());
m_routers.clear();
for (Json::ArrayIndex i = 0, e = root.size(); i < e; ++i) {
Json::Value route = root[i];
std::string dest = route[DESTINATION_KEY].asString();
boost::optional<int> sensor;
transform::JSONTransformVisitor xformParse(route[SOURCE_KEY]);
Json::Value srcLeaf = xformParse.getLeaf();
std::string srcDevice = srcLeaf[TRACKER_KEY].asString();
// OSVR_DEV_VERBOSE("Source device: " << srcDevice);
srcDevice.erase(begin(srcDevice)); // remove leading slash
if (srcLeaf.isMember(SENSOR_KEY)) {
sensor = srcLeaf[SENSOR_KEY].asInt();
}
m_addTrackerRouter(srcDevice.c_str(), dest.c_str(), sensor,
xformParse.getTransform());
}
#define OSVR_HYDRA_BUTTON(SENSOR, NAME) \
m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/left/" NAME, SensorPredicate(SENSOR)); \
m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/right/" NAME, SensorPredicate(SENSOR + 8))
OSVR_HYDRA_BUTTON(0, "middle");
OSVR_HYDRA_BUTTON(1, "1");
OSVR_HYDRA_BUTTON(2, "2");
OSVR_HYDRA_BUTTON(3, "3");
OSVR_HYDRA_BUTTON(4, "4");
OSVR_HYDRA_BUTTON(5, "bumper");
OSVR_HYDRA_BUTTON(6, "joystick/button");
#undef OSVR_HYDRA_BUTTON
#define OSVR_HYDRA_ANALOG(SENSOR, NAME) \
m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/left/" NAME, SENSOR); \
m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/right/" NAME, SENSOR + 3)
OSVR_HYDRA_ANALOG(0, "joystick/x");
OSVR_HYDRA_ANALOG(1, "joystick/y");
OSVR_HYDRA_ANALOG(2, "trigger");
#undef OSVR_HYDRA_ANALOG
OSVR_DEV_VERBOSE("Now have " << m_routers.size() << " routes.");
}
void VRPNContext::m_update() {
// mainloop the VRPN connection.
m_conn->mainloop();
// Process each of the routers.
for (auto const &p : m_routers) {
(*p)();
}
}
void VRPNContext::m_addAnalogRouter(const char *src, const char *dest,
int channel) {
OSVR_DEV_VERBOSE("Adding analog route for " << dest);
m_routers.emplace_back(
new VRPNAnalogRouter<SensorPredicate, NullTransform>(
this, m_conn.get(), src, dest, SensorPredicate(channel),
NullTransform(), channel));
}
template <typename Predicate>
void VRPNContext::m_addButtonRouter(const char *src, const char *dest,
Predicate pred) {
OSVR_DEV_VERBOSE("Adding button route for " << dest);
m_routers.emplace_back(new VRPNButtonRouter<Predicate>(
this, m_conn.get(), src, dest, pred));
}
void VRPNContext::m_addTrackerRouter(const char *src, const char *dest,
boost::optional<int> sensor,
transform::Transform const &xform) {
OSVR_DEV_VERBOSE("Adding tracker route for " << dest);
std::string source(src);
if (std::string::npos != source.find('@')) {
// We found an @ - so this is a device we need a new connection for.
m_routers.emplace_back(
new VRPNTrackerRouter(this, nullptr, src, sensor, dest, xform));
} else {
// No @: assume to be at the same location as the context.
m_routers.emplace_back(new VRPNTrackerRouter(
this, m_conn.get(), src, sensor, dest, xform));
}
}
} // namespace client
} // namespace osvr
|
/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<[email protected]>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include "VRPNContext.h"
#include "display_json.h"
#include "RouterPredicates.h"
#include "RouterTransforms.h"
#include "VRPNAnalogRouter.h"
#include "VRPNButtonRouter.h"
#include "VRPNTrackerRouter.h"
#include <osvr/Util/ClientCallbackTypesC.h>
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/ClientInterface.h>
#include <osvr/Util/Verbosity.h>
#include <osvr/Transform/JSONTransformVisitor.h>
#include <osvr/Transform/ChangeOfBasis.h>
#include <osvr/Util/MessageKeys.h>
// Library/third-party includes
#include <json/value.h>
#include <json/reader.h>
// Standard includes
#include <cstring>
namespace osvr {
namespace client {
RouterEntry::~RouterEntry() {}
static inline transform::Transform getTransform(const char *data,
size_t len) {
std::string json(data, len);
Json::Value root;
Json::Reader reader;
if (!reader.parse(json, root)) {
throw std::runtime_error("JSON parse error: " +
reader.getFormattedErrorMessages());
}
transform::JSONTransformVisitor xform(root);
return xform.getTransform();
}
VRPNContext::VRPNContext(const char appId[], const char host[])
: ::OSVR_ClientContextObject(appId), m_host(host) {
std::string contextDevice =
std::string(util::messagekeys::systemSender()) + "@" + m_host;
/// Get connection, forcing a re-open for improved thread-safety.
m_conn =
vrpn_get_connection_by_name(contextDevice.c_str(), nullptr, nullptr,
nullptr, nullptr, nullptr, true);
setParameter("/display",
std::string(reinterpret_cast<char *>(display_json),
display_json_len));
m_conn->register_handler(
m_conn->register_message_type(util::messagekeys::routingData()),
&VRPNContext::m_handleRoutingMessage, static_cast<void *>(this));
}
VRPNContext::~VRPNContext() {}
int VRPNContext::m_handleRoutingMessage(void *userdata,
vrpn_HANDLERPARAM p) {
VRPNContext *self = static_cast<VRPNContext *>(userdata);
self->m_replaceRoutes(std::string(p.buffer, p.payload_len));
return 0;
}
static const char SOURCE_KEY[] = "source";
static const char DESTINATION_KEY[] = "destination";
static const char SENSOR_KEY[] = "sensor";
static const char TRACKER_KEY[] = "tracker";
void VRPNContext::m_replaceRoutes(std::string const &routes) {
Json::Value root;
Json::Reader reader;
if (!reader.parse(routes, root)) {
throw std::runtime_error("JSON parse error: " +
reader.getFormattedErrorMessages());
}
OSVR_DEV_VERBOSE("Replacing routes: had "
<< m_routers.size() << ", received " << root.size());
m_routers.clear();
for (Json::ArrayIndex i = 0, e = root.size(); i < e; ++i) {
Json::Value route = root[i];
std::string dest = route[DESTINATION_KEY].asString();
boost::optional<int> sensor;
transform::JSONTransformVisitor xformParse(route[SOURCE_KEY]);
Json::Value srcLeaf = xformParse.getLeaf();
std::string srcDevice = srcLeaf[TRACKER_KEY].asString();
// OSVR_DEV_VERBOSE("Source device: " << srcDevice);
srcDevice.erase(begin(srcDevice)); // remove leading slash
if (srcLeaf.isMember(SENSOR_KEY)) {
sensor = srcLeaf[SENSOR_KEY].asInt();
}
m_addTrackerRouter(srcDevice.c_str(), dest.c_str(), sensor,
xformParse.getTransform());
}
#define OSVR_HYDRA_BUTTON(SENSOR, NAME) \
m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/left/" NAME, SensorPredicate(SENSOR)); \
m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/right/" NAME, SensorPredicate(SENSOR + 8))
OSVR_HYDRA_BUTTON(0, "middle");
OSVR_HYDRA_BUTTON(1, "1");
OSVR_HYDRA_BUTTON(2, "2");
OSVR_HYDRA_BUTTON(3, "3");
OSVR_HYDRA_BUTTON(4, "4");
OSVR_HYDRA_BUTTON(5, "bumper");
OSVR_HYDRA_BUTTON(6, "joystick/button");
#undef OSVR_HYDRA_BUTTON
#define OSVR_HYDRA_ANALOG(SENSOR, NAME) \
m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/left/" NAME, SENSOR); \
m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/right/" NAME, SENSOR + 3)
OSVR_HYDRA_ANALOG(0, "joystick/x");
OSVR_HYDRA_ANALOG(1, "joystick/y");
OSVR_HYDRA_ANALOG(2, "trigger");
#undef OSVR_HYDRA_ANALOG
OSVR_DEV_VERBOSE("Now have " << m_routers.size() << " routes.");
}
void VRPNContext::m_update() {
// mainloop the VRPN connection.
m_conn->mainloop();
m_client->mainloop();
// Process each of the routers.
for (auto const &p : m_routers) {
(*p)();
}
}
void VRPNContext::m_addAnalogRouter(const char *src, const char *dest,
int channel) {
OSVR_DEV_VERBOSE("Adding analog route for " << dest);
m_routers.emplace_back(
new VRPNAnalogRouter<SensorPredicate, NullTransform>(
this, m_conn.get(), src, dest, SensorPredicate(channel),
NullTransform(), channel));
}
template <typename Predicate>
void VRPNContext::m_addButtonRouter(const char *src, const char *dest,
Predicate pred) {
OSVR_DEV_VERBOSE("Adding button route for " << dest);
m_routers.emplace_back(new VRPNButtonRouter<Predicate>(
this, m_conn.get(), src, dest, pred));
}
void VRPNContext::m_addTrackerRouter(const char *src, const char *dest,
boost::optional<int> sensor,
transform::Transform const &xform) {
OSVR_DEV_VERBOSE("Adding tracker route for " << dest);
std::string source(src);
if (std::string::npos != source.find('@')) {
// We found an @ - so this is a device we need a new connection for.
m_routers.emplace_back(
new VRPNTrackerRouter(this, nullptr, src, sensor, dest, xform));
} else {
// No @: assume to be at the same location as the context.
m_routers.emplace_back(new VRPNTrackerRouter(
this, m_conn.get(), src, sensor, dest, xform));
}
}
} // namespace client
} // namespace osvr
|
Solve the weird message on client shutdown.
|
Solve the weird message on client shutdown.
Conflicts:
src/osvr/Client/VRPNContext.cpp
|
C++
|
apache-2.0
|
godbyk/OSVR-Core,OSVR/OSVR-Core,leemichaelRazer/OSVR-Core,OSVR/OSVR-Core,d235j/OSVR-Core,leemichaelRazer/OSVR-Core,feilen/OSVR-Core,feilen/OSVR-Core,Armada651/OSVR-Core,d235j/OSVR-Core,d235j/OSVR-Core,godbyk/OSVR-Core,leemichaelRazer/OSVR-Core,godbyk/OSVR-Core,OSVR/OSVR-Core,Armada651/OSVR-Core,godbyk/OSVR-Core,d235j/OSVR-Core,OSVR/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,Armada651/OSVR-Core,leemichaelRazer/OSVR-Core,feilen/OSVR-Core,feilen/OSVR-Core,feilen/OSVR-Core,godbyk/OSVR-Core,d235j/OSVR-Core,Armada651/OSVR-Core,OSVR/OSVR-Core,leemichaelRazer/OSVR-Core,Armada651/OSVR-Core
|
e326e99084306ee9ea1c799abd76f2104326a6ce
|
modules/portable/SaveToFile/savetofile.cpp
|
modules/portable/SaveToFile/savetofile.cpp
|
#include "ppasskeeper.h"
#include "tokenizer.h"
#include <string>
#include <iostream>
#include <fstream>
#include <string.h>
#include "ppasskeeper-dir.h"
#define STR_STRING "str :"
#define BLOB_STRING "blob:"
//local functions
std::string shortName();
ppk_error readFile(std::string filename, std::string& filecontent, unsigned int flags);
ppk_error writeFile(std::string filename, std::string secret, unsigned int flags);
//private functions
ppk_error deletePassword(std::string path, unsigned int flags)
{
if(remove(path.c_str())==0)
return PPK_OK;
else
return PPK_FILE_CANNOT_BE_ACCESSED;
}
ppk_boolean fileExists(std::string filepath)
{
std::ifstream inputfile(filepath.c_str());
if(inputfile.is_open())
{
inputfile.close();
return PPK_TRUE;
}
else
return PPK_FALSE;
}
bool string_replace_first(std::string& str, const std::string to_replace, const std::string replaced_by)
{
size_t found=str.find(to_replace);
if (found!=std::string::npos)
{
str=str.replace(found, to_replace.size(), replaced_by);
return true;
}
else
return false;
}
//functions
extern "C"
{
const char* getModuleName();
const int getABIVersion()
{
return 1;
}
ppk_boolean isWritable()
{
return PPK_TRUE;
}
//Get available flags
unsigned int readFlagsAvailable()
{
return ppk_rf_none|ppk_rf_silent;
}
unsigned int writeFlagsAvailable()
{
return ppk_wf_none|ppk_wf_silent;
}
unsigned int listingFlagsAvailable()
{
return ppk_lf_none|ppk_lf_silent;
}
std::string getKey(const ppk_entry* entry)
{
size_t len=ppk_key_length(entry);
char* entry_cstr=new char[len+1];
if(ppk_get_key(entry, entry_cstr, len)==PPK_TRUE)
{
std::string entry_std=entry_cstr;
std::string type_s;
switch(ppk_get_entry_type(entry))
{
case ppk_application:
type_s="APP";
break;
case ppk_network:
type_s="NET";
string_replace_first(entry_std, "://", "¤");
break;
case ppk_item:
type_s="ITM";
break;
}
return setting_dir()+toString("/")+shortName()+"_"+type_s+"_"+entry_std;
}
else
return std::string();
}
#if defined(WIN32) || defined(WIN64)
#include <windows.h>
static std::vector<std::string>& listEntries(const char* dir, unsigned int flags)
{
WIN32_FIND_DATA File;
HANDLE hSearch;
unsigned int pwdCount=0;
std::vector<std::string> entries;
std::string path;
char* tmp=getenv("HOMEDRIVE");
if(tmp!=NULL)
{
path=tmp;
tmp=getenv("HOMEPATH");
if(tmp!=NULL)
{
path+=tmp;
hSearch = FindFirstFile((path+"\\ppasskeeper\\*").c_str(), &File);
if (hSearch != INVALID_HANDLE_VALUE)
{
do {
entries.push_back(File.cFileName);
} while (FindNextFile(hSearch, &File));
FindClose(hSearch);
}
}
}
#ifdef DEBUG_MSG
else
std::cerr << "Could not open pwd directory" << std::endl;
#endif
return entries;
}
#else
#include <dlfcn.h>
#include <sys/types.h>
#include <dirent.h>
static std::vector<std::string> listEntries(const char* dir, unsigned int flags)
{
std::vector<std::string> entries;
DIR * pwddir;
struct dirent* mydirent;
//Open Plugin's directory
pwddir = opendir(dir);
if(pwddir!=NULL)
{
while ((mydirent = readdir(pwddir))!=NULL)
entries.push_back(mydirent->d_name);
closedir(pwddir);
}
#ifdef DEBUG_MSG
else
std::cerr << "Could not open password directory: " << dir << std::endl;
#endif
return entries;
}
#endif
ppk_error getSimpleEntryList(char*** list, unsigned int flags)
{
if(list==NULL)
return PPK_INVALID_ARGUMENTS;
std::vector<std::string> entries=listEntries(setting_dir().c_str(), flags);
if(entries.size()>0)
{
//Get the length of the prefix in order to compare it later to
//the begining of the entry name
int lenPrefix=shortName().size();
//Only keep entries of our own module (PT or ENC)
std::vector<std::string> filtered;
for(size_t i=0; i<entries.size(); i++)
{
std::string val=entries.at(i); //Pattern: PT_NET_http¤[email protected]:80
if(val.substr(0, lenPrefix)==shortName())
{
val=val.substr(lenPrefix+1); //Pattern: NET_http¤[email protected]:80
size_t us_pos=val.find('_');
if(us_pos!=std::string::npos)
{
std::string type=val.substr(0, us_pos); //Pattern: NET
val=val.substr(us_pos+1); //Pattern: http¤[email protected]:80
if(type=="APP" || type=="ITM" || type=="NET")
{
if(type=="NET")
string_replace_first(val, "¤", "://"); //Pattern: http://[email protected]:80
filtered.push_back(val);
}
}
}
}
//Copy to a char** list
(*list)=new char*[filtered.size()+1];
if((*list)!=NULL)
{
for(size_t i=0; i<filtered.size(); i++)
{
std::string val=filtered.at(i);
(*list)[i]=new char[val.size()];
strcpy((*list)[i], val.c_str());
}
(*list)[filtered.size()]=NULL;
}
}
return PPK_OK;
}
//Get and Set passwords
#include "ppasskeeper/data.h"
ppk_error getEntry(const ppk_entry* entry, ppk_data **edata, unsigned int flags)
{
std::string pwd;
ppk_error res_read=readFile(getKey(entry), pwd, flags);
if(res_read==PPK_OK)
{
if(pwd.substr(0,strlen(STR_STRING))==STR_STRING)
*edata=ppk_string_data_new(pwd.c_str()+strlen(STR_STRING));
else if(pwd.substr(0,strlen(BLOB_STRING))==BLOB_STRING)
*edata=ppk_blob_data_new(pwd.data()+strlen(BLOB_STRING), pwd.size()-strlen(BLOB_STRING));
else
return PPK_UNKNOWN_ENTRY_TYPE;
return PPK_OK;
}
else
return res_read;
}
ppk_error setEntry(const ppk_entry* entry, const ppk_data* edata, unsigned int flags)
{
std::string data;
if (edata->type==ppk_blob)
{
if(edata->blob.data!=NULL)
data.assign((const char *) edata->blob.data, edata->blob.size);
else
data="";
data=BLOB_STRING+data;
}
else if(edata->type==ppk_string)
{
if(edata->string!=NULL)
data.assign(edata->string);
else
data = "";
data=STR_STRING+data;
}
else
return PPK_UNKNOWN_ENTRY_TYPE;
return writeFile(getKey(entry).c_str(), data, flags);
}
ppk_error removeEntry(const ppk_entry* entry, unsigned int flags)
{
return deletePassword(getKey(entry), flags);
}
ppk_boolean entryExists(const ppk_entry* entry, unsigned int flags)
{
return fileExists(getKey(entry));
}
unsigned int maxDataSize(ppk_data_type type)
{
switch(type)
{
case ppk_string:
return (unsigned int)-1;
case ppk_blob:
return (unsigned int)-1;
}
return 0;
}
}
|
#include "ppasskeeper.h"
#include "tokenizer.h"
#include <string>
#include <iostream>
#include <fstream>
#include <string.h>
#include "ppasskeeper-dir.h"
#define STR_STRING "str :"
#define BLOB_STRING "blob:"
//local functions
std::string shortName();
ppk_error readFile(std::string filename, std::string& filecontent, unsigned int flags);
ppk_error writeFile(std::string filename, std::string secret, unsigned int flags);
//private functions
ppk_error deletePassword(std::string path, unsigned int flags)
{
if(remove(path.c_str())==0)
return PPK_OK;
else
return PPK_FILE_CANNOT_BE_ACCESSED;
}
ppk_boolean fileExists(std::string filepath)
{
std::ifstream inputfile(filepath.c_str());
if(inputfile.is_open())
{
inputfile.close();
return PPK_TRUE;
}
else
return PPK_FALSE;
}
bool string_replace_first(std::string& str, const std::string to_replace, const std::string replaced_by)
{
size_t found=str.find(to_replace);
if (found!=std::string::npos)
{
str=str.replace(found, to_replace.size(), replaced_by);
return true;
}
else
return false;
}
//functions
extern "C"
{
const char* getModuleName();
const int getABIVersion()
{
return 1;
}
ppk_boolean isWritable()
{
return PPK_TRUE;
}
//Get available flags
unsigned int readFlagsAvailable()
{
return ppk_rf_none|ppk_rf_silent;
}
unsigned int writeFlagsAvailable()
{
return ppk_wf_none|ppk_wf_silent;
}
unsigned int listingFlagsAvailable()
{
return ppk_lf_none|ppk_lf_silent;
}
std::string getKey(const ppk_entry* entry)
{
size_t len=ppk_key_length(entry);
char* entry_cstr=new char[len+1];
if(ppk_get_key(entry, entry_cstr, len)==PPK_TRUE)
{
std::string entry_std=entry_cstr;
std::string type_s;
switch(ppk_get_entry_type(entry))
{
case ppk_application:
type_s="APP";
break;
case ppk_network:
type_s="NET";
string_replace_first(entry_std, "://", "¤");
break;
case ppk_item:
type_s="ITM";
break;
}
return setting_dir()+toString("/")+shortName()+"_"+type_s+"_"+entry_std;
}
else
return std::string();
}
#if defined(WIN32) || defined(WIN64)
#include <windows.h>
static std::vector<std::string>& listEntries(const char* dir, unsigned int flags)
{
WIN32_FIND_DATA File;
HANDLE hSearch;
unsigned int pwdCount=0;
std::vector<std::string> entries;
std::string path;
char* tmp=getenv("HOMEDRIVE");
if(tmp!=NULL)
{
path=tmp;
tmp=getenv("HOMEPATH");
if(tmp!=NULL)
{
path+=tmp;
hSearch = FindFirstFile((path+"\\ppasskeeper\\*").c_str(), &File);
if (hSearch != INVALID_HANDLE_VALUE)
{
do {
entries.push_back(File.cFileName);
} while (FindNextFile(hSearch, &File));
FindClose(hSearch);
}
}
}
#ifdef DEBUG_MSG
else
std::cerr << "Could not open pwd directory" << std::endl;
#endif
return entries;
}
#else
#include <dlfcn.h>
#include <sys/types.h>
#include <dirent.h>
static std::vector<std::string> listEntries(const char* dir, unsigned int flags)
{
std::vector<std::string> entries;
DIR * pwddir;
struct dirent* mydirent;
//Open Plugin's directory
pwddir = opendir(dir);
if(pwddir!=NULL)
{
while ((mydirent = readdir(pwddir))!=NULL)
entries.push_back(mydirent->d_name);
closedir(pwddir);
}
#ifdef DEBUG_MSG
else
std::cerr << "Could not open password directory: " << dir << std::endl;
#endif
return entries;
}
#endif
ppk_error getSimpleEntryList(char*** list, unsigned int flags)
{
if(list==NULL)
return PPK_INVALID_ARGUMENTS;
std::vector<std::string> entries=listEntries(setting_dir().c_str(), flags);
if(entries.size()>0)
{
//Get the length of the prefix in order to compare it later to
//the begining of the entry name
int lenPrefix=shortName().size();
//Only keep entries of our own module (PT or ENC)
std::vector<std::string> filtered;
for(size_t i=0; i<entries.size(); i++)
{
std::string val=entries.at(i); //Pattern: PT_NET_http¤[email protected]:80
if(val.substr(0, lenPrefix)==shortName())
{
val=val.substr(lenPrefix+1); //Pattern: NET_http¤[email protected]:80
size_t us_pos=val.find('_');
if(us_pos!=std::string::npos)
{
std::string type=val.substr(0, us_pos); //Pattern: NET
val=val.substr(us_pos+1); //Pattern: http¤[email protected]:80
if(type=="APP" || type=="ITM" || type=="NET")
{
if(type=="NET")
string_replace_first(val, "¤", "://"); //Pattern: http://[email protected]:80
filtered.push_back(val);
}
}
}
}
//Copy to a char** list
(*list)=new char*[filtered.size()+1];
if((*list)!=NULL)
{
for(size_t i=0; i<filtered.size(); i++)
{
std::string val=filtered.at(i);
(*list)[i]=(char*)malloc((val.size()+1)*sizeof(char));
strncpy((*list)[i], val.c_str(), val.size()+1);
}
(*list)[filtered.size()]=NULL;
}
}
return PPK_OK;
}
//Get and Set passwords
#include "ppasskeeper/data.h"
ppk_error getEntry(const ppk_entry* entry, ppk_data **edata, unsigned int flags)
{
std::string pwd;
ppk_error res_read=readFile(getKey(entry), pwd, flags);
if(res_read==PPK_OK)
{
if(pwd.substr(0,strlen(STR_STRING))==STR_STRING)
*edata=ppk_string_data_new(pwd.c_str()+strlen(STR_STRING));
else if(pwd.substr(0,strlen(BLOB_STRING))==BLOB_STRING)
*edata=ppk_blob_data_new(pwd.data()+strlen(BLOB_STRING), pwd.size()-strlen(BLOB_STRING));
else
return PPK_UNKNOWN_ENTRY_TYPE;
return PPK_OK;
}
else
return res_read;
}
ppk_error setEntry(const ppk_entry* entry, const ppk_data* edata, unsigned int flags)
{
std::string data;
if (edata->type==ppk_blob)
{
if(edata->blob.data!=NULL)
data.assign((const char *) edata->blob.data, edata->blob.size);
else
data="";
data=BLOB_STRING+data;
}
else if(edata->type==ppk_string)
{
if(edata->string!=NULL)
data.assign(edata->string);
else
data = "";
data=STR_STRING+data;
}
else
return PPK_UNKNOWN_ENTRY_TYPE;
return writeFile(getKey(entry).c_str(), data, flags);
}
ppk_error removeEntry(const ppk_entry* entry, unsigned int flags)
{
return deletePassword(getKey(entry), flags);
}
ppk_boolean entryExists(const ppk_entry* entry, unsigned int flags)
{
return fileExists(getKey(entry));
}
unsigned int maxDataSize(ppk_data_type type)
{
switch(type)
{
case ppk_string:
return (unsigned int)-1;
case ppk_blob:
return (unsigned int)-1;
}
return 0;
}
}
|
Fix segfault, my bad :s
|
AFP: Fix segfault, my bad :s
|
C++
|
lgpl-2.1
|
mupuf/PPassKeeper,mupuf/PPassKeeper,mupuf/PPassKeeper
|
c565815174b3d3b95f7eaff06be23b5d37eb70ba
|
src/tglobal.cpp
|
src/tglobal.cpp
|
/* Copyright (c) 2010-2013, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <QStringList>
#include <QAtomicPointer>
#include <TGlobal>
#include <TWebApplication>
#include <TLogger>
#include <TLog>
#include <TActionContext>
#include <TActionThread>
#include <TActionWorker>
#include <TActionForkProcess>
#include <stdlib.h>
#include <limits.h>
#include "tloggerfactory.h"
#include "tsharedmemorylogstream.h"
#include "tbasiclogstream.h"
#include "tsystemglobal.h"
#ifdef Q_OS_WIN
# include <Windows.h>
#endif
#undef tDebug
#undef tTrace
#define APPLICATION_ABORT "ApplicationAbortOnFatal"
static TAbstractLogStream *stream = 0;
/*!
Sets up all the loggers set in the logger.ini.
This function is for internal use only.
*/
void tSetupLoggers()
{
QList<TLogger *> loggers;
QStringList loggerList = Tf::app()->loggerSettings().value("Loggers").toString().split(' ', QString::SkipEmptyParts);
for (QStringListIterator i(loggerList); i.hasNext(); ) {
TLogger *lgr = TLoggerFactory::create(i.next());
if (lgr) {
loggers << lgr;
tSystemDebug("Logger added: %s", qPrintable(lgr->key()));
}
}
if (!stream) {
if (Tf::app()->multiProcessingModule() == TWebApplication::Prefork) {
stream = new TSharedMemoryLogStream(loggers, 4096, qApp);
} else {
stream = new TBasicLogStream(loggers, qApp);
}
}
}
static void tMessage(int priority, const char *msg, va_list ap)
{
TLog log(priority, QString().vsprintf(msg, ap).toLocal8Bit());
if (stream)
stream->writeLog(log);
}
static void tFlushMessage()
{
if (stream)
stream->flush();
}
/*!
Writes the fatal message \a msg to the file app.log.
*/
void tFatal(const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
tMessage(TLogger::Fatal, msg, ap);
va_end(ap);
tFlushMessage();
if (Tf::app()->appSettings().value(APPLICATION_ABORT).toBool()) {
#if (defined(Q_OS_UNIX) || defined(Q_CC_MINGW))
abort(); // trap; generates core dump
#else
_exit(-1);
#endif
}
}
/*!
Writes the error message \a msg to the file app.log.
*/
void tError(const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
tMessage(TLogger::Error, msg, ap);
va_end(ap);
tFlushMessage();
}
/*!
Writes the warning message \a msg to the file app.log.
*/
void tWarn(const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
tMessage(TLogger::Warn, msg, ap);
va_end(ap);
tFlushMessage();
}
/*!
Writes the information message \a msg to the file app.log.
*/
void tInfo(const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
tMessage(TLogger::Info, msg, ap);
va_end(ap);
}
/*!
Writes the debug message \a msg to the file app.log.
*/
void tDebug(const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
tMessage(TLogger::Debug, msg, ap);
va_end(ap);
}
/*!
Writes the trace message \a msg to the file app.log.
*/
void tTrace(const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
tMessage(TLogger::Trace, msg, ap);
va_end(ap);
}
/*!
Returns a global pointer referring to the unique application object.
*/
TWebApplication *Tf::app()
{
return static_cast<TWebApplication *>(qApp);
}
/*!
Causes the current thread to sleep for \a msecs milliseconds.
*/
void Tf::msleep(unsigned long msecs)
{
#if defined(Q_OS_WIN)
::Sleep(msecs);
#else
struct timeval tv;
gettimeofday(&tv, 0);
struct timespec ti;
ti.tv_nsec = (tv.tv_usec + (msecs % 1000) * 1000) * 1000;
ti.tv_sec = tv.tv_sec + (msecs / 1000) + (ti.tv_nsec / 1000000000);
ti.tv_nsec %= 1000000000;
pthread_mutex_t mtx;
pthread_cond_t cnd;
pthread_mutex_init(&mtx, 0);
pthread_cond_init(&cnd, 0);
pthread_mutex_lock(&mtx);
pthread_cond_timedwait(&cnd, &mtx, &ti);
pthread_mutex_unlock(&mtx);
pthread_cond_destroy(&cnd);
pthread_mutex_destroy(&mtx);
#endif
}
/*!
Random number generator in the range from 0 to \a max.
The maximum number of \a max is UINT_MAX.
*/
quint32 Tf::random(quint32 max)
{
return (quint32)((double)randXor128() * (1.0 + max) / (1.0 + UINT_MAX));
}
/*
Xorshift random number generator implement
*/
struct Rand
{
quint32 x;
quint32 y;
quint32 z;
quint32 w;
};
static QAtomicPointer<Rand> randNumber;
/*!
Sets the argument \a seed to be used to generate a new random number sequence
of xorshift random integers to be returned by randXor128().
This function is thread-safe.
*/
void Tf::srandXor128(quint32 seed)
{
// initial numbers
Rand *r = new Rand;
r->x = 123456789;
r->y = 362436169;
r->z = 777777777;
r->w = seed;
Rand *oldr = randNumber.fetchAndStoreOrdered(r);
if (oldr)
delete oldr;
}
/*!
Returns a value between 0 and UINT_MAX, the next number in the current
sequence of xorshift random integers.
This function is thread-safe.
*/
quint32 Tf::randXor128()
{
Rand *newr = new Rand;
Rand tmp;
quint32 t;
for (;;) {
Rand *oldr = randNumber.fetchAndAddOrdered(0);
memcpy(&tmp, oldr, sizeof(tmp));
t = tmp.x ^ (tmp.x << 11);
newr->x = tmp.y;
newr->y = tmp.z;
newr->z = tmp.w;
newr->w = tmp.w ^ (tmp.w >> 19) ^ (t ^ (t >> 8));
if (randNumber.testAndSetOrdered(oldr, newr)) {
delete oldr;
break;
}
}
return newr->w;
}
TActionContext *Tf::currentContext()
{
TActionContext *context = 0;
switch ( Tf::app()->multiProcessingModule() ) {
case TWebApplication::Prefork:
context = TActionForkProcess::currentContext();
if (!context) {
throw RuntimeException("The current process is not TActionProcess", __FILE__, __LINE__);
}
break;
case TWebApplication::Thread:
context = qobject_cast<TActionThread *>(QThread::currentThread());
if (!context) {
throw RuntimeException("The current thread is not TActionThread", __FILE__, __LINE__);
}
break;
case TWebApplication::Hybrid:
#ifdef Q_OS_LINUX
context = qobject_cast<TActionWorker *>(QThread::currentThread());
if (!context) {
context = qobject_cast<TActionThread *>(QThread::currentThread());
if (!context) {
throw RuntimeException("The current thread is not TActionContext", __FILE__, __LINE__);
}
}
#else
tFatal("Unsupported MPM: hybrid");
#endif
break;
default:
break;
}
return context;
}
QSqlDatabase &Tf::currentSqlDatabase(int id)
{
return currentContext()->getSqlDatabase(id);
}
/*!
Returns the current datetime in the local time zone.
It provides 1-second accuracy.
*/
QDateTime Tf::currentDateTimeSec()
{
// QDateTime::currentDateTime() is slow.
// Faster function..
QDateTime current;
#if defined(Q_OS_WIN)
SYSTEMTIME st;
memset(&st, 0, sizeof(SYSTEMTIME));
GetLocalTime(&st);
current.setDate(QDate(st.wYear, st.wMonth, st.wDay));
current.setTime(QTime(st.wHour, st.wMinute, st.wSecond));
#elif defined(Q_OS_UNIX)
time_t ltime = 0;
tm *t = 0;
time(<ime);
# if defined(_POSIX_THREAD_SAFE_FUNCTIONS)
tzset();
tm res;
t = localtime_r(<ime, &res);
# else
t = localtime(<ime);
# endif // _POSIX_THREAD_SAFE_FUNCTIONS
current.setDate(QDate(t->tm_year + 1900, t->tm_mon + 1, t->tm_mday));
current.setTime(QTime(t->tm_hour, t->tm_min, t->tm_sec));
#endif // Q_OS_UNIX
return current;
}
|
/* Copyright (c) 2010-2013, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <QStringList>
#include <TGlobal>
#include <TWebApplication>
#include <TLogger>
#include <TLog>
#include <TActionContext>
#include <TActionThread>
#include <TActionWorker>
#include <TActionForkProcess>
#include <stdlib.h>
#include <limits.h>
#include "tloggerfactory.h"
#include "tsharedmemorylogstream.h"
#include "tbasiclogstream.h"
#include "tsystemglobal.h"
#ifdef Q_OS_WIN
# include <Windows.h>
#endif
#undef tDebug
#undef tTrace
#define APPLICATION_ABORT "ApplicationAbortOnFatal"
static TAbstractLogStream *stream = 0;
/*!
Sets up all the loggers set in the logger.ini.
This function is for internal use only.
*/
void tSetupLoggers()
{
QList<TLogger *> loggers;
QStringList loggerList = Tf::app()->loggerSettings().value("Loggers").toString().split(' ', QString::SkipEmptyParts);
for (QStringListIterator i(loggerList); i.hasNext(); ) {
TLogger *lgr = TLoggerFactory::create(i.next());
if (lgr) {
loggers << lgr;
tSystemDebug("Logger added: %s", qPrintable(lgr->key()));
}
}
if (!stream) {
if (Tf::app()->multiProcessingModule() == TWebApplication::Prefork) {
stream = new TSharedMemoryLogStream(loggers, 4096, qApp);
} else {
stream = new TBasicLogStream(loggers, qApp);
}
}
}
static void tMessage(int priority, const char *msg, va_list ap)
{
TLog log(priority, QString().vsprintf(msg, ap).toLocal8Bit());
if (stream)
stream->writeLog(log);
}
static void tFlushMessage()
{
if (stream)
stream->flush();
}
/*!
Writes the fatal message \a msg to the file app.log.
*/
void tFatal(const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
tMessage(TLogger::Fatal, msg, ap);
va_end(ap);
tFlushMessage();
if (Tf::app()->appSettings().value(APPLICATION_ABORT).toBool()) {
#if (defined(Q_OS_UNIX) || defined(Q_CC_MINGW))
abort(); // trap; generates core dump
#else
_exit(-1);
#endif
}
}
/*!
Writes the error message \a msg to the file app.log.
*/
void tError(const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
tMessage(TLogger::Error, msg, ap);
va_end(ap);
tFlushMessage();
}
/*!
Writes the warning message \a msg to the file app.log.
*/
void tWarn(const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
tMessage(TLogger::Warn, msg, ap);
va_end(ap);
tFlushMessage();
}
/*!
Writes the information message \a msg to the file app.log.
*/
void tInfo(const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
tMessage(TLogger::Info, msg, ap);
va_end(ap);
}
/*!
Writes the debug message \a msg to the file app.log.
*/
void tDebug(const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
tMessage(TLogger::Debug, msg, ap);
va_end(ap);
}
/*!
Writes the trace message \a msg to the file app.log.
*/
void tTrace(const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
tMessage(TLogger::Trace, msg, ap);
va_end(ap);
}
/*!
Returns a global pointer referring to the unique application object.
*/
TWebApplication *Tf::app()
{
return static_cast<TWebApplication *>(qApp);
}
/*!
Causes the current thread to sleep for \a msecs milliseconds.
*/
void Tf::msleep(unsigned long msecs)
{
#if defined(Q_OS_WIN)
::Sleep(msecs);
#else
struct timeval tv;
gettimeofday(&tv, 0);
struct timespec ti;
ti.tv_nsec = (tv.tv_usec + (msecs % 1000) * 1000) * 1000;
ti.tv_sec = tv.tv_sec + (msecs / 1000) + (ti.tv_nsec / 1000000000);
ti.tv_nsec %= 1000000000;
pthread_mutex_t mtx;
pthread_cond_t cnd;
pthread_mutex_init(&mtx, 0);
pthread_cond_init(&cnd, 0);
pthread_mutex_lock(&mtx);
pthread_cond_timedwait(&cnd, &mtx, &ti);
pthread_mutex_unlock(&mtx);
pthread_cond_destroy(&cnd);
pthread_mutex_destroy(&mtx);
#endif
}
/*!
Random number generator in the range from 0 to \a max.
The maximum number of \a max is UINT_MAX.
*/
quint32 Tf::random(quint32 max)
{
return (quint32)((double)randXor128() * (1.0 + max) / (1.0 + UINT_MAX));
}
/*
Xorshift random number generator implement
*/
static QMutex randMutex;
static quint32 x = 123456789;
static quint32 y = 362436069;
static quint32 z = 987654321;
static quint32 w = 1;
/*!
Sets the argument \a seed to be used to generate a new random number sequence
of xorshift random integers to be returned by randXor128().
This function is thread-safe.
*/
void Tf::srandXor128(quint32 seed)
{
QMutexLocker lock(&randMutex);
w = seed;
z = w ^ (w >> 8) ^ (w << 5);
}
/*!
Returns a value between 0 and UINT_MAX, the next number in the current
sequence of xorshift random integers.
This function is thread-safe.
*/
quint32 Tf::randXor128()
{
QMutexLocker lock(&randMutex);
quint32 t;
t = x ^ (x << 11);
x = y;
y = z;
z = w;
w = w ^ (w >> 19) ^ (t ^ (t >> 8));
return w;
}
TActionContext *Tf::currentContext()
{
TActionContext *context = 0;
switch ( Tf::app()->multiProcessingModule() ) {
case TWebApplication::Prefork:
context = TActionForkProcess::currentContext();
if (!context) {
throw RuntimeException("The current process is not TActionProcess", __FILE__, __LINE__);
}
break;
case TWebApplication::Thread:
context = qobject_cast<TActionThread *>(QThread::currentThread());
if (!context) {
throw RuntimeException("The current thread is not TActionThread", __FILE__, __LINE__);
}
break;
case TWebApplication::Hybrid:
#ifdef Q_OS_LINUX
context = qobject_cast<TActionWorker *>(QThread::currentThread());
if (!context) {
context = qobject_cast<TActionThread *>(QThread::currentThread());
if (!context) {
throw RuntimeException("The current thread is not TActionContext", __FILE__, __LINE__);
}
}
#else
tFatal("Unsupported MPM: hybrid");
#endif
break;
default:
break;
}
return context;
}
QSqlDatabase &Tf::currentSqlDatabase(int id)
{
return currentContext()->getSqlDatabase(id);
}
/*!
Returns the current datetime in the local time zone.
It provides 1-second accuracy.
*/
QDateTime Tf::currentDateTimeSec()
{
// QDateTime::currentDateTime() is slow.
// Faster function..
QDateTime current;
#if defined(Q_OS_WIN)
SYSTEMTIME st;
memset(&st, 0, sizeof(SYSTEMTIME));
GetLocalTime(&st);
current.setDate(QDate(st.wYear, st.wMonth, st.wDay));
current.setTime(QTime(st.wHour, st.wMinute, st.wSecond));
#elif defined(Q_OS_UNIX)
time_t ltime = 0;
tm *t = 0;
time(<ime);
# if defined(_POSIX_THREAD_SAFE_FUNCTIONS)
tzset();
tm res;
t = localtime_r(<ime, &res);
# else
t = localtime(<ime);
# endif // _POSIX_THREAD_SAFE_FUNCTIONS
current.setDate(QDate(t->tm_year + 1900, t->tm_mon + 1, t->tm_mday));
current.setTime(QTime(t->tm_hour, t->tm_min, t->tm_sec));
#endif // Q_OS_UNIX
return current;
}
|
revert Xorshift random number generator.
|
revert Xorshift random number generator.
|
C++
|
bsd-3-clause
|
hks2002/treefrog-framework,gonboy/treefrog-framework,gonboy/treefrog-framework,seem-sky/treefrog-framework,gonboy/treefrog-framework,froglogic/treefrog-framework,skipbit/treefrog-framework,treefrogframework/treefrog-framework,AmiArt/treefrog-framework,ThomasGueldner/treefrog-framework,ThomasGueldner/treefrog-framework,ThomasGueldner/treefrog-framework,AmiArt/treefrog-framework,froglogic/treefrog-framework,froglogic/treefrog-framework,seem-sky/treefrog-framework,hks2002/treefrog-framework,AmiArt/treefrog-framework,seem-sky/treefrog-framework,froglogic/treefrog-framework,Akhilesh05/treefrog-framework,AmiArt/treefrog-framework,froglogic/treefrog-framework,skipbit/treefrog-framework,hks2002/treefrog-framework,gonboy/treefrog-framework,treefrogframework/treefrog-framework,treefrogframework/treefrog-framework,Akhilesh05/treefrog-framework,treefrogframework/treefrog-framework,Akhilesh05/treefrog-framework,skipbit/treefrog-framework,treefrogframework/treefrog-framework,hks2002/treefrog-framework,gonboy/treefrog-framework,Akhilesh05/treefrog-framework,skipbit/treefrog-framework,hks2002/treefrog-framework,AmiArt/treefrog-framework,ThomasGueldner/treefrog-framework,skipbit/treefrog-framework,ThomasGueldner/treefrog-framework
|
9b3963ce53c2c4467dfdf085f07d76b4234e272f
|
slideshow/source/engine/transitions/shapetransitionfactory.cxx
|
slideshow/source/engine/transitions/shapetransitionfactory.cxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <canvas/debug.hxx>
#include <tools/diagnose_ex.h>
#include <comphelper/anytostring.hxx>
#include <cppuhelper/exc_hlp.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <com/sun/star/animations/TransitionType.hpp>
#include <com/sun/star/animations/TransitionSubType.hpp>
#include "transitionfactory.hxx"
#include "transitiontools.hxx"
#include "parametricpolypolygonfactory.hxx"
#include "animationfactory.hxx"
#include "clippingfunctor.hxx"
#include <boost/bind.hpp>
using namespace ::com::sun::star;
namespace slideshow {
namespace internal {
/***************************************************
*** ***
*** Shape Transition Effects ***
*** ***
***************************************************/
namespace {
class ClippingAnimation : public NumberAnimation
{
public:
ClippingAnimation(
const ParametricPolyPolygonSharedPtr& rPolygon,
const ShapeManagerSharedPtr& rShapeManager,
const TransitionInfo& rTransitionInfo,
bool bDirectionForward,
bool bModeIn );
~ClippingAnimation();
// Animation interface
// -------------------
virtual void prefetch( const AnimatableShapeSharedPtr& rShape,
const ShapeAttributeLayerSharedPtr& rAttrLayer );
virtual void start( const AnimatableShapeSharedPtr& rShape,
const ShapeAttributeLayerSharedPtr& rAttrLayer );
virtual void end();
// NumberAnimation interface
// -----------------------
virtual bool operator()( double nValue );
virtual double getUnderlyingValue() const;
private:
void end_();
AnimatableShapeSharedPtr mpShape;
ShapeAttributeLayerSharedPtr mpAttrLayer;
ShapeManagerSharedPtr mpShapeManager;
ClippingFunctor maClippingFunctor;
bool mbSpriteActive;
};
ClippingAnimation::ClippingAnimation(
const ParametricPolyPolygonSharedPtr& rPolygon,
const ShapeManagerSharedPtr& rShapeManager,
const TransitionInfo& rTransitionInfo,
bool bDirectionForward,
bool bModeIn ) :
mpShape(),
mpAttrLayer(),
mpShapeManager( rShapeManager ),
maClippingFunctor( rPolygon,
rTransitionInfo,
bDirectionForward,
bModeIn ),
mbSpriteActive(false)
{
ENSURE_OR_THROW(
rShapeManager,
"ClippingAnimation::ClippingAnimation(): Invalid ShapeManager" );
}
ClippingAnimation::~ClippingAnimation()
{
try
{
end_();
}
catch (uno::Exception &)
{
OSL_FAIL( rtl::OUStringToOString(
comphelper::anyToString(
cppu::getCaughtException() ),
RTL_TEXTENCODING_UTF8 ).getStr() );
}
}
void ClippingAnimation::prefetch( const AnimatableShapeSharedPtr&,
const ShapeAttributeLayerSharedPtr& )
{
}
void ClippingAnimation::start( const AnimatableShapeSharedPtr& rShape,
const ShapeAttributeLayerSharedPtr& rAttrLayer )
{
OSL_ENSURE( !mpShape,
"ClippingAnimation::start(): Shape already set" );
OSL_ENSURE( !mpAttrLayer,
"ClippingAnimation::start(): Attribute layer already set" );
mpShape = rShape;
mpAttrLayer = rAttrLayer;
ENSURE_OR_THROW( rShape,
"ClippingAnimation::start(): Invalid shape" );
ENSURE_OR_THROW( rAttrLayer,
"ClippingAnimation::start(): Invalid attribute layer" );
mpShape = rShape;
mpAttrLayer = rAttrLayer;
if( !mbSpriteActive )
{
mpShapeManager->enterAnimationMode( mpShape );
mbSpriteActive = true;
}
}
void ClippingAnimation::end()
{
end_();
}
void ClippingAnimation::end_()
{
if( mbSpriteActive )
{
mbSpriteActive = false;
mpShapeManager->leaveAnimationMode( mpShape );
if( mpShape->isContentChanged() )
mpShapeManager->notifyShapeUpdate( mpShape );
}
}
bool ClippingAnimation::operator()( double nValue )
{
ENSURE_OR_RETURN_FALSE(
mpAttrLayer && mpShape,
"ClippingAnimation::operator(): Invalid ShapeAttributeLayer" );
// set new clip
mpAttrLayer->setClip( maClippingFunctor( nValue,
mpShape->getDomBounds().getRange() ) );
if( mpShape->isContentChanged() )
mpShapeManager->notifyShapeUpdate( mpShape );
return true;
}
double ClippingAnimation::getUnderlyingValue() const
{
ENSURE_OR_THROW(
mpAttrLayer,
"ClippingAnimation::getUnderlyingValue(): Invalid ShapeAttributeLayer" );
return 0.0; // though this should be used in concert with
// ActivitiesFactory::createSimpleActivity, better
// explicitly name our start value.
// Permissible range for operator() above is [0,1]
}
} // anon namespace
AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
const ActivitiesFactory::CommonParameters& rParms,
const AnimatableShapeSharedPtr& rShape,
const ShapeManagerSharedPtr& rShapeManager,
const ::basegfx::B2DVector& rSlideSize,
uno::Reference< animations::XTransitionFilter > const& xTransition )
{
return createShapeTransition( rParms,
rShape,
rShapeManager,
rSlideSize,
xTransition,
xTransition->getTransition(),
xTransition->getSubtype() );
}
AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
const ActivitiesFactory::CommonParameters& rParms,
const AnimatableShapeSharedPtr& rShape,
const ShapeManagerSharedPtr& rShapeManager,
const ::basegfx::B2DVector& rSlideSize,
::com::sun::star::uno::Reference<
::com::sun::star::animations::XTransitionFilter > const& xTransition,
sal_Int16 nType,
sal_Int16 nSubType )
{
ENSURE_OR_THROW(
xTransition.is(),
"TransitionFactory::createShapeTransition(): Invalid XTransition" );
const TransitionInfo* pTransitionInfo(
getTransitionInfo( nType, nSubType ) );
AnimationActivitySharedPtr pGeneratedActivity;
if( pTransitionInfo != NULL )
{
switch( pTransitionInfo->meTransitionClass )
{
default:
case TransitionInfo::TRANSITION_INVALID:
OSL_FAIL( "TransitionFactory::createShapeTransition(): Invalid transition type. "
"Don't ask me for a 0 TransitionType, have no XTransitionFilter node instead!" );
return AnimationActivitySharedPtr();
case TransitionInfo::TRANSITION_CLIP_POLYPOLYGON:
{
// generate parametric poly-polygon
ParametricPolyPolygonSharedPtr pPoly(
ParametricPolyPolygonFactory::createClipPolyPolygon(
nType, nSubType ) );
// create a clip activity from that
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
NumberAnimationSharedPtr(
new ClippingAnimation(
pPoly,
rShapeManager,
*pTransitionInfo,
xTransition->getDirection(),
xTransition->getMode() ) ),
true );
}
break;
case TransitionInfo::TRANSITION_SPECIAL:
{
switch( nType )
{
case animations::TransitionType::RANDOM:
{
// select randomly one of the effects from the
// TransitionFactoryTable
const TransitionInfo* pRandomTransitionInfo( getRandomTransitionInfo() );
ENSURE_OR_THROW( pRandomTransitionInfo != NULL,
"TransitionFactory::createShapeTransition(): Got invalid random transition info" );
ENSURE_OR_THROW( pRandomTransitionInfo->mnTransitionType != animations::TransitionType::RANDOM,
"TransitionFactory::createShapeTransition(): Got random again for random input!" );
// and recurse
pGeneratedActivity = createShapeTransition( rParms,
rShape,
rShapeManager,
rSlideSize,
xTransition,
pRandomTransitionInfo->mnTransitionType,
pRandomTransitionInfo->mnTransitionSubType );
}
break;
// TODO(F3): Implement slidewipe for shape
case animations::TransitionType::SLIDEWIPE:
{
sal_Int16 nBarWipeSubType(0);
bool bDirectionForward(true);
// map slidewipe to BARWIPE, for now
switch( nSubType )
{
case animations::TransitionSubType::FROMLEFT:
nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
bDirectionForward = true;
break;
case animations::TransitionSubType::FROMRIGHT:
nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
bDirectionForward = false;
break;
case animations::TransitionSubType::FROMTOP:
nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
bDirectionForward = true;
break;
case animations::TransitionSubType::FROMBOTTOM:
nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
bDirectionForward = false;
break;
default:
ENSURE_OR_THROW( false,
"TransitionFactory::createShapeTransition(): Unexpected subtype for SLIDEWIPE" );
break;
}
// generate parametric poly-polygon
ParametricPolyPolygonSharedPtr pPoly(
ParametricPolyPolygonFactory::createClipPolyPolygon(
animations::TransitionType::BARWIPE,
nBarWipeSubType ) );
// create a clip activity from that
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
NumberAnimationSharedPtr(
new ClippingAnimation(
pPoly,
rShapeManager,
*getTransitionInfo( animations::TransitionType::BARWIPE,
nBarWipeSubType ),
bDirectionForward,
xTransition->getMode() ) ),
true );
}
break;
default:
{
// TODO(F1): Check whether there's anything left, anyway,
// for _shape_ transitions. AFAIK, there are no special
// effects for shapes...
// for now, map all to fade effect
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
AnimationFactory::createNumberPropertyAnimation(
::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("Opacity") ),
rShape,
rShapeManager,
rSlideSize ),
xTransition->getMode() );
}
break;
}
}
break;
}
}
if( !pGeneratedActivity )
{
// No animation generated, maybe no table entry for given
// transition?
OSL_TRACE(
"TransitionFactory::createShapeTransition(): Unknown type/subtype (%d/%d) "
"combination encountered",
xTransition->getTransition(),
xTransition->getSubtype() );
OSL_FAIL(
"TransitionFactory::createShapeTransition(): Unknown type/subtype "
"combination encountered" );
}
return pGeneratedActivity;
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <canvas/debug.hxx>
#include <tools/diagnose_ex.h>
#include <comphelper/anytostring.hxx>
#include <cppuhelper/exc_hlp.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <com/sun/star/animations/TransitionType.hpp>
#include <com/sun/star/animations/TransitionSubType.hpp>
#include "transitionfactory.hxx"
#include "transitiontools.hxx"
#include "parametricpolypolygonfactory.hxx"
#include "animationfactory.hxx"
#include "clippingfunctor.hxx"
#include <boost/bind.hpp>
using namespace ::com::sun::star;
namespace slideshow {
namespace internal {
/***************************************************
*** ***
*** Shape Transition Effects ***
*** ***
***************************************************/
namespace {
class ClippingAnimation : public NumberAnimation
{
public:
ClippingAnimation(
const ParametricPolyPolygonSharedPtr& rPolygon,
const ShapeManagerSharedPtr& rShapeManager,
const TransitionInfo& rTransitionInfo,
bool bDirectionForward,
bool bModeIn );
~ClippingAnimation();
// Animation interface
// -------------------
virtual void prefetch( const AnimatableShapeSharedPtr& rShape,
const ShapeAttributeLayerSharedPtr& rAttrLayer );
virtual void start( const AnimatableShapeSharedPtr& rShape,
const ShapeAttributeLayerSharedPtr& rAttrLayer );
virtual void end();
// NumberAnimation interface
// -----------------------
virtual bool operator()( double nValue );
virtual double getUnderlyingValue() const;
private:
void end_();
AnimatableShapeSharedPtr mpShape;
ShapeAttributeLayerSharedPtr mpAttrLayer;
ShapeManagerSharedPtr mpShapeManager;
ClippingFunctor maClippingFunctor;
bool mbSpriteActive;
};
ClippingAnimation::ClippingAnimation(
const ParametricPolyPolygonSharedPtr& rPolygon,
const ShapeManagerSharedPtr& rShapeManager,
const TransitionInfo& rTransitionInfo,
bool bDirectionForward,
bool bModeIn ) :
mpShape(),
mpAttrLayer(),
mpShapeManager( rShapeManager ),
maClippingFunctor( rPolygon,
rTransitionInfo,
bDirectionForward,
bModeIn ),
mbSpriteActive(false)
{
ENSURE_OR_THROW(
rShapeManager,
"ClippingAnimation::ClippingAnimation(): Invalid ShapeManager" );
}
ClippingAnimation::~ClippingAnimation()
{
try
{
end_();
}
catch (uno::Exception &)
{
OSL_FAIL( rtl::OUStringToOString(
comphelper::anyToString(
cppu::getCaughtException() ),
RTL_TEXTENCODING_UTF8 ).getStr() );
}
}
void ClippingAnimation::prefetch( const AnimatableShapeSharedPtr&,
const ShapeAttributeLayerSharedPtr& )
{
}
void ClippingAnimation::start( const AnimatableShapeSharedPtr& rShape,
const ShapeAttributeLayerSharedPtr& rAttrLayer )
{
OSL_ENSURE( !mpShape,
"ClippingAnimation::start(): Shape already set" );
OSL_ENSURE( !mpAttrLayer,
"ClippingAnimation::start(): Attribute layer already set" );
ENSURE_OR_THROW( rShape,
"ClippingAnimation::start(): Invalid shape" );
ENSURE_OR_THROW( rAttrLayer,
"ClippingAnimation::start(): Invalid attribute layer" );
mpShape = rShape;
mpAttrLayer = rAttrLayer;
if( !mbSpriteActive )
{
mpShapeManager->enterAnimationMode( mpShape );
mbSpriteActive = true;
}
}
void ClippingAnimation::end()
{
end_();
}
void ClippingAnimation::end_()
{
if( mbSpriteActive )
{
mbSpriteActive = false;
mpShapeManager->leaveAnimationMode( mpShape );
if( mpShape->isContentChanged() )
mpShapeManager->notifyShapeUpdate( mpShape );
}
}
bool ClippingAnimation::operator()( double nValue )
{
ENSURE_OR_RETURN_FALSE(
mpAttrLayer && mpShape,
"ClippingAnimation::operator(): Invalid ShapeAttributeLayer" );
// set new clip
mpAttrLayer->setClip( maClippingFunctor( nValue,
mpShape->getDomBounds().getRange() ) );
if( mpShape->isContentChanged() )
mpShapeManager->notifyShapeUpdate( mpShape );
return true;
}
double ClippingAnimation::getUnderlyingValue() const
{
ENSURE_OR_THROW(
mpAttrLayer,
"ClippingAnimation::getUnderlyingValue(): Invalid ShapeAttributeLayer" );
return 0.0; // though this should be used in concert with
// ActivitiesFactory::createSimpleActivity, better
// explicitly name our start value.
// Permissible range for operator() above is [0,1]
}
} // anon namespace
AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
const ActivitiesFactory::CommonParameters& rParms,
const AnimatableShapeSharedPtr& rShape,
const ShapeManagerSharedPtr& rShapeManager,
const ::basegfx::B2DVector& rSlideSize,
uno::Reference< animations::XTransitionFilter > const& xTransition )
{
return createShapeTransition( rParms,
rShape,
rShapeManager,
rSlideSize,
xTransition,
xTransition->getTransition(),
xTransition->getSubtype() );
}
AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
const ActivitiesFactory::CommonParameters& rParms,
const AnimatableShapeSharedPtr& rShape,
const ShapeManagerSharedPtr& rShapeManager,
const ::basegfx::B2DVector& rSlideSize,
::com::sun::star::uno::Reference<
::com::sun::star::animations::XTransitionFilter > const& xTransition,
sal_Int16 nType,
sal_Int16 nSubType )
{
ENSURE_OR_THROW(
xTransition.is(),
"TransitionFactory::createShapeTransition(): Invalid XTransition" );
const TransitionInfo* pTransitionInfo(
getTransitionInfo( nType, nSubType ) );
AnimationActivitySharedPtr pGeneratedActivity;
if( pTransitionInfo != NULL )
{
switch( pTransitionInfo->meTransitionClass )
{
default:
case TransitionInfo::TRANSITION_INVALID:
OSL_FAIL( "TransitionFactory::createShapeTransition(): Invalid transition type. "
"Don't ask me for a 0 TransitionType, have no XTransitionFilter node instead!" );
return AnimationActivitySharedPtr();
case TransitionInfo::TRANSITION_CLIP_POLYPOLYGON:
{
// generate parametric poly-polygon
ParametricPolyPolygonSharedPtr pPoly(
ParametricPolyPolygonFactory::createClipPolyPolygon(
nType, nSubType ) );
// create a clip activity from that
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
NumberAnimationSharedPtr(
new ClippingAnimation(
pPoly,
rShapeManager,
*pTransitionInfo,
xTransition->getDirection(),
xTransition->getMode() ) ),
true );
}
break;
case TransitionInfo::TRANSITION_SPECIAL:
{
switch( nType )
{
case animations::TransitionType::RANDOM:
{
// select randomly one of the effects from the
// TransitionFactoryTable
const TransitionInfo* pRandomTransitionInfo( getRandomTransitionInfo() );
ENSURE_OR_THROW( pRandomTransitionInfo != NULL,
"TransitionFactory::createShapeTransition(): Got invalid random transition info" );
ENSURE_OR_THROW( pRandomTransitionInfo->mnTransitionType != animations::TransitionType::RANDOM,
"TransitionFactory::createShapeTransition(): Got random again for random input!" );
// and recurse
pGeneratedActivity = createShapeTransition( rParms,
rShape,
rShapeManager,
rSlideSize,
xTransition,
pRandomTransitionInfo->mnTransitionType,
pRandomTransitionInfo->mnTransitionSubType );
}
break;
// TODO(F3): Implement slidewipe for shape
case animations::TransitionType::SLIDEWIPE:
{
sal_Int16 nBarWipeSubType(0);
bool bDirectionForward(true);
// map slidewipe to BARWIPE, for now
switch( nSubType )
{
case animations::TransitionSubType::FROMLEFT:
nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
bDirectionForward = true;
break;
case animations::TransitionSubType::FROMRIGHT:
nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
bDirectionForward = false;
break;
case animations::TransitionSubType::FROMTOP:
nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
bDirectionForward = true;
break;
case animations::TransitionSubType::FROMBOTTOM:
nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
bDirectionForward = false;
break;
default:
ENSURE_OR_THROW( false,
"TransitionFactory::createShapeTransition(): Unexpected subtype for SLIDEWIPE" );
break;
}
// generate parametric poly-polygon
ParametricPolyPolygonSharedPtr pPoly(
ParametricPolyPolygonFactory::createClipPolyPolygon(
animations::TransitionType::BARWIPE,
nBarWipeSubType ) );
// create a clip activity from that
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
NumberAnimationSharedPtr(
new ClippingAnimation(
pPoly,
rShapeManager,
*getTransitionInfo( animations::TransitionType::BARWIPE,
nBarWipeSubType ),
bDirectionForward,
xTransition->getMode() ) ),
true );
}
break;
default:
{
// TODO(F1): Check whether there's anything left, anyway,
// for _shape_ transitions. AFAIK, there are no special
// effects for shapes...
// for now, map all to fade effect
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
AnimationFactory::createNumberPropertyAnimation(
::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("Opacity") ),
rShape,
rShapeManager,
rSlideSize ),
xTransition->getMode() );
}
break;
}
}
break;
}
}
if( !pGeneratedActivity )
{
// No animation generated, maybe no table entry for given
// transition?
OSL_TRACE(
"TransitionFactory::createShapeTransition(): Unknown type/subtype (%d/%d) "
"combination encountered",
xTransition->getTransition(),
xTransition->getSubtype() );
OSL_FAIL(
"TransitionFactory::createShapeTransition(): Unknown type/subtype "
"combination encountered" );
}
return pGeneratedActivity;
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
remove duplicated assignment
|
remove duplicated assignment
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
fc56bba63ad3cc94501c9cad4dbcd56981d9deab
|
nek/type_traits/enable_if.hpp
|
nek/type_traits/enable_if.hpp
|
#ifndef NEK_TYPE_TRAITS_ENABLE_IF_HPP
#define NEK_TYPE_TRAITS_ENABLE_IF_HPP
namespace nek
{
template <bool Val, class T = void>
struct enable_if_c
{
typedef T type;
};
template <class T>
struct enable_if_c<false, T>
{
};
template <class Cond, class T = void>
struct enable_if
: public enable_if_c<Cond::value, T>
{
};
template <bool Val, class T = void>
struct disable_if_c
{
typedef T type;
};
template <class T>
struct disable_if_c<true, T>
{
};
template <class Cond, class T = void>
struct disable_if
: public disable_if_c<Cond::value, T>
{
};
}
#endif
|
#ifndef NEK_TYPE_TRAITS_ENABLE_IF_HPP
#define NEK_TYPE_TRAITS_ENABLE_IF_HPP
namespace nek
{
template <bool C, class T = void>
struct enable_if_c
{
typedef T type;
};
template <class T>
struct enable_if_c<false, T>
{
};
template <class Cond, class T = void>
struct enable_if
: public enable_if_c<Cond::value, T>
{
};
template <bool C, class T = void>
struct disable_if_c
{
typedef T type;
};
template <class T>
struct disable_if_c<true, T>
{
};
template <class Cond, class T = void>
struct disable_if
: public disable_if_c<Cond::value, T>
{
};
}
#endif
|
Rename template argument of enable_if and disable_if
|
Rename template argument of enable_if and disable_if
Val->
C
|
C++
|
bsd-3-clause
|
nekko1119/nek
|
6f10814da958a0408a7cf561fd9299143800f804
|
src/petro/presentation_time.hpp
|
src/petro/presentation_time.hpp
|
// Copyright (c) Steinwurf ApS 2016.
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#pragma once
#include <memory>
#include <cstdint>
#include "box/stts.hpp"
#include "box/ctts.hpp"
namespace petro
{
/// returns the sample's presentation time in microseconds.
/// the ctts box is allowed to be zero.
int64_t presentation_time(
std::shared_ptr<const petro::box::stts> stts,
std::shared_ptr<const petro::box::ctts> ctts,
uint32_t media_header_timescale,
uint32_t sample_index)
{
int64_t presentation_time = stts->decoding_time(sample_index);
if (ctts != nullptr)
{
presentation_time += ctts->composition_time(sample_index);
}
presentation_time *= 1000000;
presentation_time /= media_header_timescale;
return presentation_time;
}
}
|
// Copyright (c) Steinwurf ApS 2016.
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#pragma once
#include <memory>
#include <cstdint>
#include "box/stts.hpp"
#include "box/ctts.hpp"
namespace petro
{
/// returns the sample's presentation time in microseconds.
/// the ctts box is allowed to be zero.
inline int64_t presentation_time(
std::shared_ptr<const petro::box::stts> stts,
std::shared_ptr<const petro::box::ctts> ctts,
uint32_t media_header_timescale,
uint32_t sample_index)
{
int64_t presentation_time = stts->decoding_time(sample_index);
if (ctts != nullptr)
{
presentation_time += ctts->composition_time(sample_index);
}
presentation_time *= 1000000;
presentation_time /= media_header_timescale;
return presentation_time;
}
}
|
make presentation_time inline
|
make presentation_time inline
|
C++
|
bsd-3-clause
|
steinwurf/petro,steinwurf/petro
|
9a50143ca6a5f7d05dcdcbeb02d97e3eae6eb6a4
|
test/interpreter.cpp
|
test/interpreter.cpp
|
#include "p0run/interpreter.hpp"
#include "p0i/function.hpp"
#include "p0i/emitter.hpp"
#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
using namespace p0::run;
using namespace p0;
namespace
{
template <class FunctionCreator, class ResultHandler>
void run_single_function(
FunctionCreator const &create,
std::vector<value> const &arguments,
ResultHandler const &handle_result
)
{
intermediate::unit::function_vector functions;
intermediate::emitter::instruction_vector instructions;
intermediate::emitter emitter(instructions);
intermediate::unit::string_vector strings;
create(emitter, strings);
functions.push_back(intermediate::function(instructions, arguments.size()));
intermediate::unit program(functions, strings);
interpreter interpreter(program);
auto const result = interpreter.call(program.functions()[0], arguments);
handle_result(result);
}
}
BOOST_AUTO_TEST_CASE(nothing_operation_test)
{
for (size_t i = 0; i < 3; ++i)
{
run_single_function(
[i](intermediate::emitter &emitter, intermediate::unit::string_vector &strings)
{
for (size_t j = 0; j < i; ++j)
{
emitter.nothing();
}
},
std::vector<value>(),
[](value const &result)
{
BOOST_CHECK(result == value());
});
}
}
BOOST_AUTO_TEST_CASE(set_from_constant_operation_test)
{
static std::array<integer, 5> const test_numbers =
{{
0,
1,
-34,
std::numeric_limits<integer>::min(),
std::numeric_limits<integer>::max()
}};
BOOST_FOREACH (integer const number, test_numbers)
{
run_single_function(
[number](intermediate::emitter &emitter, intermediate::unit::string_vector &)
{
emitter.set_from_constant(0, number);
},
std::vector<value>(),
[number](value const &result)
{
BOOST_CHECK(result == value(number));
});
}
}
BOOST_AUTO_TEST_CASE(set_null_operation_test)
{
run_single_function(
[](intermediate::emitter &emitter, intermediate::unit::string_vector &)
{
emitter.set_from_constant(1, 123);
//overwrite the "123" with null
emitter.set_null(1);
//return the null
emitter.copy(0, 1);
},
std::vector<value>(),
[](value const &result)
{
BOOST_CHECK(result == value());
});
}
BOOST_AUTO_TEST_CASE(copy_operation_test)
{
value const test_value(static_cast<integer>(6));
run_single_function(
[](intermediate::emitter &emitter, intermediate::unit::string_vector &)
{
//return the first argument
emitter.copy(0, 1);
},
std::vector<value>(1, test_value),
[test_value](value const &result)
{
BOOST_CHECK(result == test_value);
});
}
namespace
{
void integer_arithmetic_test(
intermediate::instruction_type::Enum op,
integer left,
integer right,
integer expected_result
)
{
std::vector<value> arguments;
arguments.push_back(value(left));
arguments.push_back(value(right));
run_single_function(
[op](intermediate::emitter &emitter, intermediate::unit::string_vector &)
{
//[1] += [2]
emitter.push_instruction(intermediate::instruction(op, 1, 2));
//[0] = [1]
emitter.copy(0, 1);
//return [0]
emitter.return_();
},
arguments,
[expected_result](value const &result)
{
BOOST_CHECK(result == value(expected_result));
});
}
}
BOOST_AUTO_TEST_CASE(add_operation_test)
{
using namespace intermediate::instruction_type;
integer_arithmetic_test(add, 60, 70, 130);
integer_arithmetic_test(add, 0, 70, 70);
integer_arithmetic_test(add, 60, 0, 60);
integer_arithmetic_test(add, -60, 70, 10);
integer_arithmetic_test(add, -60, -70, -130);
}
BOOST_AUTO_TEST_CASE(sub_operation_test)
{
using namespace intermediate::instruction_type;
integer_arithmetic_test(sub, 60, 70, -10);
integer_arithmetic_test(sub, 0, 70, -70);
integer_arithmetic_test(sub, 60, 0, 60);
integer_arithmetic_test(sub, -60, 70, -130);
integer_arithmetic_test(sub, -60, -70, 10);
}
|
#include "p0run/interpreter.hpp"
#include "p0i/function.hpp"
#include "p0i/emitter.hpp"
#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
using namespace p0::run;
using namespace p0;
namespace
{
template <class FunctionCreator, class ResultHandler>
void run_single_function(
FunctionCreator const &create,
std::vector<value> const &arguments,
ResultHandler const &handle_result
)
{
intermediate::unit::function_vector functions;
intermediate::emitter::instruction_vector instructions;
intermediate::emitter emitter(instructions);
intermediate::unit::string_vector strings;
create(emitter, strings);
functions.push_back(intermediate::function(instructions, arguments.size()));
intermediate::unit program(functions, strings);
interpreter interpreter(program);
auto const result = interpreter.call(program.functions()[0], arguments);
handle_result(result);
}
}
BOOST_AUTO_TEST_CASE(nothing_operation_test)
{
for (size_t i = 0; i < 3; ++i)
{
run_single_function(
[i](intermediate::emitter &emitter, intermediate::unit::string_vector &strings)
{
for (size_t j = 0; j < i; ++j)
{
emitter.nothing();
}
},
std::vector<value>(),
[](value const &result)
{
BOOST_CHECK(result == value());
});
}
}
BOOST_AUTO_TEST_CASE(set_from_constant_operation_test)
{
static std::array<integer, 5> const test_numbers =
{{
0,
1,
-34,
std::numeric_limits<integer>::min(),
std::numeric_limits<integer>::max()
}};
BOOST_FOREACH (integer const number, test_numbers)
{
run_single_function(
[number](intermediate::emitter &emitter, intermediate::unit::string_vector &)
{
emitter.set_from_constant(0, number);
},
std::vector<value>(),
[number](value const &result)
{
BOOST_CHECK(result == value(number));
});
}
}
BOOST_AUTO_TEST_CASE(set_null_operation_test)
{
run_single_function(
[](intermediate::emitter &emitter, intermediate::unit::string_vector &)
{
emitter.set_from_constant(1, 123);
//overwrite the "123" with null
emitter.set_null(1);
//return the null
emitter.copy(0, 1);
},
std::vector<value>(),
[](value const &result)
{
BOOST_CHECK(result == value());
});
}
BOOST_AUTO_TEST_CASE(copy_operation_test)
{
value const test_value(static_cast<integer>(6));
run_single_function(
[](intermediate::emitter &emitter, intermediate::unit::string_vector &)
{
//return the first argument
emitter.copy(0, 1);
},
std::vector<value>(1, test_value),
[test_value](value const &result)
{
BOOST_CHECK(result == test_value);
});
}
namespace
{
void integer_arithmetic_test(
intermediate::instruction_type::Enum op,
integer left,
integer right,
integer expected_result
)
{
std::vector<value> arguments;
arguments.push_back(value(left));
arguments.push_back(value(right));
run_single_function(
[op](intermediate::emitter &emitter, intermediate::unit::string_vector &)
{
//[1] += [2]
emitter.push_instruction(intermediate::instruction(op, 1, 2));
//[0] = [1]
emitter.copy(0, 1);
//return [0]
emitter.return_();
},
arguments,
[expected_result](value const &result)
{
BOOST_CHECK(result == value(expected_result));
});
}
}
BOOST_AUTO_TEST_CASE(add_operation_test)
{
using namespace intermediate::instruction_type;
integer_arithmetic_test(add, 60, 70, 130);
integer_arithmetic_test(add, 0, 70, 70);
integer_arithmetic_test(add, 60, 0, 60);
integer_arithmetic_test(add, -60, 70, 10);
integer_arithmetic_test(add, -60, -70, -130);
}
BOOST_AUTO_TEST_CASE(sub_operation_test)
{
using namespace intermediate::instruction_type;
integer_arithmetic_test(sub, 60, 70, -10);
integer_arithmetic_test(sub, 0, 70, -70);
integer_arithmetic_test(sub, 60, 0, 60);
integer_arithmetic_test(sub, -60, 70, -130);
integer_arithmetic_test(sub, -60, -70, 10);
}
BOOST_AUTO_TEST_CASE(mul_operation_test)
{
using namespace intermediate::instruction_type;
integer_arithmetic_test(mul, 60, 70, 4200);
integer_arithmetic_test(mul, 0, 70, 0);
integer_arithmetic_test(mul, 60, 0, 0);
integer_arithmetic_test(mul, -60, 70, -4200);
integer_arithmetic_test(mul, -60, -70, 4200);
integer_arithmetic_test(mul, 1, 70, 70);
integer_arithmetic_test(mul, 60, 1, 60);
}
BOOST_AUTO_TEST_CASE(div_operation_test)
{
using namespace intermediate;
//VC++ says 'div' is ambiguous
integer_arithmetic_test(instruction_type::div, 60, 70, 0);
integer_arithmetic_test(instruction_type::div, 0, 70, 0);
integer_arithmetic_test(instruction_type::div, 60, 2, 30);
integer_arithmetic_test(instruction_type::div, -70, 60, -1);
integer_arithmetic_test(instruction_type::div, -70, -60, 1);
integer_arithmetic_test(instruction_type::div, 1, 70, 0);
integer_arithmetic_test(instruction_type::div, 60, 1, 60);
}
|
test mul, div
|
test mul, div
|
C++
|
mit
|
TyRoXx/protolang0
|
67a624f47f26358bcf1f1ec240b79fd70b8be1f7
|
odk/examples/DevelopersGuide/ProfUNO/CppBinding/office_connect.cxx
|
odk/examples/DevelopersGuide/ProfUNO/CppBinding/office_connect.cxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* The Contents of this file are made available subject to the terms of
* the BSD license.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
* 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 Sun Microsystems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*************************************************************************/
#include <stdio.h>
#include <sal/main.h>
#include <cppuhelper/bootstrap.hxx>
#include <com/sun/star/bridge/XUnoUrlResolver.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::bridge;
using namespace cppu;
using ::rtl::OUString;
using ::rtl::OUStringToOString;
SAL_IMPLEMENT_MAIN()
{
// create the initial component context
Reference< XComponentContext > rComponentContext =
defaultBootstrap_InitialComponentContext();
// retrieve the servicemanager from the context
Reference< XMultiComponentFactory > rServiceManager =
rComponentContext->getServiceManager();
// instantiate a sample service with the servicemanager.
Reference< XInterface > rInstance =
rServiceManager->createInstanceWithContext(
OUString("com.sun.star.bridge.UnoUrlResolver"),
rComponentContext );
// Query for the XUnoUrlResolver interface
Reference< XUnoUrlResolver > rResolver( rInstance, UNO_QUERY );
if( ! rResolver.is() )
{
printf( "Error: Couldn't instantiate com.sun.star.bridge.UnoUrlResolver service\n" );
return 1;
}
try
{
// resolve the uno-url
rInstance = rResolver->resolve( OUString(
"uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager" ) );
if( ! rInstance.is() )
{
printf( "StarOffice.ServiceManager is not exported from remote counterpart\n" );
return 1;
}
// query for the simpler XMultiServiceFactory interface, sufficient for scripting
Reference< XMultiServiceFactory > rOfficeServiceManager (rInstance, UNO_QUERY);
if( ! rInstance.is() )
{
printf( "XMultiServiceFactory interface is not exported for StarOffice.ServiceManager\n" );
return 1;
}
printf( "Connected sucessfully to the office\n" );
}
catch( Exception &e )
{
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "Error: %s\n", o.pData->buffer );
return 1;
}
return 0;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* The Contents of this file are made available subject to the terms of
* the BSD license.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
* 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 Sun Microsystems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*************************************************************************/
#include <stdio.h>
#include <sal/main.h>
#include <cppuhelper/bootstrap.hxx>
#include <com/sun/star/bridge/XUnoUrlResolver.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::bridge;
using namespace cppu;
using ::rtl::OString;
using ::rtl::OUString;
using ::rtl::OUStringToOString;
SAL_IMPLEMENT_MAIN()
{
// create the initial component context
Reference< XComponentContext > rComponentContext =
defaultBootstrap_InitialComponentContext();
// retrieve the servicemanager from the context
Reference< XMultiComponentFactory > rServiceManager =
rComponentContext->getServiceManager();
// instantiate a sample service with the servicemanager.
Reference< XInterface > rInstance =
rServiceManager->createInstanceWithContext(
OUString("com.sun.star.bridge.UnoUrlResolver"),
rComponentContext );
// Query for the XUnoUrlResolver interface
Reference< XUnoUrlResolver > rResolver( rInstance, UNO_QUERY );
if( ! rResolver.is() )
{
printf( "Error: Couldn't instantiate com.sun.star.bridge.UnoUrlResolver service\n" );
return 1;
}
try
{
// resolve the uno-url
rInstance = rResolver->resolve( OUString(
"uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager" ) );
if( ! rInstance.is() )
{
printf( "StarOffice.ServiceManager is not exported from remote counterpart\n" );
return 1;
}
// query for the simpler XMultiServiceFactory interface, sufficient for scripting
Reference< XMultiServiceFactory > rOfficeServiceManager (rInstance, UNO_QUERY);
if( ! rInstance.is() )
{
printf( "XMultiServiceFactory interface is not exported for StarOffice.ServiceManager\n" );
return 1;
}
printf( "Connected sucessfully to the office\n" );
}
catch( Exception &e )
{
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "Error: %s\n", o.pData->buffer );
return 1;
}
return 0;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Fix SDK example
|
Fix SDK example
Change-Id: Ide65bcf203f78d1e8d3286f4ee19846a357fb364
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
06876d225aecac5643a633062c8b1eb2a4f91f99
|
lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCCodeEmitter.cpp
|
lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCCodeEmitter.cpp
|
//=- WebAssemblyMCCodeEmitter.cpp - Convert WebAssembly code to machine code -//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements the WebAssemblyMCCodeEmitter class.
///
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "mccodeemitter"
STATISTIC(MCNumEmitted, "Number of MC instructions emitted.");
STATISTIC(MCNumFixups, "Number of MC fixups created.");
namespace {
class WebAssemblyMCCodeEmitter final : public MCCodeEmitter {
const MCInstrInfo &MCII;
// Implementation generated by tablegen.
uint64_t getBinaryCodeForInstr(const MCInst &MI,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const;
void encodeInstruction(const MCInst &MI, raw_ostream &OS,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const override;
public:
WebAssemblyMCCodeEmitter(const MCInstrInfo &mcii) : MCII(mcii) {}
};
} // end anonymous namespace
MCCodeEmitter *llvm::createWebAssemblyMCCodeEmitter(const MCInstrInfo &MCII) {
return new WebAssemblyMCCodeEmitter(MCII);
}
void WebAssemblyMCCodeEmitter::encodeInstruction(
const MCInst &MI, raw_ostream &OS, SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
// FIXME: This is not the real binary encoding. This is an extremely
// over-simplified encoding where we just use uint64_t for everything. This
// is a temporary measure.
support::endian::Writer<support::little>(OS).write<uint64_t>(MI.getOpcode());
const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
if (Desc.isVariadic())
support::endian::Writer<support::little>(OS).write<uint64_t>(
MI.getNumOperands() - Desc.NumOperands);
for (unsigned i = 0, e = MI.getNumOperands(); i < e; ++i) {
const MCOperand &MO = MI.getOperand(i);
if (MO.isReg()) {
support::endian::Writer<support::little>(OS).write<uint64_t>(MO.getReg());
} else if (MO.isImm()) {
support::endian::Writer<support::little>(OS).write<uint64_t>(MO.getImm());
} else if (MO.isFPImm()) {
support::endian::Writer<support::little>(OS).write<double>(MO.getFPImm());
} else if (MO.isExpr()) {
support::endian::Writer<support::little>(OS).write<uint64_t>(0);
Fixups.push_back(MCFixup::create(
(1 + MCII.get(MI.getOpcode()).isVariadic() + i) * sizeof(uint64_t),
MO.getExpr(),
STI.getTargetTriple().isArch64Bit() ? FK_Data_8 : FK_Data_4,
MI.getLoc()));
++MCNumFixups;
} else {
llvm_unreachable("unexpected operand kind");
}
}
++MCNumEmitted; // Keep track of the # of mi's emitted.
}
#include "WebAssemblyGenMCCodeEmitter.inc"
|
//=- WebAssemblyMCCodeEmitter.cpp - Convert WebAssembly code to machine code -//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements the WebAssemblyMCCodeEmitter class.
///
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "mccodeemitter"
STATISTIC(MCNumEmitted, "Number of MC instructions emitted.");
STATISTIC(MCNumFixups, "Number of MC fixups created.");
namespace {
class WebAssemblyMCCodeEmitter final : public MCCodeEmitter {
const MCInstrInfo &MCII;
// Implementation generated by tablegen.
uint64_t getBinaryCodeForInstr(const MCInst &MI,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const;
void encodeInstruction(const MCInst &MI, raw_ostream &OS,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const override;
public:
WebAssemblyMCCodeEmitter(const MCInstrInfo &mcii) : MCII(mcii) {}
};
} // end anonymous namespace
MCCodeEmitter *llvm::createWebAssemblyMCCodeEmitter(const MCInstrInfo &MCII) {
return new WebAssemblyMCCodeEmitter(MCII);
}
void WebAssemblyMCCodeEmitter::encodeInstruction(
const MCInst &MI, raw_ostream &OS, SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
// FIXME: This is not the real binary encoding. This is an extremely
// over-simplified encoding where we just use uint64_t for everything. This
// is a temporary measure.
support::endian::Writer<support::little>(OS).write<uint64_t>(MI.getOpcode());
const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
if (Desc.isVariadic())
support::endian::Writer<support::little>(OS).write<uint64_t>(
MI.getNumOperands() - Desc.NumOperands);
for (unsigned i = 0, e = MI.getNumOperands(); i < e; ++i) {
const MCOperand &MO = MI.getOperand(i);
if (MO.isReg()) {
support::endian::Writer<support::little>(OS).write<uint64_t>(MO.getReg());
} else if (MO.isImm()) {
support::endian::Writer<support::little>(OS).write<uint64_t>(MO.getImm());
} else if (MO.isFPImm()) {
support::endian::Writer<support::little>(OS).write<double>(MO.getFPImm());
} else if (MO.isExpr()) {
support::endian::Writer<support::little>(OS).write<uint64_t>(0);
Fixups.push_back(MCFixup::create(
(1 + MCII.get(MI.getOpcode()).isVariadic() + i) * sizeof(uint64_t),
MO.getExpr(),
STI.getTargetTriple().isArch64Bit() ? FK_Data_8 : FK_Data_4,
MI.getLoc()));
++MCNumFixups;
} else {
llvm_unreachable("unexpected operand kind");
}
}
++MCNumEmitted; // Keep track of the # of mi's emitted.
}
#include "WebAssemblyGenMCCodeEmitter.inc"
|
Fix the wasm build by including EndianStream.h
|
Fix the wasm build by including EndianStream.h
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@273591 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm
|
3fb303abac88b76bfd7d197ae70df359ac869511
|
src/rdb_protocol/changefeed.hpp
|
src/rdb_protocol/changefeed.hpp
|
// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_CHANGEFEED_HPP_
#define RDB_PROTOCOL_CHANGEFEED_HPP_
#include <deque>
#include <exception>
#include <map>
#include <string>
#include <vector>
#include <utility>
#include "errors.hpp"
#include <boost/variant.hpp>
#include "concurrency/rwlock.hpp"
#include "containers/counted.hpp"
#include "containers/scoped.hpp"
#include "protocol_api.hpp"
#include "rdb_protocol/counted_term.hpp"
#include "region/region.hpp"
#include "repli_timestamp.hpp"
#include "rpc/connectivity/peer_id.hpp"
#include "rpc/mailbox/typed.hpp"
#include "rpc/serialize_macros.hpp"
class auto_drainer_t;
class namespace_interface_access_t;
class mailbox_manager_t;
struct rdb_modification_report_t;
namespace ql {
class base_exc_t;
class batcher_t;
class datum_stream_t;
class datum_t;
class env_t;
class table_t;
namespace changefeed {
struct msg_t {
struct change_t {
change_t();
explicit change_t(counted_t<const datum_t> _old_val,
counted_t<const datum_t> _new_val);
~change_t();
counted_t<const datum_t> old_val, new_val;
RDB_DECLARE_ME_SERIALIZABLE;
};
struct stop_t {
};
msg_t() { }
msg_t(msg_t &&msg);
explicit msg_t(stop_t &&op);
explicit msg_t(change_t &&op);
// We need to define the copy constructor. GCC 4.4 doesn't let use use `=
// default`, and SRH is uncomfortable violating the rule of 3, so we define
// the destructor and assignment operator as well.
msg_t(const msg_t &msg) : op(msg.op) { }
~msg_t() { }
const msg_t &operator=(const msg_t &msg) {
op = msg.op;
return *this;
}
// Starts with STOP to avoid doing work for default initialization.
boost::variant<stop_t, change_t> op;
};
RDB_SERIALIZE_OUTSIDE(msg_t::change_t);
RDB_DECLARE_SERIALIZABLE(msg_t::stop_t);
RDB_DECLARE_SERIALIZABLE(msg_t);
class feed_t;
struct stamped_msg_t;
typedef mailbox_addr_t<void(stamped_msg_t)> client_addr_t;
struct keyspec_t {
struct all_t { };
struct point_t {
point_t() { }
explicit point_t(counted_t<const datum_t> _key) : key(std::move(_key)) { }
counted_t<const datum_t> key;
};
keyspec_t(keyspec_t &&keyspec) = default;
explicit keyspec_t(all_t &&all) : spec(std::move(all)) { }
explicit keyspec_t(point_t &&point) : spec(std::move(point)) { }
// This needs to be copyable and assignable because it goes inside a
// `changefeed_stamp_t`, which goes inside a variant.
keyspec_t(const keyspec_t &keyspec) = default;
keyspec_t &operator=(const keyspec_t &) = default;
boost::variant<all_t, point_t> spec;
private:
keyspec_t() { }
};
region_t keyspec_to_region(const keyspec_t &keyspec);
RDB_DECLARE_SERIALIZABLE(keyspec_t::all_t);
RDB_DECLARE_SERIALIZABLE(keyspec_t::point_t);
RDB_DECLARE_SERIALIZABLE(keyspec_t);
// The `client_t` exists on the machine handling the changefeed query, in the
// `rdb_context_t`. When a query subscribes to the changes on a table, it
// should call `new_feed`. The `client_t` will give it back a stream of rows.
// The `client_t` does this by maintaining an internal map from table UUIDs to
// `feed_t`s. (It does this so that there is at most one `feed_t` per <table,
// client> pair, to prevent redundant cluster messages.) The actual logic for
// subscribing to a changefeed server and distributing writes to streams can be
// found in the `feed_t` class.
class client_t : public home_thread_mixin_t {
public:
typedef client_addr_t addr_t;
client_t(
mailbox_manager_t *_manager,
const std::function<
namespace_interface_access_t(
const namespace_id_t &,
signal_t *)
> &_namespace_source
);
~client_t();
// Throws QL exceptions.
counted_t<datum_stream_t> new_feed(env_t *env, const namespace_id_t &table,
const protob_t<const Backtrace> &bt, const std::string &table_name,
const std::string &pkey, keyspec_t &&keyspec);
void maybe_remove_feed(const namespace_id_t &uuid);
scoped_ptr_t<feed_t> detach_feed(const namespace_id_t &uuid);
private:
friend class subscription_t;
mailbox_manager_t *const manager;
std::function<
namespace_interface_access_t(
const namespace_id_t &,
signal_t *)
> const namespace_source;
std::map<namespace_id_t, scoped_ptr_t<feed_t> > feeds;
// This lock manages access to the `feeds` map. The `feeds` map needs to be
// read whenever `new_feed` is called, and needs to be written to whenever
// `new_feed` is called with a table not already in the `feeds` map, or
// whenever `maybe_remove_feed` or `detach_feed` is called.
//
// This lock is held for a long time when `new_feed` is called with a table
// not already in the `feeds` map (in fact, it's held long enough to do a
// cluster read). This should only be a problem if the number of tables
// (*not* the number of feeds) is large relative to read throughput, because
// otherwise most of the calls to `new_feed` that block will see the table
// as soon as they're woken up and won't have to do a second read.
rwlock_t feeds_lock;
auto_drainer_t drainer;
};
typedef mailbox_addr_t<void(client_addr_t)> server_addr_t;
// There is one `server_t` per `store_t`, and it is used to send changes that
// occur on that `store_t` to any subscribed `feed_t`s contained in a
// `client_t`.
class server_t {
public:
typedef server_addr_t addr_t;
explicit server_t(mailbox_manager_t *_manager);
~server_t();
void add_client(const client_t::addr_t &addr, region_t region);
// `key` should be non-NULL if there is a key associated with the message.
void send_all(msg_t msg, const store_key_t &key);
void stop_all();
addr_t get_stop_addr();
uint64_t get_stamp(const client_t::addr_t &addr);
uuid_u get_uuid();
private:
void stop_mailbox_cb(client_t::addr_t addr);
void add_client_cb(signal_t *stopped, client_t::addr_t addr);
// The UUID of the server, used so that `feed_t`s can enforce on ordering on
// changefeed messages on a per-server basis (and drop changefeed messages
// from before their own creation timestamp on a per-server basis).
const uuid_u uuid;
mailbox_manager_t *const manager;
struct client_info_t {
scoped_ptr_t<cond_t> cond;
uint64_t stamp;
std::vector<region_t> regions;
};
std::map<client_t::addr_t, client_info_t> clients;
void send_one_with_lock(const auto_drainer_t::lock_t &lock,
std::pair<const client_t::addr_t, client_info_t> *client,
msg_t msg);
// Controls access to `clients`. A `server_t` needs to read `clients` when:
// * `send_all` is called
// * `get_stamp` is called
// And needs to write to clients when:
// * `add_client` is called
// * `clear` is called
// * A message is received at `stop_mailbox` unsubscribing a client
// A lock is needed because e.g. `send_all` calls `send`, which can block,
// while looping over `clients`, and we need to make sure the map doesn't
// change under it.
rwlock_t clients_lock;
// Clients send a message to this mailbox with their address when they want
// to unsubscribe.
mailbox_t<void(client_t::addr_t)> stop_mailbox;
auto_drainer_t drainer;
};
} // namespace changefeed
} // namespace ql
#endif // RDB_PROTOCOL_CHANGEFEED_HPP_
|
// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_CHANGEFEED_HPP_
#define RDB_PROTOCOL_CHANGEFEED_HPP_
#include <deque>
#include <exception>
#include <map>
#include <string>
#include <vector>
#include <utility>
#include "errors.hpp"
#include <boost/variant.hpp>
#include "concurrency/rwlock.hpp"
#include "containers/counted.hpp"
#include "containers/scoped.hpp"
#include "protocol_api.hpp"
#include "rdb_protocol/counted_term.hpp"
#include "region/region.hpp"
#include "repli_timestamp.hpp"
#include "rpc/connectivity/peer_id.hpp"
#include "rpc/mailbox/typed.hpp"
#include "rpc/serialize_macros.hpp"
class auto_drainer_t;
class namespace_interface_access_t;
class mailbox_manager_t;
struct rdb_modification_report_t;
namespace ql {
class base_exc_t;
class batcher_t;
class datum_stream_t;
class datum_t;
class env_t;
class table_t;
namespace changefeed {
struct msg_t {
struct change_t {
change_t();
explicit change_t(counted_t<const datum_t> _old_val,
counted_t<const datum_t> _new_val);
~change_t();
counted_t<const datum_t> old_val, new_val;
RDB_DECLARE_ME_SERIALIZABLE;
};
struct stop_t {
};
msg_t() { }
msg_t(msg_t &&msg);
explicit msg_t(stop_t &&op);
explicit msg_t(change_t &&op);
// We need to define the copy constructor. GCC 4.4 doesn't let use use `=
// default`, and SRH is uncomfortable violating the rule of 3, so we define
// the destructor and assignment operator as well.
msg_t(const msg_t &msg) : op(msg.op) { }
~msg_t() { }
const msg_t &operator=(const msg_t &msg) {
op = msg.op;
return *this;
}
// Starts with STOP to avoid doing work for default initialization.
boost::variant<stop_t, change_t> op;
};
RDB_SERIALIZE_OUTSIDE(msg_t::change_t);
RDB_DECLARE_SERIALIZABLE(msg_t::stop_t);
RDB_DECLARE_SERIALIZABLE(msg_t);
class feed_t;
struct stamped_msg_t;
typedef mailbox_addr_t<void(stamped_msg_t)> client_addr_t;
struct keyspec_t {
struct all_t { };
struct point_t {
point_t() { }
explicit point_t(counted_t<const datum_t> _key) : key(std::move(_key)) { }
counted_t<const datum_t> key;
};
keyspec_t(keyspec_t &&keyspec) = default;
explicit keyspec_t(all_t &&all) : spec(std::move(all)) { }
explicit keyspec_t(point_t &&point) : spec(std::move(point)) { }
// This needs to be copyable and assignable because it goes inside a
// `changefeed_stamp_t`, which goes inside a variant.
keyspec_t(const keyspec_t &keyspec) = default;
keyspec_t &operator=(const keyspec_t &) = default;
boost::variant<all_t, point_t> spec;
private:
keyspec_t() { }
};
region_t keyspec_to_region(const keyspec_t &keyspec);
RDB_DECLARE_SERIALIZABLE(keyspec_t::all_t);
RDB_DECLARE_SERIALIZABLE(keyspec_t::point_t);
RDB_DECLARE_SERIALIZABLE(keyspec_t);
// The `client_t` exists on the machine handling the changefeed query, in the
// `rdb_context_t`. When a query subscribes to the changes on a table, it
// should call `new_feed`. The `client_t` will give it back a stream of rows.
// The `client_t` does this by maintaining an internal map from table UUIDs to
// `feed_t`s. (It does this so that there is at most one `feed_t` per <table,
// client> pair, to prevent redundant cluster messages.) The actual logic for
// subscribing to a changefeed server and distributing writes to streams can be
// found in the `feed_t` class.
class client_t : public home_thread_mixin_t {
public:
typedef client_addr_t addr_t;
client_t(
mailbox_manager_t *_manager,
const std::function<
namespace_interface_access_t(
const namespace_id_t &,
signal_t *)
> &_namespace_source
);
~client_t();
// Throws QL exceptions.
counted_t<datum_stream_t> new_feed(env_t *env, const namespace_id_t &table,
const protob_t<const Backtrace> &bt, const std::string &table_name,
const std::string &pkey, keyspec_t &&keyspec);
void maybe_remove_feed(const namespace_id_t &uuid);
scoped_ptr_t<feed_t> detach_feed(const namespace_id_t &uuid);
private:
friend class subscription_t;
mailbox_manager_t *const manager;
std::function<
namespace_interface_access_t(
const namespace_id_t &,
signal_t *)
> const namespace_source;
std::map<namespace_id_t, scoped_ptr_t<feed_t> > feeds;
// This lock manages access to the `feeds` map. The `feeds` map needs to be
// read whenever `new_feed` is called, and needs to be written to whenever
// `new_feed` is called with a table not already in the `feeds` map, or
// whenever `maybe_remove_feed` or `detach_feed` is called.
//
// This lock is held for a long time when `new_feed` is called with a table
// not already in the `feeds` map (in fact, it's held long enough to do a
// cluster read). This should only be a problem if the number of tables
// (*not* the number of feeds) is large relative to read throughput, because
// otherwise most of the calls to `new_feed` that block will see the table
// as soon as they're woken up and won't have to do a second read.
rwlock_t feeds_lock;
auto_drainer_t drainer;
};
typedef mailbox_addr_t<void(client_addr_t)> server_addr_t;
// There is one `server_t` per `store_t`, and it is used to send changes that
// occur on that `store_t` to any subscribed `feed_t`s contained in a
// `client_t`.
class server_t {
public:
typedef server_addr_t addr_t;
explicit server_t(mailbox_manager_t *_manager);
~server_t();
void add_client(const client_t::addr_t &addr, region_t region);
// `key` should be non-NULL if there is a key associated with the message.
void send_all(msg_t msg, const store_key_t &key);
void stop_all();
addr_t get_stop_addr();
uint64_t get_stamp(const client_t::addr_t &addr);
uuid_u get_uuid();
private:
void stop_mailbox_cb(client_t::addr_t addr);
void add_client_cb(signal_t *stopped, client_t::addr_t addr);
// The UUID of the server, used so that `feed_t`s can enforce on ordering on
// changefeed messages on a per-server basis (and drop changefeed messages
// from before their own creation timestamp on a per-server basis).
const uuid_u uuid;
mailbox_manager_t *const manager;
struct client_info_t {
scoped_ptr_t<cond_t> cond;
uint64_t stamp;
std::vector<region_t> regions;
};
std::map<client_t::addr_t, client_info_t> clients;
void send_one_with_lock(const auto_drainer_t::lock_t &lock,
std::pair<const client_t::addr_t, client_info_t> *client,
msg_t msg);
// Controls access to `clients`. A `server_t` needs to read `clients` when:
// * `send_all` is called
// * `get_stamp` is called
// And needs to write to clients when:
// * `add_client` is called
// * `clear` is called
// * A message is received at `stop_mailbox` unsubscribing a client
// A lock is needed because e.g. `send_all` calls `send`, which can block,
// while looping over `clients`, and we need to make sure the map doesn't
// change under it.
rwlock_t clients_lock;
auto_drainer_t drainer;
// Clients send a message to this mailbox with their address when they want
// to unsubscribe. The callback of this mailbox acquires the drainer, so it
// has to be destroyed first.
mailbox_t<void(client_t::addr_t)> stop_mailbox;
};
} // namespace changefeed
} // namespace ql
#endif // RDB_PROTOCOL_CHANGEFEED_HPP_
|
Fix mailbox drainer bug in changefeeds.
|
Fix mailbox drainer bug in changefeeds.
|
C++
|
apache-2.0
|
alash3al/rethinkdb,robertjpayne/rethinkdb,yakovenkodenis/rethinkdb,spblightadv/rethinkdb,ayumilong/rethinkdb,mbroadst/rethinkdb,4talesa/rethinkdb,robertjpayne/rethinkdb,KSanthanam/rethinkdb,robertjpayne/rethinkdb,Qinusty/rethinkdb,tempbottle/rethinkdb,wkennington/rethinkdb,ajose01/rethinkdb,gavioto/rethinkdb,losywee/rethinkdb,Qinusty/rethinkdb,sontek/rethinkdb,eliangidoni/rethinkdb,4talesa/rethinkdb,mbroadst/rethinkdb,greyhwndz/rethinkdb,niieani/rethinkdb,bchavez/rethinkdb,RubenKelevra/rethinkdb,AntouanK/rethinkdb,yaolinz/rethinkdb,lenstr/rethinkdb,JackieXie168/rethinkdb,AntouanK/rethinkdb,niieani/rethinkdb,scripni/rethinkdb,lenstr/rethinkdb,robertjpayne/rethinkdb,bchavez/rethinkdb,bchavez/rethinkdb,robertjpayne/rethinkdb,mquandalle/rethinkdb,AntouanK/rethinkdb,elkingtonmcb/rethinkdb,tempbottle/rethinkdb,Qinusty/rethinkdb,tempbottle/rethinkdb,alash3al/rethinkdb,marshall007/rethinkdb,jmptrader/rethinkdb,catroot/rethinkdb,ajose01/rethinkdb,sontek/rethinkdb,sebadiaz/rethinkdb,catroot/rethinkdb,captainpete/rethinkdb,elkingtonmcb/rethinkdb,mquandalle/rethinkdb,sebadiaz/rethinkdb,bchavez/rethinkdb,rrampage/rethinkdb,gavioto/rethinkdb,grandquista/rethinkdb,spblightadv/rethinkdb,alash3al/rethinkdb,wkennington/rethinkdb,jesseditson/rethinkdb,4talesa/rethinkdb,yaolinz/rethinkdb,urandu/rethinkdb,greyhwndz/rethinkdb,tempbottle/rethinkdb,urandu/rethinkdb,gdi2290/rethinkdb,4talesa/rethinkdb,captainpete/rethinkdb,KSanthanam/rethinkdb,spblightadv/rethinkdb,Wilbeibi/rethinkdb,matthaywardwebdesign/rethinkdb,catroot/rethinkdb,pap/rethinkdb,yakovenkodenis/rethinkdb,marshall007/rethinkdb,captainpete/rethinkdb,wojons/rethinkdb,RubenKelevra/rethinkdb,marshall007/rethinkdb,marshall007/rethinkdb,yakovenkodenis/rethinkdb,urandu/rethinkdb,grandquista/rethinkdb,eliangidoni/rethinkdb,sbusso/rethinkdb,sbusso/rethinkdb,KSanthanam/rethinkdb,matthaywardwebdesign/rethinkdb,lenstr/rethinkdb,grandquista/rethinkdb,lenstr/rethinkdb,gdi2290/rethinkdb,victorbriz/rethinkdb,captainpete/rethinkdb,mquandalle/rethinkdb,gavioto/rethinkdb,matthaywardwebdesign/rethinkdb,sontek/rethinkdb,KSanthanam/rethinkdb,greyhwndz/rethinkdb,losywee/rethinkdb,tempbottle/rethinkdb,RubenKelevra/rethinkdb,tempbottle/rethinkdb,ayumilong/rethinkdb,gdi2290/rethinkdb,dparnell/rethinkdb,AntouanK/rethinkdb,ajose01/rethinkdb,spblightadv/rethinkdb,urandu/rethinkdb,yaolinz/rethinkdb,RubenKelevra/rethinkdb,eliangidoni/rethinkdb,alash3al/rethinkdb,dparnell/rethinkdb,wkennington/rethinkdb,Qinusty/rethinkdb,gavioto/rethinkdb,gavioto/rethinkdb,bchavez/rethinkdb,ayumilong/rethinkdb,mbroadst/rethinkdb,scripni/rethinkdb,pap/rethinkdb,victorbriz/rethinkdb,marshall007/rethinkdb,yakovenkodenis/rethinkdb,bpradipt/rethinkdb,mcanthony/rethinkdb,mquandalle/rethinkdb,yakovenkodenis/rethinkdb,dparnell/rethinkdb,KSanthanam/rethinkdb,tempbottle/rethinkdb,jmptrader/rethinkdb,niieani/rethinkdb,wojons/rethinkdb,AntouanK/rethinkdb,alash3al/rethinkdb,captainpete/rethinkdb,grandquista/rethinkdb,matthaywardwebdesign/rethinkdb,ajose01/rethinkdb,mcanthony/rethinkdb,wkennington/rethinkdb,catroot/rethinkdb,bchavez/rethinkdb,4talesa/rethinkdb,scripni/rethinkdb,JackieXie168/rethinkdb,sebadiaz/rethinkdb,yakovenkodenis/rethinkdb,losywee/rethinkdb,captainpete/rethinkdb,Qinusty/rethinkdb,catroot/rethinkdb,scripni/rethinkdb,urandu/rethinkdb,rrampage/rethinkdb,KSanthanam/rethinkdb,gdi2290/rethinkdb,jesseditson/rethinkdb,losywee/rethinkdb,wujf/rethinkdb,dparnell/rethinkdb,jmptrader/rethinkdb,dparnell/rethinkdb,Wilbeibi/rethinkdb,jmptrader/rethinkdb,yaolinz/rethinkdb,greyhwndz/rethinkdb,elkingtonmcb/rethinkdb,mquandalle/rethinkdb,mcanthony/rethinkdb,bpradipt/rethinkdb,niieani/rethinkdb,JackieXie168/rethinkdb,JackieXie168/rethinkdb,lenstr/rethinkdb,4talesa/rethinkdb,niieani/rethinkdb,jesseditson/rethinkdb,yaolinz/rethinkdb,jmptrader/rethinkdb,JackieXie168/rethinkdb,alash3al/rethinkdb,sbusso/rethinkdb,4talesa/rethinkdb,sontek/rethinkdb,yakovenkodenis/rethinkdb,eliangidoni/rethinkdb,robertjpayne/rethinkdb,elkingtonmcb/rethinkdb,Qinusty/rethinkdb,matthaywardwebdesign/rethinkdb,ayumilong/rethinkdb,jmptrader/rethinkdb,grandquista/rethinkdb,wujf/rethinkdb,sebadiaz/rethinkdb,pap/rethinkdb,losywee/rethinkdb,wkennington/rethinkdb,wujf/rethinkdb,ajose01/rethinkdb,alash3al/rethinkdb,bpradipt/rethinkdb,ayumilong/rethinkdb,ajose01/rethinkdb,Qinusty/rethinkdb,JackieXie168/rethinkdb,mcanthony/rethinkdb,marshall007/rethinkdb,bpradipt/rethinkdb,wojons/rethinkdb,Wilbeibi/rethinkdb,Wilbeibi/rethinkdb,pap/rethinkdb,wojons/rethinkdb,Wilbeibi/rethinkdb,wujf/rethinkdb,eliangidoni/rethinkdb,JackieXie168/rethinkdb,grandquista/rethinkdb,spblightadv/rethinkdb,eliangidoni/rethinkdb,scripni/rethinkdb,rrampage/rethinkdb,marshall007/rethinkdb,wojons/rethinkdb,losywee/rethinkdb,lenstr/rethinkdb,AntouanK/rethinkdb,urandu/rethinkdb,KSanthanam/rethinkdb,ajose01/rethinkdb,mquandalle/rethinkdb,bchavez/rethinkdb,matthaywardwebdesign/rethinkdb,greyhwndz/rethinkdb,dparnell/rethinkdb,urandu/rethinkdb,yaolinz/rethinkdb,elkingtonmcb/rethinkdb,rrampage/rethinkdb,mcanthony/rethinkdb,captainpete/rethinkdb,ayumilong/rethinkdb,scripni/rethinkdb,urandu/rethinkdb,grandquista/rethinkdb,sebadiaz/rethinkdb,gavioto/rethinkdb,greyhwndz/rethinkdb,pap/rethinkdb,wojons/rethinkdb,grandquista/rethinkdb,KSanthanam/rethinkdb,bpradipt/rethinkdb,sbusso/rethinkdb,RubenKelevra/rethinkdb,AntouanK/rethinkdb,victorbriz/rethinkdb,gavioto/rethinkdb,dparnell/rethinkdb,eliangidoni/rethinkdb,rrampage/rethinkdb,victorbriz/rethinkdb,victorbriz/rethinkdb,wujf/rethinkdb,wojons/rethinkdb,spblightadv/rethinkdb,dparnell/rethinkdb,wkennington/rethinkdb,niieani/rethinkdb,bpradipt/rethinkdb,elkingtonmcb/rethinkdb,spblightadv/rethinkdb,jmptrader/rethinkdb,losywee/rethinkdb,grandquista/rethinkdb,mbroadst/rethinkdb,matthaywardwebdesign/rethinkdb,greyhwndz/rethinkdb,greyhwndz/rethinkdb,mbroadst/rethinkdb,yaolinz/rethinkdb,wkennington/rethinkdb,captainpete/rethinkdb,rrampage/rethinkdb,RubenKelevra/rethinkdb,mquandalle/rethinkdb,pap/rethinkdb,jesseditson/rethinkdb,rrampage/rethinkdb,ayumilong/rethinkdb,tempbottle/rethinkdb,elkingtonmcb/rethinkdb,Qinusty/rethinkdb,sebadiaz/rethinkdb,wujf/rethinkdb,gdi2290/rethinkdb,mcanthony/rethinkdb,victorbriz/rethinkdb,ayumilong/rethinkdb,matthaywardwebdesign/rethinkdb,sbusso/rethinkdb,gavioto/rethinkdb,jmptrader/rethinkdb,scripni/rethinkdb,pap/rethinkdb,scripni/rethinkdb,mbroadst/rethinkdb,sbusso/rethinkdb,lenstr/rethinkdb,sontek/rethinkdb,bpradipt/rethinkdb,Wilbeibi/rethinkdb,mcanthony/rethinkdb,robertjpayne/rethinkdb,victorbriz/rethinkdb,bchavez/rethinkdb,eliangidoni/rethinkdb,jesseditson/rethinkdb,jesseditson/rethinkdb,jesseditson/rethinkdb,sebadiaz/rethinkdb,spblightadv/rethinkdb,rrampage/rethinkdb,robertjpayne/rethinkdb,bpradipt/rethinkdb,marshall007/rethinkdb,yaolinz/rethinkdb,dparnell/rethinkdb,4talesa/rethinkdb,robertjpayne/rethinkdb,elkingtonmcb/rethinkdb,mquandalle/rethinkdb,sontek/rethinkdb,wujf/rethinkdb,JackieXie168/rethinkdb,gdi2290/rethinkdb,RubenKelevra/rethinkdb,alash3al/rethinkdb,eliangidoni/rethinkdb,mcanthony/rethinkdb,Wilbeibi/rethinkdb,pap/rethinkdb,wojons/rethinkdb,lenstr/rethinkdb,mbroadst/rethinkdb,catroot/rethinkdb,sontek/rethinkdb,RubenKelevra/rethinkdb,victorbriz/rethinkdb,wkennington/rethinkdb,niieani/rethinkdb,mbroadst/rethinkdb,losywee/rethinkdb,bpradipt/rethinkdb,yakovenkodenis/rethinkdb,jesseditson/rethinkdb,mbroadst/rethinkdb,niieani/rethinkdb,sbusso/rethinkdb,sontek/rethinkdb,bchavez/rethinkdb,AntouanK/rethinkdb,sebadiaz/rethinkdb,ajose01/rethinkdb,catroot/rethinkdb,Wilbeibi/rethinkdb,JackieXie168/rethinkdb,catroot/rethinkdb,Qinusty/rethinkdb,sbusso/rethinkdb,gdi2290/rethinkdb
|
59d9436973147d0b944ef8452b41574c496509d5
|
src/txmodel.cpp
|
src/txmodel.cpp
|
///////////////////////////////////////////////////////////////////////////////
//
// CoinVault
//
// txmodel.cpp
//
// Copyright (c) 2013 Eric Lombrozo
//
// All Rights Reserved.
#include "txmodel.h"
#include <CoinQ/CoinQ_script.h>
#include <CoinQ/CoinQ_netsync.h>
#include <stdutils/stringutils.h>
#include <QStandardItemModel>
#include <QDateTime>
#include <QMessageBox>
#include "settings.h"
#include "coinparams.h"
#include "severitylogger.h"
using namespace CoinDB;
using namespace CoinQ::Script;
using namespace std;
TxModel::TxModel(QObject* parent)
: QStandardItemModel(parent)
{
base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();
base58_versions[1] = getCoinParams().pay_to_script_hash_version();
initColumns();
}
TxModel::TxModel(CoinDB::Vault* vault, const QString& accountName, QObject* parent)
: QStandardItemModel(parent)
{
base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();
base58_versions[1] = getCoinParams().pay_to_script_hash_version();
initColumns();
setVault(vault);
setAccount(accountName);
}
void TxModel::initColumns()
{
QStringList columns;
columns << tr("Time") << tr("Description") << tr("Type") << tr("Amount") << tr("Fee") << tr("Balance") << tr("Confirmations") << tr("Address") << tr("Transaction Hash");
setHorizontalHeaderLabels(columns);
}
void TxModel::setVault(CoinDB::Vault* vault)
{
this->vault = vault;
accountName.clear();
update();
}
void TxModel::setAccount(const QString& accountName)
{
if (!vault) {
throw std::runtime_error("Vault is not open.");
}
if (!vault->accountExists(accountName.toStdString())) {
throw std::runtime_error("Account not found.");
}
this->accountName = accountName;
update();
}
void TxModel::update()
{
removeRows(0, rowCount());
if (!vault || accountName.isEmpty()) return;
std::shared_ptr<BlockHeader> bestHeader = vault->getBestBlockHeader();
std::vector<TxOutView> txoutviews = vault->getTxOutViews(accountName.toStdString(), "", TxOut::ROLE_BOTH, TxOut::BOTH, Tx::ALL, true);
bytes_t last_txhash;
typedef std::pair<unsigned long, uint32_t> sorting_info_t;
typedef std::pair<QList<QStandardItem*>, int64_t> value_row_t; // used to associate output values with rows for computing balance
typedef std::pair<sorting_info_t, value_row_t> sortable_row_t;
QList<sortable_row_t> rows;
for (auto& item: txoutviews) {
QList<QStandardItem*> row;
QDateTime utc;
utc.setTime_t(item.tx_timestamp);
QString time = utc.toLocalTime().toString();
QString description = QString::fromStdString(item.role_label());
if (description.isEmpty()) description = "Not available";
// The type stuff is just to test the new db schema. It's all wrong, we're not going to use TxOutViews for this.
QString type;
QString amount;
QString fee;
int64_t value = 0;
bytes_t this_txhash = item.tx_status == Tx::UNSIGNED ? item.tx_unsigned_hash : item.tx_hash;
switch (item.role_flags) {
case TxOut::ROLE_NONE:
type = tr("None");
break;
case TxOut::ROLE_SENDER:
type = tr("Send");
amount = "-";
value -= item.value;
if (item.tx_has_all_outpoints && item.tx_fee > 0) {
if (this_txhash != last_txhash) {
fee = "-";
fee += QString::number(item.tx_fee/100000000.0, 'g', 8);
value -= item.tx_fee;
last_txhash = this_txhash;
}
else {
fee = "||";
}
}
break;
case TxOut::ROLE_RECEIVER:
type = tr("Receive");
amount = "+";
value += item.value;
break;
default:
type = tr("Unknown");
}
amount += QString::number(item.value/100000000.0, 'g', 8);
uint32_t nConfirmations = 0;
QString confirmations;
if (item.tx_status >= Tx::PROPAGATED) {
if (bestHeader && item.height) {
nConfirmations = bestHeader->height() + 1 - item.height;
confirmations = QString::number(nConfirmations);
}
else {
confirmations = "0";
}
}
else if (item.tx_status == Tx::UNSIGNED) {
confirmations = tr("Unsigned");
}
else if (item.tx_status == Tx::UNSENT) {
confirmations = tr("Unsent");
}
QStandardItem* confirmationsItem = new QStandardItem(confirmations);
confirmationsItem->setData(item.tx_status, Qt::UserRole);
QString address = QString::fromStdString(getAddressForTxOutScript(item.script, base58_versions));
QString hash = QString::fromStdString(uchar_vector(this_txhash).getHex());
row.append(new QStandardItem(time));
row.append(new QStandardItem(description));
row.append(new QStandardItem(type));
row.append(new QStandardItem(amount));
row.append(new QStandardItem(fee));
row.append(new QStandardItem("")); // placeholder for balance, once sorted
row.append(confirmationsItem);
row.append(new QStandardItem(address));
row.append(new QStandardItem(hash));
rows.append(std::make_pair(std::make_pair(item.tx_id, nConfirmations), std::make_pair(row, value)));
}
qSort(rows.begin(), rows.end(), [](const sortable_row_t& a, const sortable_row_t& b) {
sorting_info_t a_info = a.first;
sorting_info_t b_info = b.first;
// if confirmation counts are equal
if (a_info.second == b_info.second) {
// if one value is positive and the other is negative, sort so that running balance remains positive
if (a.second.second < 0 && b.second.second > 0) return true;
if (a.second.second > 0 && b.second.second < 0) return false;
// otherwise sort by descending index
return (a_info.first > b_info.first);
}
// otherwise sort by ascending confirmation count
return (a_info.second < b_info.second);
});
// iterate in reverse order to compute running balance
int64_t balance = 0;
for (int i = rows.size() - 1; i >= 0; i--) {
balance += rows[i].second.second;
(rows[i].second.first)[5]->setText(QString::number(balance/100000000.0, 'g', 8));
}
// iterate in forward order to display
for (auto& row: rows) appendRow(row.second.first);
}
void TxModel::signTx(int row)
{
LOGGER(trace) << "TxModel::signTx(" << row << ")" << std::endl;
if (row == -1 || row >= rowCount()) {
throw std::runtime_error(tr("Invalid row.").toStdString());
}
QStandardItem* typeItem = item(row, 6);
int type = typeItem->data(Qt::UserRole).toInt();
if (type != CoinDB::Tx::UNSIGNED) {
throw std::runtime_error(tr("Transaction is already signed.").toStdString());
}
QStandardItem* txHashItem = item(row, 8);
uchar_vector txhash;
txhash.setHex(txHashItem->text().toStdString());
std::vector<std::string> keychainNames;
std::shared_ptr<Tx> tx = vault->signTx(txhash, keychainNames, true);
if (!tx) throw std::runtime_error(tr("No new signatures were added.").toStdString());
LOGGER(trace) << "TxModel::signTx - signature(s) added. raw tx: " << uchar_vector(tx->raw()).getHex() << std::endl;
update();
QString msg;
if (keychainNames.empty())
{
msg = tr("No new signatures were added.");
}
else
{
msg = tr("Signatures added using keychain(s) ") + QString::fromStdString(stdutils::delimited_list(keychainNames, ", ")) + tr(".");
}
emit txSigned(msg);
}
void TxModel::sendTx(int row, CoinQ::Network::NetworkSync* networkSync)
{
if (row == -1 || row >= rowCount()) {
throw std::runtime_error(tr("Invalid row.").toStdString());
}
if (!networkSync || !networkSync->isConnected()) {
throw std::runtime_error(tr("Must be connected to network to send.").toStdString());
}
QStandardItem* typeItem = item(row, 6);
int type = typeItem->data(Qt::UserRole).toInt();
if (type == CoinDB::Tx::UNSIGNED) {
throw std::runtime_error(tr("Transaction must be fully signed before sending.").toStdString());
}
else if (type == CoinDB::Tx::PROPAGATED) {
throw std::runtime_error(tr("Transaction already sent.").toStdString());
}
QStandardItem* txHashItem = item(row, 8);
uchar_vector txhash;
txhash.setHex(txHashItem->text().toStdString());
std::shared_ptr<CoinDB::Tx> tx = vault->getTx(txhash);
Coin::Transaction coin_tx = tx->toCoinCore();
networkSync->sendTx(coin_tx);
// TODO: Check transaction has propagated before changing status to PROPAGATED
tx->updateStatus(CoinDB::Tx::PROPAGATED);
vault->insertTx(tx);
update();
// networkSync->getTx(txhash);
}
std::shared_ptr<Tx> TxModel::getTx(int row)
{
if (row == -1 || row >= rowCount()) {
throw std::runtime_error(tr("Invalid row.").toStdString());
}
QStandardItem* txHashItem = item(row, 8);
uchar_vector txhash;
txhash.setHex(txHashItem->text().toStdString());
return vault->getTx(txhash);
}
void TxModel::deleteTx(int row)
{
if (row == -1 || row >= rowCount()) {
throw std::runtime_error(tr("Invalid row.").toStdString());
}
QStandardItem* txHashItem = item(row, 8);
uchar_vector txhash;
txhash.setHex(txHashItem->text().toStdString());
vault->deleteTx(txhash);
update();
emit txDeleted();
}
QVariant TxModel::data(const QModelIndex& index, int role) const
{
// Right-align numeric fields
if (role == Qt::TextAlignmentRole && index.column() >= 3 && index.column() <= 6) {
return Qt::AlignRight;
}
else {
return QStandardItemModel::data(index, role);
}
}
Qt::ItemFlags TxModel::flags(const QModelIndex& /*index*/) const
{
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}
|
///////////////////////////////////////////////////////////////////////////////
//
// CoinVault
//
// txmodel.cpp
//
// Copyright (c) 2013 Eric Lombrozo
//
// All Rights Reserved.
#include "txmodel.h"
#include <CoinQ/CoinQ_script.h>
#include <CoinQ/CoinQ_netsync.h>
#include <stdutils/stringutils.h>
#include <QStandardItemModel>
#include <QDateTime>
#include <QMessageBox>
#include "settings.h"
#include "coinparams.h"
#include "severitylogger.h"
using namespace CoinDB;
using namespace CoinQ::Script;
using namespace std;
TxModel::TxModel(QObject* parent)
: QStandardItemModel(parent)
{
base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();
base58_versions[1] = getCoinParams().pay_to_script_hash_version();
initColumns();
}
TxModel::TxModel(CoinDB::Vault* vault, const QString& accountName, QObject* parent)
: QStandardItemModel(parent)
{
base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();
base58_versions[1] = getCoinParams().pay_to_script_hash_version();
initColumns();
setVault(vault);
setAccount(accountName);
}
void TxModel::initColumns()
{
QStringList columns;
columns << tr("Time") << tr("Description") << tr("Type") << tr("Amount") << tr("Fee") << tr("Balance") << tr("Confirmations") << tr("Address") << tr("Transaction Hash");
setHorizontalHeaderLabels(columns);
}
void TxModel::setVault(CoinDB::Vault* vault)
{
this->vault = vault;
accountName.clear();
update();
}
void TxModel::setAccount(const QString& accountName)
{
if (!vault) {
throw std::runtime_error("Vault is not open.");
}
if (!vault->accountExists(accountName.toStdString())) {
throw std::runtime_error("Account not found.");
}
this->accountName = accountName;
update();
}
void TxModel::update()
{
removeRows(0, rowCount());
if (!vault || accountName.isEmpty()) return;
std::shared_ptr<BlockHeader> bestHeader = vault->getBestBlockHeader();
std::vector<TxOutView> txoutviews = vault->getTxOutViews(accountName.toStdString(), "", TxOut::ROLE_BOTH, TxOut::BOTH, Tx::ALL, true);
bytes_t last_txhash;
typedef std::pair<unsigned long, uint32_t> sorting_info_t;
typedef std::pair<QList<QStandardItem*>, int64_t> value_row_t; // used to associate output values with rows for computing balance
typedef std::pair<sorting_info_t, value_row_t> sortable_row_t;
QList<sortable_row_t> rows;
for (auto& item: txoutviews) {
QList<QStandardItem*> row;
QDateTime utc;
utc.setTime_t(item.tx_timestamp);
QString time = utc.toLocalTime().toString();
QString description = QString::fromStdString(item.role_label());
if (description.isEmpty()) description = "Not available";
// The type stuff is just to test the new db schema. It's all wrong, we're not going to use TxOutViews for this.
QString type;
QString amount;
QString fee;
int64_t value = 0;
bytes_t this_txhash = item.tx_status == Tx::UNSIGNED ? item.tx_unsigned_hash : item.tx_hash;
switch (item.role_flags) {
case TxOut::ROLE_NONE:
type = tr("None");
break;
case TxOut::ROLE_SENDER:
type = tr("Send");
amount = "-";
value -= item.value;
if (item.tx_has_all_outpoints && item.tx_fee > 0) {
if (this_txhash != last_txhash) {
fee = "-";
fee += QString::number(item.tx_fee/100000000.0, 'g', 8);
value -= item.tx_fee;
last_txhash = this_txhash;
}
else {
fee = "||";
}
}
break;
case TxOut::ROLE_RECEIVER:
type = tr("Receive");
amount = "+";
value += item.value;
break;
default:
type = tr("Unknown");
}
amount += QString::number(item.value/100000000.0, 'g', 8);
uint32_t nConfirmations = 0;
QString confirmations;
if (item.tx_status >= Tx::PROPAGATED) {
if (bestHeader && item.height) {
nConfirmations = bestHeader->height() + 1 - item.height;
confirmations = QString::number(nConfirmations);
}
else {
confirmations = "0";
}
}
else if (item.tx_status == Tx::UNSIGNED) {
confirmations = tr("Unsigned");
}
else if (item.tx_status == Tx::UNSENT) {
confirmations = tr("Unsent");
}
QStandardItem* confirmationsItem = new QStandardItem(confirmations);
confirmationsItem->setData(item.tx_status, Qt::UserRole);
QString address = QString::fromStdString(getAddressForTxOutScript(item.script, base58_versions));
QString hash = QString::fromStdString(uchar_vector(this_txhash).getHex());
row.append(new QStandardItem(time));
row.append(new QStandardItem(description));
row.append(new QStandardItem(type));
row.append(new QStandardItem(amount));
row.append(new QStandardItem(fee));
row.append(new QStandardItem("")); // placeholder for balance, once sorted
row.append(confirmationsItem);
row.append(new QStandardItem(address));
row.append(new QStandardItem(hash));
rows.append(std::make_pair(std::make_pair(item.tx_id, nConfirmations), std::make_pair(row, value)));
}
qSort(rows.begin(), rows.end(), [](const sortable_row_t& a, const sortable_row_t& b) {
sorting_info_t a_info = a.first;
sorting_info_t b_info = b.first;
// if confirmation counts are equal
if (a_info.second == b_info.second) {
// if one value is positive and the other is negative, sort so that running balance remains positive
if (a.second.second < 0 && b.second.second > 0) return true;
if (a.second.second > 0 && b.second.second < 0) return false;
// otherwise sort by descending index
return (a_info.first > b_info.first);
}
// otherwise sort by ascending confirmation count
return (a_info.second < b_info.second);
});
// iterate in reverse order to compute running balance
int64_t balance = 0;
for (int i = rows.size() - 1; i >= 0; i--) {
balance += rows[i].second.second;
(rows[i].second.first)[5]->setText(QString::number(balance/100000000.0, 'g', 8));
}
// iterate in forward order to display
for (auto& row: rows) appendRow(row.second.first);
}
void TxModel::signTx(int row)
{
LOGGER(trace) << "TxModel::signTx(" << row << ")" << std::endl;
if (row == -1 || row >= rowCount()) {
throw std::runtime_error(tr("Invalid row.").toStdString());
}
QStandardItem* typeItem = item(row, 6);
int type = typeItem->data(Qt::UserRole).toInt();
if (type != CoinDB::Tx::UNSIGNED) {
throw std::runtime_error(tr("Transaction is already signed.").toStdString());
}
QStandardItem* txHashItem = item(row, 8);
uchar_vector txhash;
txhash.setHex(txHashItem->text().toStdString());
std::vector<std::string> keychainNames;
std::shared_ptr<Tx> tx = vault->signTx(txhash, keychainNames, true);
if (!tx) throw std::runtime_error(tr("No new signatures were added.").toStdString());
LOGGER(trace) << "TxModel::signTx - signature(s) added. raw tx: " << uchar_vector(tx->raw()).getHex() << std::endl;
update();
QString msg;
if (keychainNames.empty())
{
msg = tr("No new signatures were added.");
}
else
{
msg = tr("Signatures added using keychain(s) ") + QString::fromStdString(stdutils::delimited_list(keychainNames, ", ")) + tr(".");
}
emit txSigned(msg);
}
void TxModel::sendTx(int row, CoinQ::Network::NetworkSync* networkSync)
{
if (row == -1 || row >= rowCount()) {
throw std::runtime_error(tr("Invalid row.").toStdString());
}
if (!networkSync || !networkSync->isConnected()) {
throw std::runtime_error(tr("Must be connected to network to send.").toStdString());
}
QStandardItem* typeItem = item(row, 6);
int type = typeItem->data(Qt::UserRole).toInt();
if (type == CoinDB::Tx::UNSIGNED) {
throw std::runtime_error(tr("Transaction must be fully signed before sending.").toStdString());
}
else if (type == CoinDB::Tx::PROPAGATED) {
throw std::runtime_error(tr("Transaction already sent.").toStdString());
}
QStandardItem* txHashItem = item(row, 8);
uchar_vector txhash;
txhash.setHex(txHashItem->text().toStdString());
std::shared_ptr<CoinDB::Tx> tx = vault->getTx(txhash);
Coin::Transaction coin_tx = tx->toCoinCore();
networkSync->sendTx(coin_tx);
// TODO: Check transaction has propagated before changing status to PROPAGATED
// tx->updateStatus(CoinDB::Tx::PROPAGATED);
// vault->insertTx(tx);
// update();
networkSync->getTx(txhash);
}
std::shared_ptr<Tx> TxModel::getTx(int row)
{
if (row == -1 || row >= rowCount()) {
throw std::runtime_error(tr("Invalid row.").toStdString());
}
QStandardItem* txHashItem = item(row, 8);
uchar_vector txhash;
txhash.setHex(txHashItem->text().toStdString());
return vault->getTx(txhash);
}
void TxModel::deleteTx(int row)
{
if (row == -1 || row >= rowCount()) {
throw std::runtime_error(tr("Invalid row.").toStdString());
}
QStandardItem* txHashItem = item(row, 8);
uchar_vector txhash;
txhash.setHex(txHashItem->text().toStdString());
vault->deleteTx(txhash);
update();
emit txDeleted();
}
QVariant TxModel::data(const QModelIndex& index, int role) const
{
// Right-align numeric fields
if (role == Qt::TextAlignmentRole && index.column() >= 3 && index.column() <= 6) {
return Qt::AlignRight;
}
else {
return QStandardItemModel::data(index, role);
}
}
Qt::ItemFlags TxModel::flags(const QModelIndex& /*index*/) const
{
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}
|
Check for tx propagation by requesting it back from peer.
|
Check for tx propagation by requesting it back from peer.
|
C++
|
mit
|
ciphrex/mSIGNA,Faldon/mSIGNA,ciphrex/mSIGNA,Faldon/mSIGNA,ciphrex/mSIGNA
|
b0fe05931adfcbf82b14a3acb83f8f471d1c7f4c
|
test/test_affine.cpp
|
test/test_affine.cpp
|
#include "loss.h"
#include "utest.h"
#include "trainer.h"
#include "criterion.h"
#include "math/epsilon.h"
#include "tasks/task_affine.h"
#include "layers/make_layers.h"
using namespace nano;
const auto idims = tensor_size_t(3);
const auto irows = tensor_size_t(5);
const auto icols = tensor_size_t(7);
const auto osize = tensor_size_t(4);
const auto count = tensor_size_t(1000);
const auto noise = epsilon2<scalar_t>();
NANO_BEGIN_MODULE(test_affine)
NANO_CASE(construction)
{
affine_task_t task(to_params(
"idims", idims, "irows", irows, "icols", icols, "osize", osize, "count", count, "noise", noise));
task.load();
NANO_CHECK_EQUAL(task.idims(), idims);
NANO_CHECK_EQUAL(task.irows(), irows);
NANO_CHECK_EQUAL(task.icols(), icols);
NANO_CHECK_EQUAL(task.osize(), osize);
NANO_CHECK_EQUAL(task.n_samples(), count);
}
NANO_CASE(training)
{
affine_task_t task(to_params(
"idims", idims, "irows", irows, "icols", icols, "osize", osize, "count", count, "noise", noise));
task.load();
// create model
const auto model_config = make_output_layer(task.osize());
const auto model = get_models().get("forward-network", model_config);
NANO_CHECK_EQUAL(model->resize(task, true), true);
NANO_REQUIRE(*model == task);
// create loss
const std::vector<std::pair<string_t, string_t>> lconfigs =
{
{"square", ""},
{"cauchy", ""}
};
// create criteria
const auto criterion = get_criteria().get("avg");
// create trainers
const auto batch = 32;
const auto epochs = 1000;
const auto policy = trainer_policy::stop_early;
const std::vector<std::pair<string_t, string_t>> tconfigs =
{
{"batch", to_params("opt", "gd", "epochs", epochs, "policy", policy)},
{"batch", to_params("opt", "cgd", "epochs", epochs, "policy", policy)},
{"batch", to_params("opt", "lbfgs", "epochs", epochs, "policy", policy)},
{"stoch", to_params("opt", "sg", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
{"stoch", to_params("opt", "sgm", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
//{"stoch", to_params("opt", "ngd", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
//{"stoch", to_params("opt", "adam", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
//{"stoch", to_params("opt", "adagrad", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
//{"stoch", to_params("opt", "adadelta", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
{"stoch", to_params("opt", "ag", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
//{"stoch", to_params("opt", "agfr", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
{"stoch", to_params("opt", "aggr", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
};
// check training
for (const auto& lconfig : lconfigs)
{
const auto loss = get_losses().get(lconfig.first, lconfig.second);
for (const auto& tconfig : tconfigs)
{
const auto trainer = get_trainers().get(tconfig.first, tconfig.second);
model->random_params();
const auto fold = size_t(0);
const auto threads = size_t(1);
const auto result = trainer->train(task, fold, threads, *loss, *criterion, *model);
// the average training loss value & error should be "small"
const auto opt_state = result.optimum_state();
NANO_CHECK_LESS(opt_state.m_train.m_value_avg, epsilon3<scalar_t>());
NANO_CHECK_LESS(opt_state.m_train.m_error_avg, epsilon3<scalar_t>());
}
}
}
NANO_END_MODULE()
|
#include "loss.h"
#include "utest.h"
#include "trainer.h"
#include "criterion.h"
#include "math/epsilon.h"
#include "tasks/task_affine.h"
#include "layers/make_layers.h"
using namespace nano;
const auto idims = tensor_size_t(3);
const auto irows = tensor_size_t(5);
const auto icols = tensor_size_t(7);
const auto osize = tensor_size_t(4);
const auto count = tensor_size_t(1000);
const auto noise = epsilon2<scalar_t>();
NANO_BEGIN_MODULE(test_affine)
NANO_CASE(construction)
{
affine_task_t task(to_params(
"idims", idims, "irows", irows, "icols", icols, "osize", osize, "count", count, "noise", noise));
task.load();
NANO_CHECK_EQUAL(task.idims(), idims);
NANO_CHECK_EQUAL(task.irows(), irows);
NANO_CHECK_EQUAL(task.icols(), icols);
NANO_CHECK_EQUAL(task.osize(), osize);
NANO_CHECK_EQUAL(task.n_samples(), count);
NANO_REQUIRE_EQUAL(task.n_folds(), size_t(1));
const auto& weights = task.weights();
const auto& bias = task.bias();
for (const auto proto : {protocol::train, protocol::valid, protocol::test})
{
const auto fold = fold_t{0, proto};
const auto size = task.n_samples(fold);
for (size_t i = 0; i < size; ++ i)
{
const auto input = task.input(fold, i);
const auto target = task.target(fold, i);
NANO_CHECK_EIGEN_CLOSE(weights * input.vector() + bias, target, noise);
}
}
}
NANO_CASE(training)
{
affine_task_t task(to_params(
"idims", idims, "irows", irows, "icols", icols, "osize", osize, "count", count, "noise", noise));
task.load();
// create model
const auto model_config = make_output_layer(task.osize());
const auto model = get_models().get("forward-network", model_config);
NANO_CHECK_EQUAL(model->resize(task, true), true);
NANO_REQUIRE(*model == task);
// create loss
const std::vector<std::pair<string_t, string_t>> lconfigs =
{
{"square", ""},
{"cauchy", ""}
};
// create criteria
const auto criterion = get_criteria().get("avg");
// create trainers
const auto batch = 32;
const auto epochs = 1000;
const auto policy = trainer_policy::stop_early;
const std::vector<std::pair<string_t, string_t>> tconfigs =
{
{"batch", to_params("opt", "gd", "epochs", epochs, "policy", policy)},
{"batch", to_params("opt", "cgd", "epochs", epochs, "policy", policy)},
{"batch", to_params("opt", "lbfgs", "epochs", epochs, "policy", policy)},
{"stoch", to_params("opt", "sg", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
{"stoch", to_params("opt", "sgm", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
//{"stoch", to_params("opt", "ngd", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
//{"stoch", to_params("opt", "adam", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
//{"stoch", to_params("opt", "adagrad", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
//{"stoch", to_params("opt", "adadelta", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
{"stoch", to_params("opt", "ag", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
//{"stoch", to_params("opt", "agfr", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
{"stoch", to_params("opt", "aggr", "epochs", epochs, "min_batch", batch, "max_batch", batch, "policy", policy)},
};
// check training
for (const auto& lconfig : lconfigs)
{
const auto loss = get_losses().get(lconfig.first, lconfig.second);
for (const auto& tconfig : tconfigs)
{
const auto trainer = get_trainers().get(tconfig.first, tconfig.second);
model->random_params();
const auto fold = size_t(0);
const auto threads = size_t(1);
const auto result = trainer->train(task, fold, threads, *loss, *criterion, *model);
// the average training loss value & error should be "small"
const auto opt_state = result.optimum_state();
NANO_CHECK_LESS(opt_state.m_train.m_value_avg, epsilon3<scalar_t>());
NANO_CHECK_LESS(opt_state.m_train.m_error_avg, epsilon3<scalar_t>());
}
}
}
NANO_END_MODULE()
|
extend unit test
|
extend unit test
|
C++
|
mit
|
accosmin/nano,accosmin/nano,accosmin/nanocv,accosmin/nanocv,accosmin/nanocv,accosmin/nano
|
ad37a36ebdba71215b422a6ebbf3038c5ae9add6
|
test/test_buffer.cpp
|
test/test_buffer.cpp
|
/*
Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin
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 Rasterbar Software nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <cassert>
#include <iostream>
#include <vector>
#include <utility>
#include <set>
#include "libtorrent/buffer.hpp"
#include "libtorrent/chained_buffer.hpp"
#include "libtorrent/socket.hpp"
#include "test.hpp"
using namespace libtorrent;
/*
template<class T>
T const& min_(T const& x, T const& y)
{
return x < y ? x : y;
}
void test_speed()
{
buffer b;
char data[32];
srand(0);
boost::timer t;
int const iterations = 5000000;
int const step = iterations / 20;
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
b.insert(data, data + n);
}
else
{
b.erase(min_(b.size(), n));
}
}
float t1 = t.elapsed();
std::cerr << "buffer elapsed: " << t.elapsed() << "\n";
std::vector<char> v;
srand(0);
t.restart();
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
v.insert(v.end(), data, data + n);
}
else
{
v.erase(v.begin(), v.begin() + min_(v.size(), n));
}
}
float t2 = t.elapsed();
std::cerr << "std::vector elapsed: " << t.elapsed() << "\n";
assert(t1 < t2);
}
*/
// -- test buffer --
void test_buffer()
{
char data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
buffer b;
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 0);
TEST_CHECK(b.empty());
b.resize(10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(b.capacity() == 10);
std::memcpy(b.begin(), data, 10);
b.reserve(50);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
TEST_CHECK(b.capacity() == 50);
b.erase(b.begin() + 6, b.end());
TEST_CHECK(std::memcmp(b.begin(), data, 6) == 0);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 6);
b.insert(b.begin(), data + 5, data + 10);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 11);
TEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0);
b.clear();
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 50);
b.insert(b.end(), data, data + 10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
b.erase(b.begin(), b.end());
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 0);
buffer().swap(b);
TEST_CHECK(b.capacity() == 0);
}
// -- test chained buffer --
std::set<char*> buffer_list;
void free_buffer(char* m)
{
std::set<char*>::iterator i = buffer_list.find(m);
TEST_CHECK(i != buffer_list.end());
buffer_list.erase(i);
std::free(m);
}
char* allocate_buffer(int size)
{
char* mem = (char*)std::malloc(size);
buffer_list.insert(mem);
return mem;
}
template <class T>
int copy_buffers(T const& b, char* target)
{
int copied = 0;
for (typename T::const_iterator i = b.begin()
, end(b.end()); i != end; ++i)
{
memcpy(target, libtorrent::asio::buffer_cast<char const*>(*i), libtorrent::asio::buffer_size(*i));
target += libtorrent::asio::buffer_size(*i);
copied += libtorrent::asio::buffer_size(*i);
}
return copied;
}
bool compare_chained_buffer(chained_buffer& b, char const* mem, int size)
{
if (size == 0) return true;
std::vector<char> flat(size);
std::list<libtorrent::asio::const_buffer> const& iovec2 = b.build_iovec(size);
int copied = copy_buffers(iovec2, &flat[0]);
TEST_CHECK(copied == size);
return std::memcmp(&flat[0], mem, size) == 0;
}
void test_chained_buffer()
{
char data[] = "foobar";
{
chained_buffer b;
TEST_CHECK(b.empty());
TEST_CHECK(b.capacity() == 0);
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.space_in_last_buffer() == 0);
TEST_CHECK(buffer_list.empty());
char* b1 = allocate_buffer(512);
std::memcpy(b1, data, 6);
b.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 1);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 6);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
b.pop_front(3);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 3);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
bool ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 9);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 12);
char data2[1024];
ret = b.append(data2, 1024);
TEST_CHECK(ret == false);
char* b2 = allocate_buffer(512);
std::memcpy(b2, data, 6);
b.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 2);
char* b3 = allocate_buffer(512);
std::memcpy(b3, data, 6);
b.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 3);
TEST_CHECK(b.capacity() == 512 * 3);
TEST_CHECK(b.size() == 21);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
TEST_CHECK(compare_chained_buffer(b, "barfoobar", 9));
for (int i = 1; i < 21; ++i)
TEST_CHECK(compare_chained_buffer(b, "barfoobarfoobarfoobar", i));
b.pop_front(5 + 6);
TEST_CHECK(buffer_list.size() == 2);
TEST_CHECK(b.capacity() == 512 * 2);
TEST_CHECK(b.size() == 10);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
char const* str = "obarfooba";
TEST_CHECK(compare_chained_buffer(b, str, 9));
for (int i = 0; i < 9; ++i)
{
b.pop_front(1);
++str;
TEST_CHECK(compare_chained_buffer(b, str, 8 - i));
TEST_CHECK(b.size() == 9 - i);
}
char* b4 = allocate_buffer(20);
std::memcpy(b4, data, 6);
std::memcpy(b4 + 6, data, 6);
b.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer);
TEST_CHECK(b.space_in_last_buffer() == 8);
ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 2);
std::cout << b.space_in_last_buffer() << std::endl;
ret = b.append(data, 2);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 0);
std::cout << b.space_in_last_buffer() << std::endl;
char* b5 = allocate_buffer(20);
std::memcpy(b4, data, 6);
b.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer);
b.pop_front(22);
TEST_CHECK(b.size() == 5);
}
TEST_CHECK(buffer_list.empty());
}
int test_main()
{
test_buffer();
test_chained_buffer();
return 0;
}
|
/*
Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin
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 Rasterbar Software nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <cassert>
#include <iostream>
#include <vector>
#include <utility>
#include <set>
#include "libtorrent/buffer.hpp"
#include "libtorrent/chained_buffer.hpp"
#include "libtorrent/socket.hpp"
#include "test.hpp"
using namespace libtorrent;
/*
template<class T>
T const& min_(T const& x, T const& y)
{
return x < y ? x : y;
}
void test_speed()
{
buffer b;
char data[32];
srand(0);
boost::timer t;
int const iterations = 5000000;
int const step = iterations / 20;
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
b.insert(data, data + n);
}
else
{
b.erase(min_(b.size(), n));
}
}
float t1 = t.elapsed();
std::cerr << "buffer elapsed: " << t.elapsed() << "\n";
std::vector<char> v;
srand(0);
t.restart();
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
v.insert(v.end(), data, data + n);
}
else
{
v.erase(v.begin(), v.begin() + min_(v.size(), n));
}
}
float t2 = t.elapsed();
std::cerr << "std::vector elapsed: " << t.elapsed() << "\n";
assert(t1 < t2);
}
*/
// -- test buffer --
void test_buffer()
{
char data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
buffer b;
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 0);
TEST_CHECK(b.empty());
b.resize(10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(b.capacity() == 10);
std::memcpy(b.begin(), data, 10);
b.reserve(50);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
TEST_CHECK(b.capacity() == 50);
b.erase(b.begin() + 6, b.end());
TEST_CHECK(std::memcmp(b.begin(), data, 6) == 0);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 6);
b.insert(b.begin(), data + 5, data + 10);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 11);
TEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0);
b.clear();
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 50);
b.insert(b.end(), data, data + 10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
b.erase(b.begin(), b.end());
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 0);
buffer().swap(b);
TEST_CHECK(b.capacity() == 0);
}
// -- test chained buffer --
std::set<char*> buffer_list;
void free_buffer(char* m)
{
std::set<char*>::iterator i = buffer_list.find(m);
TEST_CHECK(i != buffer_list.end());
buffer_list.erase(i);
std::free(m);
}
char* allocate_buffer(int size)
{
char* mem = (char*)std::malloc(size);
buffer_list.insert(mem);
return mem;
}
template <class T>
int copy_buffers(T const& b, char* target)
{
int copied = 0;
for (typename T::const_iterator i = b.begin()
, end(b.end()); i != end; ++i)
{
memcpy(target, libtorrent::asio::buffer_cast<char const*>(*i), libtorrent::asio::buffer_size(*i));
target += libtorrent::asio::buffer_size(*i);
copied += libtorrent::asio::buffer_size(*i);
}
return copied;
}
bool compare_chained_buffer(chained_buffer& b, char const* mem, int size)
{
if (size == 0) return true;
std::vector<char> flat(size);
std::list<libtorrent::asio::const_buffer> const& iovec2 = b.build_iovec(size);
int copied = copy_buffers(iovec2, &flat[0]);
TEST_CHECK(copied == size);
return std::memcmp(&flat[0], mem, size) == 0;
}
void test_chained_buffer()
{
char data[] = "foobar";
{
chained_buffer b;
TEST_CHECK(b.empty());
TEST_EQUAL(b.capacity(), 0);
TEST_EQUAL(b.size(), 0);
TEST_EQUAL(b.space_in_last_buffer(), 0);
TEST_CHECK(buffer_list.empty());
// there are no buffers, we should not be able to allocate
// an appendix in an existing buffer
TEST_EQUAL(b.allocate_appendix(1), 0);
char* b1 = allocate_buffer(512);
std::memcpy(b1, data, 6);
b.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer);
TEST_EQUAL(buffer_list.size(), 1);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 6);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
b.pop_front(3);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 3);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
bool ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 9);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 12);
char data2[1024];
ret = b.append(data2, 1024);
TEST_CHECK(ret == false);
char* b2 = allocate_buffer(512);
std::memcpy(b2, data, 6);
b.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 2);
char* b3 = allocate_buffer(512);
std::memcpy(b3, data, 6);
b.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 3);
TEST_CHECK(b.capacity() == 512 * 3);
TEST_CHECK(b.size() == 21);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
TEST_CHECK(compare_chained_buffer(b, "barfoobar", 9));
for (int i = 1; i < 21; ++i)
TEST_CHECK(compare_chained_buffer(b, "barfoobarfoobarfoobar", i));
b.pop_front(5 + 6);
TEST_CHECK(buffer_list.size() == 2);
TEST_CHECK(b.capacity() == 512 * 2);
TEST_CHECK(b.size() == 10);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
char const* str = "obarfooba";
TEST_CHECK(compare_chained_buffer(b, str, 9));
for (int i = 0; i < 9; ++i)
{
b.pop_front(1);
++str;
TEST_CHECK(compare_chained_buffer(b, str, 8 - i));
TEST_CHECK(b.size() == 9 - i);
}
char* b4 = allocate_buffer(20);
std::memcpy(b4, data, 6);
std::memcpy(b4 + 6, data, 6);
b.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer);
TEST_CHECK(b.space_in_last_buffer() == 8);
ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 2);
std::cout << b.space_in_last_buffer() << std::endl;
ret = b.append(data, 2);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 0);
std::cout << b.space_in_last_buffer() << std::endl;
char* b5 = allocate_buffer(20);
std::memcpy(b4, data, 6);
b.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer);
b.pop_front(22);
TEST_CHECK(b.size() == 5);
}
TEST_CHECK(buffer_list.empty());
}
int test_main()
{
test_buffer();
test_chained_buffer();
return 0;
}
|
tweak chained buffer test
|
tweak chained buffer test
|
C++
|
bsd-3-clause
|
mrmichalis/libtorrent-code,mrmichalis/libtorrent-code,mrmichalis/libtorrent-code,mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mildred/rasterbar-libtorrent,mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mildred/rasterbar-libtorrent
|
92c22475ae7fbab55385a81a5e00e1811d4fb228
|
ArcGISRuntimeSDKQt_CppSamples/Scenes/Animate3DSymbols/Animate3DSymbols.cpp
|
ArcGISRuntimeSDKQt_CppSamples/Scenes/Animate3DSymbols/Animate3DSymbols.cpp
|
// [WriteFile Name=Animate3DSymbols, Category=Scenes]
// [Legal]
// Copyright 2016 Esri.
// 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.
// [Legal]
#include "Animate3DSymbols.h"
#include "MissionData.h"
#include "ArcGISTiledElevationSource.h"
#include "Camera.h"
#include "DistanceCompositeSceneSymbol.h"
#include "GraphicsOverlay.h"
#include "Map.h"
#include "MapQuickView.h"
#include "ModelSceneSymbol.h"
#include "PointCollection.h"
#include "Polyline.h"
#include "PolylineBuilder.h"
#include "Scene.h"
#include "SceneQuickView.h"
#include "SceneViewTypes.h"
#include "SimpleMarkerSymbol.h"
#include "SimpleMarkerSceneSymbol.h"
#include "SimpleRenderer.h"
#include "SpatialReference.h"
#include <QDir>
#include <QFileInfo>
#include <QStringListModel>
#include <QQmlProperty>
using namespace Esri::ArcGISRuntime;
const QString Animate3DSymbols::HEADING = "HEADING";
const QString Animate3DSymbols::ROLL = "ROLL";
const QString Animate3DSymbols::PITCH = "PITCH";
const QString Animate3DSymbols::ANGLE = "ANGLE";
Animate3DSymbols::Animate3DSymbols(QQuickItem* parent /* = nullptr */):
QQuickItem(parent),
m_sceneView(nullptr),
m_mapView(nullptr),
m_model3d(nullptr),
m_graphic3d(nullptr),
m_graphic2d(nullptr),
m_routeGraphic(nullptr),
m_missionsModel( new QStringListModel({"Grand Canyon", "Hawaii", "Pyrenees", "Snowdon"}, this)),
m_missionData( new MissionData()),
m_frame(0),
m_zoomDist(0.),
m_following(true),
m_mapZoomFactor(5.)
{
Q_INIT_RESOURCE(Animate3DSymbols);
}
Animate3DSymbols::~Animate3DSymbols()
{
}
void Animate3DSymbols::componentComplete()
{
QQuickItem::componentComplete();
// get the data path
m_dataPath = QQmlProperty::read(this, "dataPath").toString();
// find QML SceneView component
m_sceneView = findChild<SceneQuickView*>("sceneView");
// create a new scene instance
Scene* scene = new Scene(Basemap::imagery(this), this);
// set scene on the scene view
m_sceneView->setScene(scene);
// create a new elevation source
ArcGISTiledElevationSource* elevationSource = new ArcGISTiledElevationSource(
QUrl("http://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"), this);
// add the elevation source to the scene to display elevation
scene->baseSurface()->elevationSources()->append(elevationSource);
// create a new graphics overlay and add it to the sceneview
GraphicsOverlay* sceneOverlay = new GraphicsOverlay(this);
sceneOverlay->sceneProperties().setSurfacePlacement(SurfacePlacement::Absolute);
m_sceneView->graphicsOverlays()->append(sceneOverlay);
SimpleRenderer* renderer3D = new SimpleRenderer(this);
RendererSceneProperties renderProperties = renderer3D->sceneProperties();
renderProperties.setHeadingExpression(HEADING);
renderProperties.setPitchExpression(PITCH);
renderProperties.setRollExpression(ROLL);
sceneOverlay->setRenderer(renderer3D);
// find QML MapView component
m_mapView = findChild<MapQuickView*>("mapView");
// set up mini map
Map* map = new Map(Basemap::imagery(this), this);
m_mapView->setMap(map);
// create a graphics overlay for the mini map
GraphicsOverlay* mapOverlay = new GraphicsOverlay(this);
m_mapView->graphicsOverlays()->append(mapOverlay);
// create renderer to handle updating plane heading using the graphics card
SimpleRenderer* renderer2D = new SimpleRenderer(this);
renderer2D->setRotationExpression(QString("[%1]").arg(ANGLE));
mapOverlay->setRenderer(renderer2D);
// set up route graphic
createRoute2d(mapOverlay);
// set up 3d graphic for model position in map view
createModel2d(mapOverlay);
}
void Animate3DSymbols::setFrame(int newFrame)
{
if(m_missionData == nullptr ||
newFrame > m_missionData->size() ||
newFrame < 0 ||
m_frame == newFrame)
return;
m_frame = newFrame;
}
void Animate3DSymbols::nextFrame()
{
if(m_missionData == nullptr)
return;
if(m_frame < m_missionData->size())
{
// get the data for this stage in the mission
const MissionData::DataPoint& dp = m_missionData->dataAt(m_frame);
#ifdef ANIMATE_MAP // TODO: Currently, if we do any sort of graphics update for the map view at the same time the scene view flickers
// move 2d graphic to the new position
m_graphic2d->setGeometry(dp.m_pos);
#endif
// move 3D graphic to the new position
m_graphic3d->setGeometry(dp.m_pos);
// update attribute expressions to immediately update rotation
m_graphic3d->attributes()->replaceAttribute(HEADING, dp.m_heading);
m_graphic3d->attributes()->replaceAttribute(PITCH, dp.m_pitch);
m_graphic3d->attributes()->replaceAttribute(ROLL, dp.m_roll);
if(m_following)
{
// move the camera to follow the 3d model
Camera camera(dp.m_pos, m_zoomDist, dp.m_heading, m_angle, dp.m_roll );
m_sceneView->setViewpointCamera(camera);
#ifdef ANIMATE_MAP
// rotate the map view about the direction of motion
m_mapView->setViewpoint(Viewpoint(dp.m_pos, m_mapView->mapScale(), 360. + dp.m_heading));
#endif
}
else
{
#ifdef ANIMATE_MAP
m_graphic2d->attributes()->replaceAttribute(ANGLE, 360 + dp.m_heading - m_mapView->mapRotation());
#endif
m_sceneView->update();
}
}
// increment the frame count
m_frame++;
if(m_frame >= m_missionData->size())
m_frame = 0;
}
void Animate3DSymbols::changeMission(const QString &missionNameStr)
{
m_frame = 0;
// read the mission data from .csv files stored in qrc
QString formattedname = missionNameStr;
m_missionData->parse(":/" + formattedname.remove(" ") + ".csv");
// if the mission was loaded successfully, move to the start position
if(missionReady())
{
// create a polyline representing the route for the mission
PolylineBuilder* routeBldr = new PolylineBuilder(SpatialReference::wgs84(), this);
for(size_t i = 0; i < m_missionData->size(); ++i )
{
const MissionData::DataPoint& dp = m_missionData->dataAt(i);
routeBldr->addPoint(dp.m_pos);
}
// set the polyline as a graphic on the mapView
m_routeGraphic->setGeometry(routeBldr->toGeometry());
const MissionData::DataPoint& dp = m_missionData->dataAt(m_frame);
Camera camera(dp.m_pos, m_zoomDist, dp.m_heading, m_angle, dp.m_roll);
m_sceneView->setViewpointCameraAndWait(camera);
m_mapView->setViewpointAndWait(Viewpoint(m_routeGraphic->geometry()));
createModel3d();
}
emit missionReadyChanged();
emit missionSizeChanged();
}
void Animate3DSymbols::clearGraphic3D()
{
if(m_graphic3d == nullptr)
return;
if(m_sceneView->graphicsOverlays()->size() > 0 && m_sceneView->graphicsOverlays()->at(0))
m_sceneView->graphicsOverlays()->at(0)->graphics()->clear();
delete m_graphic3d;
m_graphic3d = nullptr;
}
void Animate3DSymbols::createModel3d()
{
// load the ModelSceneSymbol to be animated in the 3d view
if( m_model3d == nullptr)
{
m_model3d = new ModelSceneSymbol(QUrl(m_dataPath + "/SkyCrane/SkyCrane.lwo"), 0.01f, this);
// correct the symbol's orientation to match the graphic's orientation
m_model3d->setHeading(180.);
}
// when the model is successfully loaded, setup the 3g draphic to show it it the scene
connect(m_model3d, &ModelSceneSymbol::loadStatusChanged, [this]()
{
if (m_model3d->loadStatus() == LoadStatus::Loaded)
createGraphic3D();
}
);
if( m_model3d->loadStatus() == LoadStatus::Loaded)
createGraphic3D(); // if the model is already loaded just recreate the graphic
else
m_model3d->load(); // if the model has not been loaded before, call load
}
void Animate3DSymbols::createModel2d(GraphicsOverlay *mapOverlay)
{
// create a blue triangle symbol to represent the plane on the mini map
SimpleMarkerSymbol* plane2DSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Triangle, Qt::blue, 10, this);
// create a graphic with the symbol and attributes
QVariantMap attributes;
attributes.insert(ANGLE, 0.f);
m_graphic2d = new Graphic(Point(0, 0, SpatialReference::wgs84()), attributes, plane2DSymbol);
mapOverlay->graphics()->append(m_graphic2d);
}
void Animate3DSymbols::createRoute2d(GraphicsOverlay* mapOverlay)
{
// Create a 2d graphic of a solid red line to represen the route of the mission
SimpleLineSymbol* routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, Qt::red, 2);
m_routeGraphic = new Graphic(this);
m_routeGraphic->setSymbol(routeSymbol);
mapOverlay->graphics()->append(m_routeGraphic);
}
void Animate3DSymbols::createGraphic3D()
{
if(m_model3d == nullptr || !missionReady())
return;
clearGraphic3D();
// get the mission data for the frame
const MissionData::DataPoint& dp = m_missionData->dataAt(m_frame);
// create a graphic using the model symbol
m_graphic3d = new Graphic(dp.m_pos, m_model3d, this);
m_graphic3d->attributes()->insertAttribute(HEADING, dp.m_heading);
m_graphic3d->attributes()->insertAttribute(PITCH, dp.m_pitch);
m_graphic3d->attributes()->insertAttribute(ROLL, dp.m_roll);
// add the graphic to the graphics overlay
m_sceneView->graphicsOverlays()->at(0)->graphics()->append(m_graphic3d);
}
void Animate3DSymbols::setFollowing(bool following)
{
m_following = following;
}
void Animate3DSymbols::zoomMapIn()
{
if (m_mapView == nullptr ||
m_graphic2d == nullptr)
return;
// zoom the map view in, focusing on the position of the 2d graphic for the helicopter
m_mapView->setViewpoint(Viewpoint((Point)m_graphic2d->geometry(), m_mapView->mapScale() / m_mapZoomFactor));
}
void Animate3DSymbols::zoomMapOut()
{
if (m_mapView == nullptr ||
m_graphic2d == nullptr)
return;
// zoom the map view out, focusing on the position of the 2d graphic for the helicopter
m_mapView->setViewpoint(Viewpoint((Point)m_graphic2d->geometry(), m_mapView->mapScale() * m_mapZoomFactor));
}
bool Animate3DSymbols::missionReady() const
{
if( m_missionData == nullptr)
return false;
return m_missionData->ready();
}
int Animate3DSymbols::missionSize() const
{
if( m_missionData == nullptr)
return 0;
return (int)m_missionData->size();
}
|
// [WriteFile Name=Animate3DSymbols, Category=Scenes]
// [Legal]
// Copyright 2016 Esri.
// 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.
// [Legal]
#include "Animate3DSymbols.h"
#include "MissionData.h"
#include "ArcGISTiledElevationSource.h"
#include "Camera.h"
#include "DistanceCompositeSceneSymbol.h"
#include "GraphicsOverlay.h"
#include "Map.h"
#include "MapQuickView.h"
#include "ModelSceneSymbol.h"
#include "PointCollection.h"
#include "Polyline.h"
#include "PolylineBuilder.h"
#include "Scene.h"
#include "SceneQuickView.h"
#include "SceneViewTypes.h"
#include "SimpleMarkerSymbol.h"
#include "SimpleMarkerSceneSymbol.h"
#include "SimpleRenderer.h"
#include "SpatialReference.h"
#include <QDir>
#include <QFileInfo>
#include <QStringListModel>
#include <QQmlProperty>
using namespace Esri::ArcGISRuntime;
const QString Animate3DSymbols::HEADING = "HEADING";
const QString Animate3DSymbols::ROLL = "ROLL";
const QString Animate3DSymbols::PITCH = "PITCH";
const QString Animate3DSymbols::ANGLE = "ANGLE";
Animate3DSymbols::Animate3DSymbols(QQuickItem* parent /* = nullptr */):
QQuickItem(parent),
m_sceneView(nullptr),
m_mapView(nullptr),
m_model3d(nullptr),
m_graphic3d(nullptr),
m_graphic2d(nullptr),
m_routeGraphic(nullptr),
m_missionsModel( new QStringListModel({"Grand Canyon", "Hawaii", "Pyrenees", "Snowdon"}, this)),
m_missionData( new MissionData()),
m_frame(0),
m_zoomDist(0.),
m_following(true),
m_mapZoomFactor(5.)
{
Q_INIT_RESOURCE(Animate3DSymbols);
}
Animate3DSymbols::~Animate3DSymbols()
{
}
void Animate3DSymbols::componentComplete()
{
QQuickItem::componentComplete();
// get the data path
m_dataPath = QQmlProperty::read(this, "dataPath").toString();
// find QML SceneView component
m_sceneView = findChild<SceneQuickView*>("sceneView");
// create a new scene instance
Scene* scene = new Scene(Basemap::imagery(this), this);
// set scene on the scene view
m_sceneView->setScene(scene);
// create a new elevation source
ArcGISTiledElevationSource* elevationSource = new ArcGISTiledElevationSource(
QUrl("http://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"), this);
// add the elevation source to the scene to display elevation
scene->baseSurface()->elevationSources()->append(elevationSource);
// create a new graphics overlay and add it to the sceneview
GraphicsOverlay* sceneOverlay = new GraphicsOverlay(this);
sceneOverlay->sceneProperties().setSurfacePlacement(SurfacePlacement::Absolute);
m_sceneView->graphicsOverlays()->append(sceneOverlay);
SimpleRenderer* renderer3D = new SimpleRenderer(this);
RendererSceneProperties renderProperties = renderer3D->sceneProperties();
renderProperties.setHeadingExpression(HEADING);
renderProperties.setPitchExpression(PITCH);
renderProperties.setRollExpression(ROLL);
sceneOverlay->setRenderer(renderer3D);
// find QML MapView component
m_mapView = findChild<MapQuickView*>("mapView");
// set up mini map
Map* map = new Map(Basemap::imagery(this), this);
m_mapView->setMap(map);
// create a graphics overlay for the mini map
GraphicsOverlay* mapOverlay = new GraphicsOverlay(this);
m_mapView->graphicsOverlays()->append(mapOverlay);
// create renderer to handle updating plane heading using the graphics card
SimpleRenderer* renderer2D = new SimpleRenderer(this);
renderer2D->setRotationExpression(QString("[%1]").arg(ANGLE));
mapOverlay->setRenderer(renderer2D);
// set up route graphic
createRoute2d(mapOverlay);
// set up 3d graphic for model position in map view
createModel2d(mapOverlay);
}
void Animate3DSymbols::setFrame(int newFrame)
{
if(m_missionData == nullptr ||
newFrame > (int)m_missionData->size() ||
newFrame < 0 ||
m_frame == newFrame)
return;
m_frame = newFrame;
}
void Animate3DSymbols::nextFrame()
{
if(m_missionData == nullptr)
return;
if(m_frame < (int)m_missionData->size())
{
// get the data for this stage in the mission
const MissionData::DataPoint& dp = m_missionData->dataAt(m_frame);
#ifdef ANIMATE_MAP // TODO: Currently, if we do any sort of graphics update for the map view at the same time the scene view flickers
// move 2d graphic to the new position
m_graphic2d->setGeometry(dp.m_pos);
#endif
// move 3D graphic to the new position
m_graphic3d->setGeometry(dp.m_pos);
// update attribute expressions to immediately update rotation
m_graphic3d->attributes()->replaceAttribute(HEADING, dp.m_heading);
m_graphic3d->attributes()->replaceAttribute(PITCH, dp.m_pitch);
m_graphic3d->attributes()->replaceAttribute(ROLL, dp.m_roll);
if(m_following)
{
// move the camera to follow the 3d model
Camera camera(dp.m_pos, m_zoomDist, dp.m_heading, m_angle, dp.m_roll );
m_sceneView->setViewpointCamera(camera);
#ifdef ANIMATE_MAP
// rotate the map view about the direction of motion
m_mapView->setViewpoint(Viewpoint(dp.m_pos, m_mapView->mapScale(), 360. + dp.m_heading));
#endif
}
else
{
#ifdef ANIMATE_MAP
m_graphic2d->attributes()->replaceAttribute(ANGLE, 360 + dp.m_heading - m_mapView->mapRotation());
#endif
m_sceneView->update();
}
}
// increment the frame count
m_frame++;
if(m_frame >= (int)m_missionData->size())
m_frame = 0;
}
void Animate3DSymbols::changeMission(const QString &missionNameStr)
{
m_frame = 0;
// read the mission data from .csv files stored in qrc
QString formattedname = missionNameStr;
m_missionData->parse(":/" + formattedname.remove(" ") + ".csv");
// if the mission was loaded successfully, move to the start position
if(missionReady())
{
// create a polyline representing the route for the mission
PolylineBuilder* routeBldr = new PolylineBuilder(SpatialReference::wgs84(), this);
for(size_t i = 0; i < m_missionData->size(); ++i )
{
const MissionData::DataPoint& dp = m_missionData->dataAt(i);
routeBldr->addPoint(dp.m_pos);
}
// set the polyline as a graphic on the mapView
m_routeGraphic->setGeometry(routeBldr->toGeometry());
const MissionData::DataPoint& dp = m_missionData->dataAt(m_frame);
Camera camera(dp.m_pos, m_zoomDist, dp.m_heading, m_angle, dp.m_roll);
m_sceneView->setViewpointCameraAndWait(camera);
m_mapView->setViewpointAndWait(Viewpoint(m_routeGraphic->geometry()));
createModel3d();
}
emit missionReadyChanged();
emit missionSizeChanged();
}
void Animate3DSymbols::clearGraphic3D()
{
if(m_graphic3d == nullptr)
return;
if(m_sceneView->graphicsOverlays()->size() > 0 && m_sceneView->graphicsOverlays()->at(0))
m_sceneView->graphicsOverlays()->at(0)->graphics()->clear();
delete m_graphic3d;
m_graphic3d = nullptr;
}
void Animate3DSymbols::createModel3d()
{
// load the ModelSceneSymbol to be animated in the 3d view
if( m_model3d == nullptr)
{
m_model3d = new ModelSceneSymbol(QUrl(m_dataPath + "/SkyCrane/SkyCrane.lwo"), 0.01f, this);
// correct the symbol's orientation to match the graphic's orientation
m_model3d->setHeading(180.);
}
// when the model is successfully loaded, setup the 3g draphic to show it it the scene
connect(m_model3d, &ModelSceneSymbol::loadStatusChanged, [this]()
{
if (m_model3d->loadStatus() == LoadStatus::Loaded)
createGraphic3D();
}
);
if( m_model3d->loadStatus() == LoadStatus::Loaded)
createGraphic3D(); // if the model is already loaded just recreate the graphic
else
m_model3d->load(); // if the model has not been loaded before, call load
}
void Animate3DSymbols::createModel2d(GraphicsOverlay *mapOverlay)
{
// create a blue triangle symbol to represent the plane on the mini map
SimpleMarkerSymbol* plane2DSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Triangle, Qt::blue, 10, this);
// create a graphic with the symbol and attributes
QVariantMap attributes;
attributes.insert(ANGLE, 0.f);
m_graphic2d = new Graphic(Point(0, 0, SpatialReference::wgs84()), attributes, plane2DSymbol);
mapOverlay->graphics()->append(m_graphic2d);
}
void Animate3DSymbols::createRoute2d(GraphicsOverlay* mapOverlay)
{
// Create a 2d graphic of a solid red line to represen the route of the mission
SimpleLineSymbol* routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, Qt::red, 2);
m_routeGraphic = new Graphic(this);
m_routeGraphic->setSymbol(routeSymbol);
mapOverlay->graphics()->append(m_routeGraphic);
}
void Animate3DSymbols::createGraphic3D()
{
if(m_model3d == nullptr || !missionReady())
return;
clearGraphic3D();
// get the mission data for the frame
const MissionData::DataPoint& dp = m_missionData->dataAt(m_frame);
// create a graphic using the model symbol
m_graphic3d = new Graphic(dp.m_pos, m_model3d, this);
m_graphic3d->attributes()->insertAttribute(HEADING, dp.m_heading);
m_graphic3d->attributes()->insertAttribute(PITCH, dp.m_pitch);
m_graphic3d->attributes()->insertAttribute(ROLL, dp.m_roll);
// add the graphic to the graphics overlay
m_sceneView->graphicsOverlays()->at(0)->graphics()->append(m_graphic3d);
}
void Animate3DSymbols::setFollowing(bool following)
{
m_following = following;
}
void Animate3DSymbols::zoomMapIn()
{
if (m_mapView == nullptr ||
m_graphic2d == nullptr)
return;
// zoom the map view in, focusing on the position of the 2d graphic for the helicopter
m_mapView->setViewpoint(Viewpoint((Point)m_graphic2d->geometry(), m_mapView->mapScale() / m_mapZoomFactor));
}
void Animate3DSymbols::zoomMapOut()
{
if (m_mapView == nullptr ||
m_graphic2d == nullptr)
return;
// zoom the map view out, focusing on the position of the 2d graphic for the helicopter
m_mapView->setViewpoint(Viewpoint((Point)m_graphic2d->geometry(), m_mapView->mapScale() * m_mapZoomFactor));
}
bool Animate3DSymbols::missionReady() const
{
if( m_missionData == nullptr)
return false;
return m_missionData->ready();
}
int Animate3DSymbols::missionSize() const
{
if( m_missionData == nullptr)
return 0;
return (int)m_missionData->size();
}
|
remove warnings int vs size_t
|
remove warnings int vs size_t
|
C++
|
apache-2.0
|
Esri/arcgis-runtime-samples-qt,Esri/arcgis-runtime-samples-qt,Esri/arcgis-runtime-samples-qt,Esri/arcgis-runtime-samples-qt
|
1ffa38a75c775a2b1d805032d6603ba2235c93b1
|
sources/stack.cpp
|
sources/stack.cpp
|
#include "stack.hpp"
#include <string>
#include <chrono>
#include <thread>
void producer(stack<int> &Stack)
{
for(;;)
{
Stack.push(std::rand() % 100);
std::this_thread::sleep_for(std::chrono::seconds(std::rand() % (3) + 1));
}
}
void consumer(stack<int> &Stack)
{
for(;;)
{
try
{
Stack.pop();
}
catch(std::logic_error)
{
std::this_thread::sleep_for(std::chrono::seconds(std::rand() % (3) + 2));
}
std::this_thread::sleep_for(std::chrono::seconds(std::rand() % (3) + 2));
}
}
int main()
{
stack<int> Stack;
std::thread prod(producer, std::ref(Stack));
std::thread cons(consumer, std::ref(Stack));
prod.join();
cons.join();
return 0;
}
|
#include "stack.hpp"
#include <string>
#include <chrono>
void producer(stack<int> &Stack)
{
for(;;)
{
Stack.push(std::rand() % 100);
std::this_thread::sleep_for(std::chrono::seconds(std::rand() % (3) + 1));
}
}
void consumer(stack<int> &Stack)
{
for(;;)
{
try
{
Stack.pop();
}
catch(std::logic_error)
{
std::this_thread::sleep_for(std::chrono::seconds(std::rand() % (3) + 2));
}
std::this_thread::sleep_for(std::chrono::seconds(std::rand() % (3) + 2));
}
}
int main()
{
stack<int> Stack;
std::thread prod(producer, std::ref(Stack));
std::thread cons(consumer, std::ref(Stack));
prod.join();
cons.join();
return 0;
}
|
Update stack.cpp
|
Update stack.cpp
|
C++
|
mit
|
kate-lozovaya/stack-0.0.3
|
e4b45c9ed2b1349009eedfdce91aa3af6e193232
|
src/utility.hpp
|
src/utility.hpp
|
/** \file
* Implements generally useful functions.
*/
#include <type_traits> /* std::underlying_type */
#include <string>
#include <cstdio> /* snprintf() */
#ifndef _POWERDXX_UTILITY_HPP_
#define _POWERDXX_UTILITY_HPP_
/**
* A collection of generally useful functions.
*/
namespace utility {
/**
* Like sizeof(), but it returns the number of elements an array consists
* of instead of the number of bytes.
*
* @tparam T,Count
* The type and number of array elements
* @return
* The number of array entries
*/
template <typename T, size_t Count>
constexpr size_t countof(T (&)[Count]) { return Count; }
/**
* Contains literals.
*/
namespace literals {
/**
* A string literal operator equivalent to the `operator "" s` literal
* provided by C++14 in \<string\>.
*
* @param op
* The raw string to turn into an std::string object
* @param size
* The size of the raw string
* @return
* An std::string instance
*/
inline std::string operator "" _s(char const * const op, size_t const size) {
return {op, size};
}
} /* namespace literals */
/**
* This is a safeguard against accidentally using sprintf().
*
* Using it triggers a static_assert(), preventing compilation.
*
* @tparam Args
* Catch all arguments
*/
template <typename... Args>
void sprintf(Args...) {
/* Assert depends on Args so it can only be determined if
* the function is actually instantiated. */
static_assert(sizeof...(Args) && false,
"Use of sprintf() is unsafe, use sprintf_safe() instead");
}
/**
* A wrapper around snprintf() that automatically pulls in the
* destination buffer size.
*
* @tparam Size
* The destination buffer size
* @tparam Args
* The types of the arguments
* @param dst
* A reference to the destination buffer
* @param format
* A printf style formatting string
* @param args
* The printf arguments
* @return
* The number of characters in the resulting string, regardless of the
* available space
*/
template <size_t Size, typename... Args>
inline int sprintf_safe(char (& dst)[Size], char const * const format,
Args const... args) {
return snprintf(dst, Size, format, args...);
}
/**
* Casts an enum to its underlying value.
*
* @tparam ET,VT
* The enum and value type
* @param op
* The operand to convert
* @return
* The integer representation of the operand
*/
template <class ET, typename VT = typename std::underlying_type<ET>::type>
constexpr VT to_value(ET const op) {
return static_cast<VT>(op);
}
/**
* A formatting wrapper around string literals.
*
* Overloads operator (), which treats the string as a printf formatting
* string, the arguments represent the data to format.
*
* In combination with the literal _fmt, it can be used like this:
*
* ~~~ c++
* std::cout << "%-15.15s %#018p\n"_fmt("Address:", this);
* ~~~
*
* @tparam BufSize
* The buffer size for formatting, resulting strings cannot
* grow beyond `BufSize - 1`
*/
template <size_t BufSize>
class Formatter {
private:
/**
* Pointer to the string literal.
*/
char const * const fmt;
public:
/**
* Construct from string literal.
*/
constexpr Formatter(char const * const fmt) : fmt{fmt} {}
/**
* Returns a formatted string.
*
* @tparam ArgTs
* Variadic argument types
* @param args
* Variadic arguments
* @return
* An std::string formatted according to fmt
*/
template <typename... ArgTs>
std::string operator ()(ArgTs const &... args) const {
char buf[BufSize];
auto count = sprintf_safe(buf, this->fmt, args...);
if (count < 0) {
/* encoding error */
return {};
} else if (static_cast<size_t>(count) >= BufSize) {
/* does not fit into buffer */
return {buf, BufSize - 1};
}
return {buf, static_cast<size_t>(count)};
}
};
namespace literals {
/**
* Literal to convert a string literal to a Formatter instance.
*
* @param fmt
* A printf style format string
* @param const
* Unused
* @return
* A Formatter instance
*/
constexpr Formatter<16384> operator "" _fmt(char const * const fmt, size_t const) {
return {fmt};
}
} /* namespace literals */
} /* namespace utility */
#endif /* _POWERDXX_UTILITY_HPP_ */
|
/** \file
* Implements generally useful functions.
*/
#include <type_traits> /* std::underlying_type */
#include <string>
#include <cstdio> /* snprintf() */
#ifndef _POWERDXX_UTILITY_HPP_
#define _POWERDXX_UTILITY_HPP_
/**
* A collection of generally useful functions.
*/
namespace utility {
/**
* Like sizeof(), but it returns the number of elements an array consists
* of instead of the number of bytes.
*
* @tparam T,Count
* The type and number of array elements
* @return
* The number of array entries
*/
template <typename T, size_t Count>
constexpr size_t countof(T (&)[Count]) { return Count; }
/**
* Contains literals.
*/
namespace literals {
/**
* A string literal operator equivalent to the `operator "" s` literal
* provided by C++14 in \<string\>.
*
* @param op
* The raw string to turn into an std::string object
* @param size
* The size of the raw string
* @return
* An std::string instance
*/
inline std::string operator "" _s(char const * const op, size_t const size) {
return {op, size};
}
} /* namespace literals */
/**
* This is a safeguard against accidentally using sprintf().
*
* Using it triggers a static_assert(), preventing compilation.
*
* @tparam Args
* Catch all arguments
*/
template <typename... Args>
inline void sprintf(Args...) {
/* Assert depends on Args so it can only be determined if
* the function is actually instantiated. */
static_assert(sizeof...(Args) && false,
"Use of sprintf() is unsafe, use sprintf_safe() instead");
}
/**
* A wrapper around snprintf() that automatically pulls in the
* destination buffer size.
*
* @tparam Size
* The destination buffer size
* @tparam Args
* The types of the arguments
* @param dst
* A reference to the destination buffer
* @param format
* A printf style formatting string
* @param args
* The printf arguments
* @return
* The number of characters in the resulting string, regardless of the
* available space
*/
template <size_t Size, typename... Args>
inline int sprintf_safe(char (& dst)[Size], char const * const format,
Args const... args) {
return snprintf(dst, Size, format, args...);
}
/**
* Casts an enum to its underlying value.
*
* @tparam ET,VT
* The enum and value type
* @param op
* The operand to convert
* @return
* The integer representation of the operand
*/
template <class ET, typename VT = typename std::underlying_type<ET>::type>
constexpr VT to_value(ET const op) {
return static_cast<VT>(op);
}
/**
* A formatting wrapper around string literals.
*
* Overloads operator (), which treats the string as a printf formatting
* string, the arguments represent the data to format.
*
* In combination with the literal _fmt, it can be used like this:
*
* ~~~ c++
* std::cout << "%-15.15s %#018p\n"_fmt("Address:", this);
* ~~~
*
* @tparam BufSize
* The buffer size for formatting, resulting strings cannot
* grow beyond `BufSize - 1`
*/
template <size_t BufSize>
class Formatter {
private:
/**
* Pointer to the string literal.
*/
char const * const fmt;
public:
/**
* Construct from string literal.
*/
constexpr Formatter(char const * const fmt) : fmt{fmt} {}
/**
* Returns a formatted string.
*
* @tparam ArgTs
* Variadic argument types
* @param args
* Variadic arguments
* @return
* An std::string formatted according to fmt
*/
template <typename... ArgTs>
std::string operator ()(ArgTs const &... args) const {
char buf[BufSize];
auto count = sprintf_safe(buf, this->fmt, args...);
if (count < 0) {
/* encoding error */
return {};
} else if (static_cast<size_t>(count) >= BufSize) {
/* does not fit into buffer */
return {buf, BufSize - 1};
}
return {buf, static_cast<size_t>(count)};
}
};
namespace literals {
/**
* Literal to convert a string literal to a Formatter instance.
*
* @param fmt
* A printf style format string
* @param const
* Unused
* @return
* A Formatter instance
*/
constexpr Formatter<16384> operator "" _fmt(char const * const fmt, size_t const) {
return {fmt};
}
} /* namespace literals */
} /* namespace utility */
#endif /* _POWERDXX_UTILITY_HPP_ */
|
Add missing inline
|
Add missing inline
|
C++
|
isc
|
lonkamikaze/powerdxx,lonkamikaze/powerdxx
|
fa0b0e40cc2ec7e40897c2c35a815bb922f39913
|
src/version.cpp
|
src/version.cpp
|
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "corgi/version.h"
namespace corgi {
#define CORGI_VERSION_MAJOR 1
#define CORGI_VERSION_MINOR 0
#define CORGI_VERSION_REVISION 0
// Turn X into a string literal.
#define CORGI_STRING_EXPAND(X) #X
#define CORGI_STRING(X) CORGI_STRING_EXPAND(X)
/// @var kVersion
/// @brief String which identifies the current version of MathFu.
///
/// @ref kVersion is used by Google developers to identify which applications
/// uploaded to Google Play are using this library. This allows the development
/// team at Google to determine the popularity of the library.
/// How it works: Applications that are uploaded to the Google Play Store are
/// scanned for this version string. We track which applications are using it
/// to measure popularity. You are free to remove it (of course) but we would
/// appreciate if you left it in.
///
static const CorgiVersion kVersion = {
CORGI_VERSION_MAJOR, CORGI_VERSION_MINOR, CORGI_VERSION_REVISION,
"Corgi Entity Library " CORGI_STRING(CORGI_VERSION_MAJOR) "." CORGI_STRING(
CORGI_VERSION_MINOR) "." CORGI_STRING(CORGI_VERSION_REVISION)};
const CorgiVersion& Version() { return kVersion; }
} // namespace corgi
|
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "corgi/version.h"
namespace corgi {
#define CORGI_VERSION_MAJOR 1
#define CORGI_VERSION_MINOR 0
#define CORGI_VERSION_REVISION 1
// Turn X into a string literal.
#define CORGI_STRING_EXPAND(X) #X
#define CORGI_STRING(X) CORGI_STRING_EXPAND(X)
/// @var kVersion
/// @brief String which identifies the current version of MathFu.
///
/// @ref kVersion is used by Google developers to identify which applications
/// uploaded to Google Play are using this library. This allows the development
/// team at Google to determine the popularity of the library.
/// How it works: Applications that are uploaded to the Google Play Store are
/// scanned for this version string. We track which applications are using it
/// to measure popularity. You are free to remove it (of course) but we would
/// appreciate if you left it in.
///
static const CorgiVersion kVersion = {
CORGI_VERSION_MAJOR, CORGI_VERSION_MINOR, CORGI_VERSION_REVISION,
"Corgi Entity Library " CORGI_STRING(CORGI_VERSION_MAJOR) "." CORGI_STRING(
CORGI_VERSION_MINOR) "." CORGI_STRING(CORGI_VERSION_REVISION)};
const CorgiVersion& Version() { return kVersion; }
} // namespace corgi
|
Update version number for GitHub push.
|
Update version number for GitHub push.
Change-Id: Ifb3ccf442144f15f0bc7abbcabd000d88e5c629c
Process: Issue 27791837
|
C++
|
apache-2.0
|
google/corgi,google/corgi
|
b911349b49c04d754e9b890a887debc4e16df097
|
software/perception/plane-seg/src/PlaneFitter.cpp
|
software/perception/plane-seg/src/PlaneFitter.cpp
|
#include "PlaneFitter.hpp"
#include <limits>
#include <drc_utils/RansacGeneric.hpp>
using namespace planeseg;
namespace {
struct SimpleProblemBase {
struct Solution {
Eigen::Vector4f mPlane;
float mCurvature;
Eigen::Vector3f mCenterPoint;
};
MatrixX3f mPoints;
Eigen::Vector3f mCenterPoint;
SimpleProblemBase(const std::vector<Eigen::Vector3f>& iPoints) {
mPoints.resize(iPoints.size(),3);
for (int i = 0; i < (int)iPoints.size(); ++i) {
mPoints.row(i) = iPoints[i];
}
}
void setCenterPoint(const Eigen::Vector3f& iPoint) { mCenterPoint = iPoint; }
int getSampleSize() const { return 3; }
int getNumDataPoints() const { return mPoints.rows(); }
Solution estimate(const std::vector<int>& iIndices) const {
Solution sol;
const int n = iIndices.size();
if (n == 3) {
Eigen::Vector3f p1 = mPoints.row(iIndices[0]);
Eigen::Vector3f p2 = mPoints.row(iIndices[1]);
Eigen::Vector3f p3 = mPoints.row(iIndices[2]);
sol.mPlane.head<3>() = ((p3-p1).cross(p2-p1)).normalized();
sol.mPlane[3] = -sol.mPlane.head<3>().dot(p1);
sol.mCurvature = 0;
float centerDist = sol.mPlane.head<3>().dot(mCenterPoint) + sol.mPlane[3];
if (std::abs(centerDist) > 0.02f) sol.mPlane[3] = 1e10;
}
else {
sol = estimateFull(iIndices);
}
return sol;
}
Solution estimateFull(const std::vector<int>& iIndices) const {
Solution sol;
const int n = iIndices.size();
MatrixX3f data(n,3);
for (int i = 0; i < n; ++i) data.row(i) = mPoints.row(iIndices[i]);
Eigen::Vector3f avg = data.colwise().mean();
data.rowwise() -= avg.transpose();
auto svd = data.jacobiSvd(Eigen::ComputeFullV);
sol.mPlane.head<3>() = svd.matrixV().col(2);
sol.mPlane[3] = -sol.mPlane.head<3>().dot(avg);
sol.mCurvature = svd.singularValues()[2]/n;
sol.mCenterPoint = avg;
return sol;
}
std::vector<double> computeSquaredErrors(const Solution& iSolution) const {
const auto& plane = iSolution.mPlane;
Eigen::VectorXf errors = (mPoints*plane.head<3>()).array() + plane[3];
std::vector<double> errors2(errors.size());
for (int i = 0; i < (int)errors2.size(); ++i) {
errors2[i] = errors[i]*errors[i];
}
return errors2;
}
};
struct SimpleProblem : public SimpleProblemBase {
SimpleProblem(const std::vector<Eigen::Vector3f>& iPoints) :
SimpleProblemBase(iPoints) {}
int getSampleSize() const { return 2; }
Solution estimate(const std::vector<int>& iIndices) const {
Solution sol;
const int n = iIndices.size();
if (n == 2) {
Eigen::Vector3f p1 = mPoints.row(iIndices[0]);
Eigen::Vector3f p2 = mPoints.row(iIndices[1]);
const Eigen::Vector3f& p3 = mCenterPoint;
sol.mPlane.head<3>() = ((p3-p1).cross(p2-p1)).normalized();
sol.mPlane[3] = -sol.mPlane.head<3>().dot(p1);
sol.mCurvature = 0;
}
else {
sol = estimateFull(iIndices);
}
return sol;
}
};
}
PlaneFitter::
PlaneFitter() {
setMaxDistance(0.01);
setMaxIterations(100);
setRefineUsingInliers(true);
float badValue = std::numeric_limits<float>::infinity();
setCenterPoint(Eigen::Vector3f(badValue, badValue, badValue));
}
PlaneFitter::
~PlaneFitter() {
}
void PlaneFitter::
setMaxDistance(const float iDistance) {
mMaxDistance = iDistance;
}
void PlaneFitter::
setCenterPoint(const Eigen::Vector3f& iPoint) {
mCenterPoint = iPoint;
}
void PlaneFitter::
setMaxIterations(const int iIterations) {
mMaxIterations = iIterations;
}
void PlaneFitter::
setRefineUsingInliers(const bool iVal) {
mRefineUsingInliers = iVal;
}
PlaneFitter::Result PlaneFitter::
go(const std::vector<Eigen::Vector3f>& iPoints) const {
if (std::isinf(mCenterPoint[0])) return solve<SimpleProblemBase>(iPoints);
else return solve<SimpleProblem>(iPoints);
}
template<typename T>
PlaneFitter::Result PlaneFitter::
solve(const std::vector<Eigen::Vector3f>& iPoints) const {
Result result;
drc::RansacGeneric<T> ransac;
ransac.setMaximumError(mMaxDistance);
ransac.setRefineUsingInliers(mRefineUsingInliers);
ransac.setMaximumIterations(mMaxIterations);
SimpleProblem problem(iPoints);
problem.setCenterPoint(mCenterPoint);
auto res = ransac.solve(problem);
result.mSuccess = res.mSuccess;
result.mPlane = res.mSolution.mPlane;
result.mCenterPoint = res.mSolution.mCenterPoint;
result.mInliers = res.mInliers;
result.mCurvature = res.mSolution.mCurvature;
return result;
}
|
#include "PlaneFitter.hpp"
#include <limits>
#include <drc_utils/RansacGeneric.hpp>
using namespace planeseg;
namespace {
struct SimpleProblemBase {
struct Solution {
Eigen::Vector4f mPlane;
float mCurvature;
Eigen::Vector3f mCenterPoint;
};
MatrixX3f mPoints;
Eigen::Vector3f mCenterPoint;
SimpleProblemBase(const std::vector<Eigen::Vector3f>& iPoints) {
mPoints.resize(iPoints.size(),3);
for (int i = 0; i < (int)iPoints.size(); ++i) {
mPoints.row(i) = iPoints[i];
}
}
void setCenterPoint(const Eigen::Vector3f& iPoint) { mCenterPoint = iPoint; }
int getSampleSize() const { return 3; }
int getNumDataPoints() const { return mPoints.rows(); }
Solution estimate(const std::vector<int>& iIndices) const {
Solution sol;
const int n = iIndices.size();
if (n == 3) {
Eigen::Vector3f p1 = mPoints.row(iIndices[0]);
Eigen::Vector3f p2 = mPoints.row(iIndices[1]);
Eigen::Vector3f p3 = mPoints.row(iIndices[2]);
sol.mPlane.head<3>() = ((p3-p1).cross(p2-p1)).normalized();
sol.mPlane[3] = -sol.mPlane.head<3>().dot(p1);
sol.mCurvature = 0;
float centerDist = sol.mPlane.head<3>().dot(mCenterPoint) + sol.mPlane[3];
if (std::abs(centerDist) > 0.02f) sol.mPlane[3] = 1e10;
}
else {
sol = estimateFull(iIndices);
}
return sol;
}
Solution estimateFull(const std::vector<int>& iIndices) const {
Solution sol;
const int n = iIndices.size();
MatrixX3f data(n,3);
for (int i = 0; i < n; ++i) data.row(i) = mPoints.row(iIndices[i]);
Eigen::Vector3f avg = data.colwise().mean();
data.rowwise() -= avg.transpose();
auto svd = data.jacobiSvd(Eigen::ComputeFullV);
sol.mPlane.head<3>() = svd.matrixV().col(2);
sol.mPlane[3] = -sol.mPlane.head<3>().dot(avg);
sol.mCurvature = svd.singularValues()[2]/n;
sol.mCenterPoint = avg;
return sol;
}
std::vector<double> computeSquaredErrors(const Solution& iSolution) const {
const auto& plane = iSolution.mPlane;
Eigen::VectorXf errors = (mPoints*plane.head<3>()).array() + plane[3];
std::vector<double> errors2(errors.size());
for (int i = 0; i < (int)errors2.size(); ++i) {
errors2[i] = errors[i]*errors[i];
}
return errors2;
}
};
struct SimpleProblem : public SimpleProblemBase {
SimpleProblem(const std::vector<Eigen::Vector3f>& iPoints) :
SimpleProblemBase(iPoints) {}
int getSampleSize() const { return 2; }
Solution estimate(const std::vector<int>& iIndices) const {
Solution sol;
const int n = iIndices.size();
if (n == 2) {
Eigen::Vector3f p1 = mPoints.row(iIndices[0]);
Eigen::Vector3f p2 = mPoints.row(iIndices[1]);
const Eigen::Vector3f& p3 = mCenterPoint;
sol.mPlane.head<3>() = ((p3-p1).cross(p2-p1)).normalized();
sol.mPlane[3] = -sol.mPlane.head<3>().dot(p1);
sol.mCurvature = 0;
}
else {
sol = estimateFull(iIndices);
}
return sol;
}
};
}
PlaneFitter::
PlaneFitter() {
setMaxDistance(0.01);
setMaxIterations(100);
setRefineUsingInliers(true);
float badValue = std::numeric_limits<float>::infinity();
setCenterPoint(Eigen::Vector3f(badValue, badValue, badValue));
}
PlaneFitter::
~PlaneFitter() {
}
void PlaneFitter::
setMaxDistance(const float iDistance) {
mMaxDistance = iDistance;
}
void PlaneFitter::
setCenterPoint(const Eigen::Vector3f& iPoint) {
mCenterPoint = iPoint;
}
void PlaneFitter::
setMaxIterations(const int iIterations) {
mMaxIterations = iIterations;
}
void PlaneFitter::
setRefineUsingInliers(const bool iVal) {
mRefineUsingInliers = iVal;
}
PlaneFitter::Result PlaneFitter::
go(const std::vector<Eigen::Vector3f>& iPoints) const {
if (std::isinf(mCenterPoint[0])) return solve<SimpleProblemBase>(iPoints);
else return solve<SimpleProblem>(iPoints);
}
template<typename T>
PlaneFitter::Result PlaneFitter::
solve(const std::vector<Eigen::Vector3f>& iPoints) const {
Result result;
drc::RansacGeneric<T> ransac;
ransac.setMaximumError(mMaxDistance);
ransac.setRefineUsingInliers(mRefineUsingInliers);
ransac.setMaximumIterations(mMaxIterations);
T problem(iPoints);
problem.setCenterPoint(mCenterPoint);
auto res = ransac.solve(problem);
result.mSuccess = res.mSuccess;
result.mPlane = res.mSolution.mPlane;
result.mCenterPoint = res.mSolution.mCenterPoint;
result.mInliers = res.mInliers;
result.mCurvature = res.mSolution.mCurvature;
return result;
}
|
select correct plane fit method
|
select correct plane fit method
|
C++
|
bsd-3-clause
|
openhumanoids/oh-distro,openhumanoids/oh-distro,openhumanoids/oh-distro,openhumanoids/oh-distro,openhumanoids/oh-distro,openhumanoids/oh-distro,openhumanoids/oh-distro,openhumanoids/oh-distro
|
bb14e302fc53edefb3d425419f15475a354bf86e
|
src/vmEntry.cpp
|
src/vmEntry.cpp
|
/*
* Copyright 2016 Andrei Pangin
*
* 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 <fstream>
#include <string.h>
#include <stdlib.h>
#include "asyncProfiler.h"
#include "vmEntry.h"
JavaVM* VM::_vm;
jvmtiEnv* VM::_jvmti;
template<class FunctionType>
inline FunctionType getJvmFunction(const char *function_name) {
// get address of function, return null if not found
return (FunctionType) dlsym(RTLD_DEFAULT, function_name);
}
void VM::init(JavaVM* vm) {
_vm = vm;
_vm->GetEnv((void**)&_jvmti, JVMTI_VERSION_1_0);
jvmtiCapabilities capabilities = {0};
capabilities.can_generate_all_class_hook_events = 1;
capabilities.can_get_bytecodes = 1;
capabilities.can_get_constant_pool = 1;
capabilities.can_get_source_file_name = 1;
capabilities.can_get_line_numbers = 1;
capabilities.can_generate_compiled_method_load_events = 1;
_jvmti->AddCapabilities(&capabilities);
jvmtiEventCallbacks callbacks = {0};
callbacks.VMInit = VMInit;
callbacks.ClassLoad = ClassLoad;
callbacks.ClassPrepare = ClassPrepare;
callbacks.CompiledMethodLoad = CompiledMethodLoad;
_jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_LOAD, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_PREPARE, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL);
asgct = getJvmFunction<ASGCTType>("AsyncGetCallTrace");
}
void VM::loadMethodIDs(jvmtiEnv* jvmti, jclass klass) {
jint method_count;
jmethodID* methods;
if (jvmti->GetClassMethods(klass, &method_count, &methods) == 0) {
jvmti->Deallocate((unsigned char*)methods);
}
}
void VM::loadAllMethodIDs(jvmtiEnv* jvmti) {
jint class_count;
jclass* classes;
if (jvmti->GetLoadedClasses(&class_count, &classes) == 0) {
for (int i = 0; i < class_count; i++) {
loadMethodIDs(jvmti, classes[i]);
}
jvmti->Deallocate((unsigned char*)classes);
}
}
extern "C" JNIEXPORT jint JNICALL
Agent_OnLoad(JavaVM* vm, char* options, void* reserved) {
VM::init(vm);
Profiler::_instance.start(DEFAULT_INTERVAL);
return 0;
}
const char OPTION_DELIMITER[] = ",";
const char FRAME_BUFFER_SIZE[] = "frameBufferSize:";
const char FREQ[] = "freq:";
const char START[] = "start";
const char STOP[] = "stop";
const char DUMP_RAW_TRACES[] = "dumpRawTraces:";
extern "C" JNIEXPORT jint JNICALL
Agent_OnAttach(JavaVM* vm, char* options, void* reserved) {
VM::attach(vm);
char args[1024];
if (strlen(options) >= sizeof(args)) {
std::cerr << "List of options is too long" << std::endl;
return -1;
}
strncpy(args, options, sizeof(args));
int freq = 1000 / DEFAULT_INTERVAL;
char *token = strtok(args, OPTION_DELIMITER);
while (token) {
if (strncmp(token, FRAME_BUFFER_SIZE, strlen(FRAME_BUFFER_SIZE)) == 0) {
const char *text = token + strlen(FRAME_BUFFER_SIZE);
const int value = atoi(text);
std::cout << "Setting frame buffer size to " << value << std::endl;
Profiler::_instance.frameBufferSize(value);
} else if (strncmp(token, FREQ, strlen(FREQ)) == 0) {
const char *text = token + strlen(FREQ);
const int value = atoi(text);
if (value <= 0 || value > 1000) {
std::cerr << "Frequency must be in (0, 1000]: " << value << std::endl;
return -1;
}
freq = value;
} else if (strcmp(token, START) == 0) {
if (Profiler::_instance.is_running()) {
std::cerr << "Profiler is already running" << std::endl;
return -1;
}
std::cout << "Profiling started with frequency " << freq << "Hz" << std::endl;
Profiler::_instance.start(1000 / freq);
} else if (strcmp(token, STOP) == 0) {
if (!Profiler::_instance.is_running()) {
std::cerr << "Profiler is not running" << std::endl;
return -1;
}
std::cout << "Profiling stopped" << std::endl;
Profiler::_instance.stop();
Profiler::_instance.dumpTraces(std::cout, DEFAULT_TRACES_TO_DUMP);
Profiler::_instance.dumpMethods(std::cout);
} else if (strncmp(token, DUMP_RAW_TRACES, strlen(DUMP_RAW_TRACES)) == 0) {
if (!Profiler::_instance.is_running()) {
std::cerr << "Profiler is not running" << std::endl;
return -1;
}
std::cout << "Profiling stopped" << std::endl;
Profiler::_instance.stop();
const char *fileName = token + strlen(DUMP_RAW_TRACES);
std::ofstream dump(fileName, std::ios::out | std::ios::trunc);
if (!dump.is_open()) {
std::cerr << "Couldn't open: " << fileName << std::endl;
return -1;
}
std::cout << "Dumping raw traces to " << fileName << std::endl;
Profiler::_instance.dumpRawTraces(dump);
dump.close();
}
token = strtok(NULL, OPTION_DELIMITER);
}
return 0;
}
extern "C" JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM* vm, void* reserved) {
VM::attach(vm);
return JNI_VERSION_1_6;
}
|
/*
* Copyright 2016 Andrei Pangin
*
* 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 <fstream>
#include <string.h>
#include <stdlib.h>
#include "asyncProfiler.h"
#include "vmEntry.h"
JavaVM* VM::_vm;
jvmtiEnv* VM::_jvmti;
template<class FunctionType>
inline FunctionType getJvmFunction(const char *function_name) {
// get address of function, return null if not found
return (FunctionType) dlsym(RTLD_DEFAULT, function_name);
}
void VM::init(JavaVM* vm) {
_vm = vm;
_vm->GetEnv((void**)&_jvmti, JVMTI_VERSION_1_0);
jvmtiCapabilities capabilities = {0};
capabilities.can_generate_all_class_hook_events = 1;
capabilities.can_get_bytecodes = 1;
capabilities.can_get_constant_pool = 1;
capabilities.can_get_source_file_name = 1;
capabilities.can_get_line_numbers = 1;
capabilities.can_generate_compiled_method_load_events = 1;
_jvmti->AddCapabilities(&capabilities);
jvmtiEventCallbacks callbacks = {0};
callbacks.VMInit = VMInit;
callbacks.ClassLoad = ClassLoad;
callbacks.ClassPrepare = ClassPrepare;
callbacks.CompiledMethodLoad = CompiledMethodLoad;
_jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_LOAD, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_PREPARE, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL);
asgct = getJvmFunction<ASGCTType>("AsyncGetCallTrace");
}
void VM::loadMethodIDs(jvmtiEnv* jvmti, jclass klass) {
jint method_count;
jmethodID* methods;
if (jvmti->GetClassMethods(klass, &method_count, &methods) == 0) {
jvmti->Deallocate((unsigned char*)methods);
}
}
void VM::loadAllMethodIDs(jvmtiEnv* jvmti) {
jint class_count;
jclass* classes;
if (jvmti->GetLoadedClasses(&class_count, &classes) == 0) {
for (int i = 0; i < class_count; i++) {
loadMethodIDs(jvmti, classes[i]);
}
jvmti->Deallocate((unsigned char*)classes);
}
}
extern "C" JNIEXPORT jint JNICALL
Agent_OnLoad(JavaVM* vm, char* options, void* reserved) {
VM::init(vm);
Profiler::_instance.start(DEFAULT_INTERVAL);
return 0;
}
const char OPTION_DELIMITER[] = ",";
const char FRAME_BUFFER_SIZE[] = "frameBufferSize:";
const char INTERVAL[] = "interval:";
const char START[] = "start";
const char STOP[] = "stop";
const char DUMP_RAW_TRACES[] = "dumpRawTraces:";
extern "C" JNIEXPORT jint JNICALL
Agent_OnAttach(JavaVM* vm, char* options, void* reserved) {
VM::attach(vm);
char args[1024];
if (strlen(options) >= sizeof(args)) {
std::cerr << "List of options is too long" << std::endl;
return -1;
}
strncpy(args, options, sizeof(args));
int interval = DEFAULT_INTERVAL;
char *token = strtok(args, OPTION_DELIMITER);
while (token) {
if (strncmp(token, FRAME_BUFFER_SIZE, strlen(FRAME_BUFFER_SIZE)) == 0) {
const char *text = token + strlen(FRAME_BUFFER_SIZE);
const int value = atoi(text);
std::cout << "Setting frame buffer size to " << value << std::endl;
Profiler::_instance.frameBufferSize(value);
} else if (strncmp(token, INTERVAL, strlen(INTERVAL)) == 0) {
const char *text = token + strlen(INTERVAL);
const int value = atoi(text);
if (value <= 0) {
std::cerr << "Interval must be positive: " << value << std::endl;
return -1;
}
interval = value;
} else if (strcmp(token, START) == 0) {
if (!Profiler::_instance.is_running()) {
std::cout << "Profiling started with interval " << interval << " ms" << std::endl;
Profiler::_instance.start(interval);
}
} else if (strcmp(token, STOP) == 0) {
std::cout << "Profiling stopped" << std::endl;
Profiler::_instance.stop();
Profiler::_instance.dumpTraces(std::cout, DEFAULT_TRACES_TO_DUMP);
Profiler::_instance.dumpMethods(std::cout);
} else if (strncmp(token, DUMP_RAW_TRACES, strlen(DUMP_RAW_TRACES)) == 0) {
std::cout << "Profiling stopped" << std::endl;
Profiler::_instance.stop();
const char *fileName = token + strlen(DUMP_RAW_TRACES);
std::ofstream dump(fileName, std::ios::out | std::ios::trunc);
if (!dump.is_open()) {
std::cerr << "Couldn't open: " << fileName << std::endl;
return -1;
}
std::cout << "Dumping raw traces to " << fileName << std::endl;
Profiler::_instance.dumpRawTraces(dump);
dump.close();
}
token = strtok(NULL, OPTION_DELIMITER);
}
return 0;
}
extern "C" JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM* vm, void* reserved) {
VM::attach(vm);
return JNI_VERSION_1_6;
}
|
Switch from frequency to interval and revert some profiler state checks
|
Switch from frequency to interval and revert some profiler state checks
|
C++
|
apache-2.0
|
jvm-profiling-tools/async-profiler,incubos/async-profiler,incubos/async-profiler,jvm-profiling-tools/async-profiler,incubos/async-profiler,apangin/async-profiler,apangin/async-profiler,incubos/async-profiler,apangin/async-profiler,jvm-profiling-tools/async-profiler,apangin/async-profiler,jvm-profiling-tools/async-profiler,jvm-profiling-tools/async-profiler
|
99a2aee476b519392940dff42658722a03eb944e
|
src/abaclade/collections/detail/trie_ordered_multimap_impl.cxx
|
src/abaclade/collections/detail/trie_ordered_multimap_impl.cxx
|
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2015
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abaclade.hxx>
#include <abaclade/bitmanip.hxx>
#include <abaclade/collections/detail/trie_ordered_multimap_impl.hxx>
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace abc { namespace collections { namespace detail {
bitwise_trie_ordered_multimap_impl::bitwise_trie_ordered_multimap_impl(
bitwise_trie_ordered_multimap_impl && bwtommi
) :
m_pnRoot(bwtommi.m_pnRoot),
m_cValues(bwtommi.m_cValues),
mc_iKeyPadding(bwtommi.mc_iKeyPadding),
mc_iTreeAnchorsLevel(bwtommi.mc_iTreeAnchorsLevel) {
bwtommi.m_pnRoot.tn = nullptr;
bwtommi.m_cValues = 0;
}
bitwise_trie_ordered_multimap_impl & bitwise_trie_ordered_multimap_impl::operator=(
bitwise_trie_ordered_multimap_impl && bwtommi
) {
// Assume that the subclass has already moved *this out.
m_pnRoot = bwtommi.m_pnRoot;
bwtommi.m_pnRoot.tn = nullptr;
m_cValues = bwtommi.m_cValues;
bwtommi.m_cValues = 0;
return *this;
}
bitwise_trie_ordered_multimap_impl::list_node * bitwise_trie_ordered_multimap_impl::add(
type_void_adapter const & typeValue, std::uintmax_t iKey, void const * pValue, bool bMove
) {
ABC_TRACE_FUNC(this/*, typeValue*/, iKey, pValue, bMove);
tree_node * ptnParent;
unsigned iBitsPermutation;
// Descend into the tree, creating nodes as necessary until the path for iKey is complete.
{
// ppnChildInParent points to *ptnParent’s parent’s pointer to *ptnParent.
tree_or_list_node_ptr * ppnChildInParent = &m_pnRoot;
std::uintmax_t iKeyRemaining = iKey << mc_iKeyPadding;
unsigned iLevel = 0;
do {
ptnParent = ppnChildInParent->tn;
if (!ptnParent) {
ptnParent = (iLevel == mc_iTreeAnchorsLevel ? new anchor_node() : new tree_node());
ppnChildInParent->tn = ptnParent;
}
iKeyRemaining = bitmanip::rotate_l(iKeyRemaining, smc_cBitsPerLevel);
iBitsPermutation = static_cast<unsigned>(
iKeyRemaining & (smc_cBitPermutationsPerLevel - 1)
);
ppnChildInParent = &ptnParent->m_apnChildren[iBitsPermutation];
} while (++iLevel <= mc_iTreeAnchorsLevel);
}
// We got here, so *ptnParent is actually an anchor_node. Append a new node to its list.
anchor_node_slot ans(static_cast<anchor_node *>(ptnParent), iBitsPermutation);
list_node * pln = ans.push_back(typeValue, pValue, bMove);
++m_cValues;
return pln;
}
void bitwise_trie_ordered_multimap_impl::clear(type_void_adapter const & typeValue) {
ABC_TRACE_FUNC(this/*, typeValue*/);
if (m_pnRoot.tn) {
if (mc_iTreeAnchorsLevel == 0) {
// *pnRoot is an anchor.
destruct_anchor_node(typeValue, static_cast<anchor_node *>(m_pnRoot.tn));
} else {
destruct_tree_node(typeValue, m_pnRoot.tn, 0);
}
m_pnRoot = tree_or_list_node_ptr();
m_cValues = 0;
}
}
void bitwise_trie_ordered_multimap_impl::destruct_anchor_node(
type_void_adapter const & typeValue, anchor_node * pan
) {
ABC_TRACE_FUNC(this/*, typeValue*/, pan);
unsigned iBitsPermutation = 0;
do {
if (list_node * pln = pan->m_apnChildren[iBitsPermutation].ln) {
doubly_linked_list_impl::destruct_list(typeValue, pln);
}
} while (++iBitsPermutation < smc_cBitPermutationsPerLevel);
delete pan;
}
void bitwise_trie_ordered_multimap_impl::destruct_tree_node(
type_void_adapter const & typeValue, tree_node * ptn, unsigned iLevel
) {
ABC_TRACE_FUNC(this/*, typeValue*/, ptn, iLevel);
++iLevel;
unsigned iBitsPermutation = 0;
do {
if (tree_node * ptnChild = ptn->m_apnChildren[iBitsPermutation].tn) {
if (iLevel == mc_iTreeAnchorsLevel) {
destruct_anchor_node(typeValue, static_cast<anchor_node *>(ptnChild));
} else {
destruct_tree_node(typeValue, ptnChild, iLevel);
}
}
} while (++iBitsPermutation < smc_cBitPermutationsPerLevel);
delete ptn;
}
bitwise_trie_ordered_multimap_impl::list_node * bitwise_trie_ordered_multimap_impl::find(
std::uintmax_t iKey
) {
ABC_TRACE_FUNC(this, iKey);
if (anchor_node_slot ans = find_anchor_node_slot(iKey)) {
return ans.first_child();
} else {
return nullptr;
}
}
bitwise_trie_ordered_multimap_impl::anchor_node_slot
bitwise_trie_ordered_multimap_impl::find_anchor_node_slot(std::uintmax_t iKey) const {
ABC_TRACE_FUNC(this, iKey);
tree_node * ptnParent = m_pnRoot.tn;
std::uintmax_t iKeyRemaining = iKey << mc_iKeyPadding;
std::size_t iLevel = 0;
for (;;) {
iKeyRemaining = bitmanip::rotate_l(iKeyRemaining, smc_cBitsPerLevel);
unsigned iBitsPermutation = static_cast<unsigned>(
iKeyRemaining & (smc_cBitPermutationsPerLevel - 1)
);
if (iLevel == mc_iTreeAnchorsLevel) {
// At this level, *ptnParent is an anchor.
return anchor_node_slot(static_cast<anchor_node *>(ptnParent), iBitsPermutation);
} else if (!ptnParent) {
return anchor_node_slot(nullptr, 0);
}
ptnParent = ptnParent->m_apnChildren[iBitsPermutation].tn;
++iLevel;
}
}
bitwise_trie_ordered_multimap_impl::key_value_ptr bitwise_trie_ordered_multimap_impl::front() {
ABC_TRACE_FUNC(this);
tree_or_list_node_ptr pnChild;
std::uintmax_t iKey = 0;
// Descend into the tree.
tree_node * ptnParent = m_pnRoot.tn;
unsigned iLevel = 0;
do {
if (!ptnParent) {
return key_value_ptr(0, nullptr);
}
// Look for the left-most branch to descend into.
unsigned iChild = 0;
do {
pnChild = ptnParent->m_apnChildren[iChild];
if (pnChild.tn) {
// Prepend the selected bit permutation to the key.
iKey <<= smc_cBitsPerLevel;
iKey |= static_cast<std::uintmax_t>(iChild);
break;
}
} while (++iChild < smc_cBitPermutationsPerLevel);
ptnParent = pnChild.tn;
} while (++iLevel <= mc_iTreeAnchorsLevel);
// We got to the leaf level, so we can return pnChild.ln, though it might be nullptr.
return key_value_ptr(iKey, pnChild.ln);
}
void bitwise_trie_ordered_multimap_impl::prune_branch(std::uintmax_t iKey) {
tree_node * ptn = m_pnRoot.tn, ** pptnTopmostNullable = &m_pnRoot.tn;
tree_node * aptnAncestorsStack[smc_cBitPermutationsPerLevel];
std::uintmax_t iKeyRemaining = iKey << mc_iKeyPadding;
unsigned iLevel = 0;
int iLastNonEmptyLevel = -1;
do {
iKeyRemaining = bitmanip::rotate_l(iKeyRemaining, smc_cBitsPerLevel);
unsigned iBitsPermutation = static_cast<unsigned>(
iKeyRemaining & (smc_cBitPermutationsPerLevel - 1)
);
// Check if the node has any children other than [iBitsPermutation].
unsigned iChild = 0;
do {
if (iChild != iBitsPermutation && ptn->m_apnChildren[iChild].tn) {
iLastNonEmptyLevel = static_cast<int>(iLevel);
pptnTopmostNullable = &ptn->m_apnChildren[iBitsPermutation].tn;
break;
}
} while (++iChild < smc_cBitPermutationsPerLevel);
// Push this node on the ancestors stack.
aptnAncestorsStack[iLevel] = ptn;
ptn = ptn->m_apnChildren[iBitsPermutation].tn;
} while (++iLevel <= mc_iTreeAnchorsLevel);
// Now prune every empty level.
while (static_cast<int>(--iLevel) > iLastNonEmptyLevel) {
if (iLevel == mc_iTreeAnchorsLevel) {
delete static_cast<anchor_node *>(aptnAncestorsStack[iLevel]);
} else {
delete aptnAncestorsStack[iLevel];
}
}
// Make the last non-empty level no longer point to the branch we just pruned.
*pptnTopmostNullable = nullptr;
}
void bitwise_trie_ordered_multimap_impl::remove_value(
type_void_adapter const & typeValue, std::uintmax_t iKey, list_node * pln
) {
ABC_TRACE_FUNC(this/*, typeValue*/, iKey, pln);
if (pln->next() && pln->prev()) {
// *pln is in the middle of its list, so we don’t need to find and update the anchor.
doubly_linked_list_impl::remove(typeValue, nullptr, nullptr, pln);
} else if (!pln->next() && !pln->prev()) {
// *pln is in the only node in its list, so we can destruct it and prune the whole branch.
typeValue.destruct(pln->value_ptr(typeValue));
delete pln;
prune_branch(iKey);
} else {
// *pln is the first or the last node in its list, so we need to update the anchor.
if (anchor_node_slot ans = find_anchor_node_slot(iKey)) {
ans.remove(typeValue, pln);
} else {
ABC_THROW(iterator_error, ());
}
}
--m_cValues;
}
}}} //namespace abc::collections::detail
|
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2015
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abaclade.hxx>
#include <abaclade/bitmanip.hxx>
#include <abaclade/collections/detail/trie_ordered_multimap_impl.hxx>
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace abc { namespace collections { namespace detail {
bitwise_trie_ordered_multimap_impl::bitwise_trie_ordered_multimap_impl(
bitwise_trie_ordered_multimap_impl && bwtommi
) :
m_pnRoot(bwtommi.m_pnRoot),
m_cValues(bwtommi.m_cValues),
mc_iKeyPadding(bwtommi.mc_iKeyPadding),
mc_iTreeAnchorsLevel(bwtommi.mc_iTreeAnchorsLevel) {
bwtommi.m_pnRoot.tn = nullptr;
bwtommi.m_cValues = 0;
}
bitwise_trie_ordered_multimap_impl & bitwise_trie_ordered_multimap_impl::operator=(
bitwise_trie_ordered_multimap_impl && bwtommi
) {
// Assume that the subclass has already moved *this out.
m_pnRoot = bwtommi.m_pnRoot;
bwtommi.m_pnRoot.tn = nullptr;
m_cValues = bwtommi.m_cValues;
bwtommi.m_cValues = 0;
return *this;
}
bitwise_trie_ordered_multimap_impl::list_node * bitwise_trie_ordered_multimap_impl::add(
type_void_adapter const & typeValue, std::uintmax_t iKey, void const * pValue, bool bMove
) {
ABC_TRACE_FUNC(this/*, typeValue*/, iKey, pValue, bMove);
tree_node * ptnParent;
unsigned iBitsPermutation;
// Descend into the tree, creating nodes as necessary until the path for iKey is complete.
{
// ppnChildInParent points to *ptnParent’s parent’s pointer to *ptnParent.
tree_or_list_node_ptr * ppnChildInParent = &m_pnRoot;
std::uintmax_t iKeyRemaining = iKey << mc_iKeyPadding;
unsigned iLevel = 0;
do {
ptnParent = ppnChildInParent->tn;
if (!ptnParent) {
ptnParent = (iLevel == mc_iTreeAnchorsLevel ? new anchor_node() : new tree_node());
ppnChildInParent->tn = ptnParent;
}
iKeyRemaining = bitmanip::rotate_l(iKeyRemaining, smc_cBitsPerLevel);
iBitsPermutation = static_cast<unsigned>(
iKeyRemaining & (smc_cBitPermutationsPerLevel - 1)
);
ppnChildInParent = &ptnParent->m_apnChildren[iBitsPermutation];
} while (++iLevel <= mc_iTreeAnchorsLevel);
}
// We got here, so *ptnParent is actually an anchor_node. Append a new node to its list.
anchor_node_slot ans(static_cast<anchor_node *>(ptnParent), iBitsPermutation);
list_node * pln = ans.push_back(typeValue, pValue, bMove);
++m_cValues;
return pln;
}
void bitwise_trie_ordered_multimap_impl::clear(type_void_adapter const & typeValue) {
ABC_TRACE_FUNC(this/*, typeValue*/);
if (m_pnRoot.tn) {
if (mc_iTreeAnchorsLevel == 0) {
// *pnRoot is an anchor.
destruct_anchor_node(typeValue, static_cast<anchor_node *>(m_pnRoot.tn));
} else {
destruct_tree_node(typeValue, m_pnRoot.tn, 0);
}
m_pnRoot = tree_or_list_node_ptr();
m_cValues = 0;
}
}
void bitwise_trie_ordered_multimap_impl::destruct_anchor_node(
type_void_adapter const & typeValue, anchor_node * pan
) {
ABC_TRACE_FUNC(this/*, typeValue*/, pan);
unsigned iBitsPermutation = 0;
do {
if (list_node * pln = pan->m_apnChildren[iBitsPermutation].ln) {
doubly_linked_list_impl::destruct_list(typeValue, pln);
}
} while (++iBitsPermutation < smc_cBitPermutationsPerLevel);
delete pan;
}
void bitwise_trie_ordered_multimap_impl::destruct_tree_node(
type_void_adapter const & typeValue, tree_node * ptn, unsigned iLevel
) {
ABC_TRACE_FUNC(this/*, typeValue*/, ptn, iLevel);
++iLevel;
unsigned iBitsPermutation = 0;
do {
if (tree_node * ptnChild = ptn->m_apnChildren[iBitsPermutation].tn) {
if (iLevel == mc_iTreeAnchorsLevel) {
destruct_anchor_node(typeValue, static_cast<anchor_node *>(ptnChild));
} else {
destruct_tree_node(typeValue, ptnChild, iLevel);
}
}
} while (++iBitsPermutation < smc_cBitPermutationsPerLevel);
delete ptn;
}
bitwise_trie_ordered_multimap_impl::list_node * bitwise_trie_ordered_multimap_impl::find(
std::uintmax_t iKey
) {
ABC_TRACE_FUNC(this, iKey);
if (anchor_node_slot ans = find_anchor_node_slot(iKey)) {
return ans.first_child();
} else {
return nullptr;
}
}
bitwise_trie_ordered_multimap_impl::anchor_node_slot
bitwise_trie_ordered_multimap_impl::find_anchor_node_slot(std::uintmax_t iKey) const {
ABC_TRACE_FUNC(this, iKey);
tree_node * ptnParent = m_pnRoot.tn;
std::uintmax_t iKeyRemaining = iKey << mc_iKeyPadding;
unsigned iLevel = 0;
for (;;) {
iKeyRemaining = bitmanip::rotate_l(iKeyRemaining, smc_cBitsPerLevel);
unsigned iBitsPermutation = static_cast<unsigned>(
iKeyRemaining & (smc_cBitPermutationsPerLevel - 1)
);
if (iLevel == mc_iTreeAnchorsLevel) {
// At this level, *ptnParent is an anchor.
return anchor_node_slot(static_cast<anchor_node *>(ptnParent), iBitsPermutation);
} else if (!ptnParent) {
return anchor_node_slot(nullptr, 0);
}
ptnParent = ptnParent->m_apnChildren[iBitsPermutation].tn;
++iLevel;
}
}
bitwise_trie_ordered_multimap_impl::key_value_ptr bitwise_trie_ordered_multimap_impl::front() {
ABC_TRACE_FUNC(this);
tree_or_list_node_ptr pnChild;
std::uintmax_t iKey = 0;
// Descend into the tree.
tree_node * ptnParent = m_pnRoot.tn;
unsigned iLevel = 0;
do {
if (!ptnParent) {
return key_value_ptr(0, nullptr);
}
// Look for the left-most branch to descend into.
unsigned iChild = 0;
do {
pnChild = ptnParent->m_apnChildren[iChild];
if (pnChild.tn) {
// Prepend the selected bit permutation to the key.
iKey <<= smc_cBitsPerLevel;
iKey |= static_cast<std::uintmax_t>(iChild);
break;
}
} while (++iChild < smc_cBitPermutationsPerLevel);
ptnParent = pnChild.tn;
} while (++iLevel <= mc_iTreeAnchorsLevel);
// We got to the leaf level, so we can return pnChild.ln, though it might be nullptr.
return key_value_ptr(iKey, pnChild.ln);
}
void bitwise_trie_ordered_multimap_impl::prune_branch(std::uintmax_t iKey) {
tree_node * ptn = m_pnRoot.tn, ** pptnTopmostNullable = &m_pnRoot.tn;
tree_node * aptnAncestorsStack[smc_cBitPermutationsPerLevel];
std::uintmax_t iKeyRemaining = iKey << mc_iKeyPadding;
unsigned iLevel = 0;
int iLastNonEmptyLevel = -1;
do {
iKeyRemaining = bitmanip::rotate_l(iKeyRemaining, smc_cBitsPerLevel);
unsigned iBitsPermutation = static_cast<unsigned>(
iKeyRemaining & (smc_cBitPermutationsPerLevel - 1)
);
// Check if the node has any children other than [iBitsPermutation].
unsigned iChild = 0;
do {
if (iChild != iBitsPermutation && ptn->m_apnChildren[iChild].tn) {
iLastNonEmptyLevel = static_cast<int>(iLevel);
pptnTopmostNullable = &ptn->m_apnChildren[iBitsPermutation].tn;
break;
}
} while (++iChild < smc_cBitPermutationsPerLevel);
// Push this node on the ancestors stack.
aptnAncestorsStack[iLevel] = ptn;
ptn = ptn->m_apnChildren[iBitsPermutation].tn;
} while (++iLevel <= mc_iTreeAnchorsLevel);
// Now prune every empty level.
while (static_cast<int>(--iLevel) > iLastNonEmptyLevel) {
if (iLevel == mc_iTreeAnchorsLevel) {
delete static_cast<anchor_node *>(aptnAncestorsStack[iLevel]);
} else {
delete aptnAncestorsStack[iLevel];
}
}
// Make the last non-empty level no longer point to the branch we just pruned.
*pptnTopmostNullable = nullptr;
}
void bitwise_trie_ordered_multimap_impl::remove_value(
type_void_adapter const & typeValue, std::uintmax_t iKey, list_node * pln
) {
ABC_TRACE_FUNC(this/*, typeValue*/, iKey, pln);
if (pln->next() && pln->prev()) {
// *pln is in the middle of its list, so we don’t need to find and update the anchor.
doubly_linked_list_impl::remove(typeValue, nullptr, nullptr, pln);
} else if (!pln->next() && !pln->prev()) {
// *pln is in the only node in its list, so we can destruct it and prune the whole branch.
typeValue.destruct(pln->value_ptr(typeValue));
delete pln;
prune_branch(iKey);
} else {
// *pln is the first or the last node in its list, so we need to update the anchor.
if (anchor_node_slot ans = find_anchor_node_slot(iKey)) {
ans.remove(typeValue, pln);
} else {
ABC_THROW(iterator_error, ());
}
}
--m_cValues;
}
}}} //namespace abc::collections::detail
|
Change iLevel type to unsigned for consistency
|
Change iLevel type to unsigned for consistency
|
C++
|
lgpl-2.1
|
raffaellod/lofty,raffaellod/lofty
|
c0a332693eceec4171c4e2fef30924e4f22771fc
|
src/wasm-js.cpp
|
src/wasm-js.cpp
|
//
// wasm intepreter for asm2wasm output, in a js environment. receives asm.js,
// generates a runnable module suitable as a polyfill.
//
// this polyfills an emscripten --separate-asm *.asm.js file, as a drop-in
// replacement. it writes the wasm module to Module.asm, and sets Module.buffer.
//
#include <emscripten.h>
#include "asm2wasm.h"
#include "wasm-interpreter.h"
using namespace cashew;
using namespace wasm;
ModuleInstance* instance = nullptr;
// receives asm.js code, parses into wasm and returns an instance handle.
// this creates a module, an external interface, a builder, and a module instance,
// all of which are then the responsibility of the caller to free.
// note: this modifies the input.
extern "C" void EMSCRIPTEN_KEEPALIVE load_asm(char *input) {
assert(instance == nullptr); // singleton
// emcc --separate-asm modules look like
//
// Module["asm"] = (function(global, env, buffer) {
// ..
// });
//
// we need to clean that up.
size_t num = strlen(input);
assert(*input == 'M');
while (*input != 'f') {
input++;
num--;
}
char *end = input + num - 1;
while (*end != '}') {
*end = 0;
end--;
}
int debug = 0;
if (debug) std::cerr << "parsing...\n";
cashew::Parser<Ref, DotZeroValueBuilder> builder;
Ref asmjs = builder.parseToplevel(input);
Module* wasm = new Module();
if (debug) std::cerr << "wasming...\n";
Asm2WasmBuilder* asm2wasm = new Asm2WasmBuilder(*wasm);
asm2wasm->processAsm(asmjs);
if (debug) std::cerr << "optimizing...\n";
asm2wasm->optimize();
//std::cerr << *wasm << '\n';
if (debug) std::cerr << "generating exports...\n";
EM_ASM({
Module['asmExports'] = {};
});
for (auto& curr : wasm->exports) {
EM_ASM_({
var name = Pointer_stringify($0);
Module['asmExports'][name] = function() {
Module['tempArguments'] = Array.prototype.slice.call(arguments);
return Module['_call_from_js']($0);
};
}, curr.name.str);
}
if (debug) std::cerr << "creating instance...\n";
struct JSExternalInterface : ModuleInstance::ExternalInterface {
Literal callImport(Import *import, ModuleInstance::LiteralList& arguments) override {
EM_ASM({
Module['tempArguments'] = [];
});
for (auto& argument : arguments) {
if (argument.type == i32) {
EM_ASM_({ Module['tempArguments'].push($0) }, argument.geti32());
} else if (argument.type == f64) {
EM_ASM_({ Module['tempArguments'].push($0) }, argument.getf64());
} else {
abort();
}
}
return Literal(EM_ASM_DOUBLE({
var mod = Pointer_stringify($0);
var base = Pointer_stringify($1);
var tempArguments = Module['tempArguments'];
Module['tempArguments'] = null;
var lookup = Module['info'];
if (mod.indexOf('.') < 0) {
lookup = (lookup || {})[mod];
} else {
var parts = mod.split('.');
lookup = (lookup || {})[parts[0]];
lookup = (lookup || {})[parts[1]];
}
lookup = (lookup || {})[base];
if (!lookup) {
abort('bad CallImport to (' + mod + ').' + base);
}
return lookup.apply(null, tempArguments);
}, import->module.str, import->base.str));
}
Literal load(Load* load, Literal ptr) override {
size_t addr = ptr.geti32();
assert(load->align == load->bytes);
if (!load->float_) {
if (load->bytes == 1) {
if (load->signed_) {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAP8'][$0] }, addr));
} else {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAPU8'][$0] }, addr));
}
} else if (load->bytes == 2) {
if (load->signed_) {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAP16'][$0] }, addr));
} else {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAPU16'][$0] }, addr));
}
} else if (load->bytes == 4) {
if (load->signed_) {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAP32'][$0] }, addr));
} else {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAPU32'][$0] }, addr));
}
}
abort();
} else {
if (load->bytes == 4) {
return Literal(EM_ASM_DOUBLE({ return Module['info'].parent['HEAPF32'][$0] }, addr));
} else if (load->bytes == 8) {
return Literal(EM_ASM_DOUBLE({ return Module['info'].parent['HEAPF64'][$0] }, addr));
}
abort();
}
}
void store(Store* store, Literal ptr, Literal value) override {
size_t addr = ptr.geti32();
assert(store->align == store->bytes);
if (!store->float_) {
if (store->bytes == 1) {
EM_ASM_INT({ Module['info'].parent['HEAP8'][$0] = $1 }, addr, value.geti32());
} else if (store->bytes == 2) {
EM_ASM_INT({ Module['info'].parent['HEAP16'][$0] = $1 }, addr, value.geti32());
} else if (store->bytes == 4) {
EM_ASM_INT({ Module['info'].parent['HEAP32'][$0] = $1 }, addr, value.geti32());
} else {
abort();
}
} else {
if (store->bytes == 4) {
EM_ASM_DOUBLE({ Module['info'].parent['HEAPF32'][$0] = $1 }, addr, value.getf64());
} else if (store->bytes == 8) {
EM_ASM_DOUBLE({ Module['info'].parent['HEAPF64'][$0] = $1 }, addr, value.getf64());
} else {
abort();
}
}
}
};
instance = new ModuleInstance(*wasm, new JSExternalInterface());
}
// Does a call from js into an export of the module.
extern "C" double EMSCRIPTEN_KEEPALIVE call_from_js(const char *target) {
IString name(target);
assert(instance->functions.find(name) != instance->functions.end());
Function *function = instance->functions[name];
size_t seen = EM_ASM_INT_V({ return Module['tempArguments'].length });
size_t actual = function->params.size();
ModuleInstance::LiteralList arguments;
for (size_t i = 0; i < actual; i++) {
WasmType type = function->params[i].type;
// add the parameter, with a zero value if JS did not provide it.
if (type == i32) {
arguments.push_back(Literal(i < seen ? EM_ASM_INT({ return Module['tempArguments'][$0] }, i) : (int32_t)0));
} else if (type == f64) {
arguments.push_back(Literal(i < seen ? EM_ASM_DOUBLE({ return Module['tempArguments'][$0] }, i) : (double)0.0));
} else {
abort();
}
}
Literal ret = instance->callFunction(name, arguments);
if (ret.type == i32) return ret.i32;
if (ret.type == f64) return ret.f64;
abort();
}
|
//
// wasm intepreter for asm2wasm output, in a js environment. receives asm.js,
// generates a runnable module suitable as a polyfill.
//
// this polyfills an emscripten --separate-asm *.asm.js file, as a drop-in
// replacement. it writes the wasm module to Module.asm, and sets Module.buffer.
//
#include <emscripten.h>
#include "asm2wasm.h"
#include "wasm-interpreter.h"
using namespace cashew;
using namespace wasm;
ModuleInstance* instance = nullptr;
// receives asm.js code, parses into wasm and returns an instance handle.
// this creates a module, an external interface, a builder, and a module instance,
// all of which are then the responsibility of the caller to free.
// note: this modifies the input.
extern "C" void EMSCRIPTEN_KEEPALIVE load_asm(char *input) {
assert(instance == nullptr); // singleton
// emcc --separate-asm modules look like
//
// Module["asm"] = (function(global, env, buffer) {
// ..
// });
//
// we need to clean that up.
size_t num = strlen(input);
assert(*input == 'M');
while (*input != 'f') {
input++;
num--;
}
char *end = input + num - 1;
while (*end != '}') {
*end = 0;
end--;
}
int debug = 0;
if (debug) std::cerr << "parsing...\n";
cashew::Parser<Ref, DotZeroValueBuilder> builder;
Ref asmjs = builder.parseToplevel(input);
Module* wasm = new Module();
if (debug) std::cerr << "wasming...\n";
Asm2WasmBuilder* asm2wasm = new Asm2WasmBuilder(*wasm);
asm2wasm->processAsm(asmjs);
if (debug) std::cerr << "optimizing...\n";
asm2wasm->optimize();
//std::cerr << *wasm << '\n';
if (debug) std::cerr << "generating exports...\n";
EM_ASM({
Module['asmExports'] = {};
});
for (auto& curr : wasm->exports) {
EM_ASM_({
var name = Pointer_stringify($0);
Module['asmExports'][name] = function() {
Module['tempArguments'] = Array.prototype.slice.call(arguments);
return Module['_call_from_js']($0);
};
}, curr.name.str);
}
if (debug) std::cerr << "creating instance...\n";
struct JSExternalInterface : ModuleInstance::ExternalInterface {
Literal callImport(Import *import, ModuleInstance::LiteralList& arguments) override {
EM_ASM({
Module['tempArguments'] = [];
});
for (auto& argument : arguments) {
if (argument.type == i32) {
EM_ASM_({ Module['tempArguments'].push($0) }, argument.geti32());
} else if (argument.type == f64) {
EM_ASM_({ Module['tempArguments'].push($0) }, argument.getf64());
} else {
abort();
}
}
return Literal(EM_ASM_DOUBLE({
var mod = Pointer_stringify($0);
var base = Pointer_stringify($1);
var tempArguments = Module['tempArguments'];
Module['tempArguments'] = null;
var lookup = Module['info'];
if (mod.indexOf('.') < 0) {
lookup = (lookup || {})[mod];
} else {
var parts = mod.split('.');
lookup = (lookup || {})[parts[0]];
lookup = (lookup || {})[parts[1]];
}
lookup = (lookup || {})[base];
if (!lookup) {
abort('bad CallImport to (' + mod + ').' + base);
}
return lookup.apply(null, tempArguments);
}, import->module.str, import->base.str));
}
Literal load(Load* load, Literal ptr) override {
size_t addr = ptr.geti32();
assert(load->align == load->bytes);
if (!load->float_) {
if (load->bytes == 1) {
if (load->signed_) {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAP8'][$0] }, addr));
} else {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAPU8'][$0] }, addr));
}
} else if (load->bytes == 2) {
if (load->signed_) {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAP16'][$0] }, addr));
} else {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAPU16'][$0] }, addr));
}
} else if (load->bytes == 4) {
if (load->signed_) {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAP32'][$0] }, addr));
} else {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAPU32'][$0] }, addr));
}
}
abort();
} else {
if (load->bytes == 4) {
return Literal(EM_ASM_DOUBLE({ return Module['info'].parent['HEAPF32'][$0] }, addr)); // XXX expands into double
} else if (load->bytes == 8) {
return Literal(EM_ASM_DOUBLE({ return Module['info'].parent['HEAPF64'][$0] }, addr));
}
abort();
}
}
void store(Store* store, Literal ptr, Literal value) override {
size_t addr = ptr.geti32();
assert(store->align == store->bytes);
if (!store->float_) {
if (store->bytes == 1) {
EM_ASM_INT({ Module['info'].parent['HEAP8'][$0] = $1 }, addr, value.geti32());
} else if (store->bytes == 2) {
EM_ASM_INT({ Module['info'].parent['HEAP16'][$0] = $1 }, addr, value.geti32());
} else if (store->bytes == 4) {
EM_ASM_INT({ Module['info'].parent['HEAP32'][$0] = $1 }, addr, value.geti32());
} else {
abort();
}
} else {
if (store->bytes == 4) {
EM_ASM_DOUBLE({ Module['info'].parent['HEAPF32'][$0] = $1 }, addr, value.getf64());
} else if (store->bytes == 8) {
EM_ASM_DOUBLE({ Module['info'].parent['HEAPF64'][$0] = $1 }, addr, value.getf64());
} else {
abort();
}
}
}
};
instance = new ModuleInstance(*wasm, new JSExternalInterface());
}
// Does a call from js into an export of the module.
extern "C" double EMSCRIPTEN_KEEPALIVE call_from_js(const char *target) {
IString name(target);
assert(instance->functions.find(name) != instance->functions.end());
Function *function = instance->functions[name];
size_t seen = EM_ASM_INT_V({ return Module['tempArguments'].length });
size_t actual = function->params.size();
ModuleInstance::LiteralList arguments;
for (size_t i = 0; i < actual; i++) {
WasmType type = function->params[i].type;
// add the parameter, with a zero value if JS did not provide it.
if (type == i32) {
arguments.push_back(Literal(i < seen ? EM_ASM_INT({ return Module['tempArguments'][$0] }, i) : (int32_t)0));
} else if (type == f32) {
arguments.push_back(Literal(i < seen ? (float)EM_ASM_DOUBLE({ return Module['tempArguments'][$0] }, i) : (float)0.0));
} else if (type == f64) {
arguments.push_back(Literal(i < seen ? EM_ASM_DOUBLE({ return Module['tempArguments'][$0] }, i) : (double)0.0));
} else {
abort();
}
}
Literal ret = instance->callFunction(name, arguments);
if (ret.type == none) return 0;
if (ret.type == i32) return ret.i32;
if (ret.type == f32) return ret.f32;
if (ret.type == f64) return ret.f64;
abort();
}
|
handle float and void types in js<->wasm calls
|
handle float and void types in js<->wasm calls
|
C++
|
apache-2.0
|
yurydelendik/binaryen,yurydelendik/binaryen,yurydelendik/binaryen,ddcc/binaryen,WebAssembly/binaryen,WebAssembly/binaryen,ddcc/binaryen,ddcc/binaryen,yurydelendik/binaryen,yurydelendik/binaryen,WebAssembly/binaryen,ddcc/binaryen,ddcc/binaryen,WebAssembly/binaryen,WebAssembly/binaryen
|
1439158543934922e2a371b1ec04485fadcbc10f
|
source/bundles/product/ProductBundleActivator.cpp
|
source/bundles/product/ProductBundleActivator.cpp
|
#include "ProductBundleActivator.h"
#include "ProductSearchService.h"
#include "ProductTaskService.h"
#include "ProductIndexHooker.h"
#include "ProductScdReceiver.h"
#include <bundles/index/IndexTaskService.h>
#include <bundles/index/IndexSearchService.h>
#include <common/SFLogger.h>
#include <index-manager/IndexManager.h>
#include <document-manager/DocumentManager.h>
#include <aggregator-manager/SearchWorker.h>
#include <aggregator-manager/IndexWorker.h>
#include <product-manager/product_manager.h>
#include <product-manager/collection_product_data_source.h>
#include <product-manager/scd_operation_processor.h>
#include <product-manager/product_price_trend.h>
#include <product-manager/product_cron_job_handler.h>
#include <util/singleton.h>
#include <boost/filesystem.hpp>
#include <memory> // for auto_ptr
namespace bfs = boost::filesystem;
using namespace izenelib::util;
namespace sf1r
{
using namespace izenelib::osgi;
ProductBundleActivator::ProductBundleActivator()
: searchTracker_(0)
, taskTracker_(0)
, context_(0)
, searchService_(0)
, searchServiceReg_(0)
, taskService_(0)
, taskServiceReg_(0)
, refIndexTaskService_(0)
, config_(0)
, data_source_(0)
, op_processor_(0)
, price_trend_(0)
, scd_receiver_(0)
{
}
ProductBundleActivator::~ProductBundleActivator()
{
if (data_source_)
{
delete data_source_;
}
if (op_processor_)
{
delete op_processor_;
}
if (price_trend_)
{
delete price_trend_;
}
if (scd_receiver_)
{
delete scd_receiver_;
}
}
void ProductBundleActivator::start( IBundleContext::ConstPtr context )
{
context_ = context;
boost::shared_ptr<BundleConfiguration> bundleConfigPtr = context->getBundleConfig();
config_ = static_cast<ProductBundleConfiguration*>(bundleConfigPtr.get());
searchTracker_ = new ServiceTracker( context, "IndexSearchService", this );
searchTracker_->startTracking();
taskTracker_ = new ServiceTracker( context, "IndexTaskService", this );
taskTracker_->startTracking();
}
void ProductBundleActivator::stop( IBundleContext::ConstPtr context )
{
if(searchTracker_)
{
searchTracker_->stopTracking();
delete searchTracker_;
searchTracker_ = 0;
}
if(taskTracker_)
{
taskTracker_->stopTracking();
delete taskTracker_;
taskTracker_ = 0;
}
if(searchServiceReg_)
{
searchServiceReg_->unregister();
delete searchServiceReg_;
delete searchService_;
searchServiceReg_ = 0;
searchService_ = 0;
}
if(taskServiceReg_)
{
taskServiceReg_->unregister();
delete taskServiceReg_;
delete taskService_;
taskServiceReg_ = 0;
taskService_ = 0;
}
}
bool ProductBundleActivator::addingService( const ServiceReference& ref )
{
if ( ref.getServiceName() == "IndexSearchService" )
{
Properties props = ref.getServiceProperties();
if ( props.get( "collection" ) == config_->collectionName_)
{
IndexSearchService* service = reinterpret_cast<IndexSearchService*> ( const_cast<IService*>(ref.getService()) );
std::cout << "[ProductBundleActivator#addingService] Calling IndexSearchService..." << std::endl;
if(config_->mode_=="m" || config_->mode_=="o")//in m
{
productManager_ = createProductManager_(service);
searchService_ = new ProductSearchService(config_);
searchService_->productManager_ = productManager_;
if(refIndexTaskService_ )
{
addIndexHook_(refIndexTaskService_);
}
}
taskService_ = new ProductTaskService(config_);
searchServiceReg_ = context_->registerService( "ProductSearchService", searchService_, props );
taskServiceReg_ = context_->registerService( "ProductTaskService", taskService_, props );
return true;
}
else
{
return false;
}
}
else if( ref.getServiceName() == "IndexTaskService" )
{
Properties props = ref.getServiceProperties();
if ( props.get( "collection" ) == config_->collectionName_)
{
refIndexTaskService_ = reinterpret_cast<IndexTaskService*> ( const_cast<IService*>(ref.getService()) );
if(config_->mode_=="m" || config_->mode_=="o")//in m
{
if(productManager_)
{
addIndexHook_(refIndexTaskService_);
}
}
else if(config_->mode_=="a")//in a
{
LOG(INFO)<<"Scd Reciever init with id : "<<config_->productId_<<std::endl;
scd_receiver_ = new ProductScdReceiver(config_->productId_, config_->collectionName_, config_->callback_);
scd_receiver_->Set(refIndexTaskService_);
}
}
else
{
return false;
}
}
else
{
return false;
}
return true;
}
boost::shared_ptr<ProductManager>
ProductBundleActivator::createProductManager_(IndexSearchService* indexService)
{
std::cout<<"ProductBundleActivator::createProductManager_"<<std::endl;
openDataDirectories_();
std::string dir = getCurrentCollectionDataPath_()+"/product";
std::cout<<"product dir : "<<dir<<std::endl;
boost::filesystem::create_directories(dir);
std::string scd_dir = dir+"/scd";
boost::filesystem::create_directories(scd_dir);
data_source_ = new CollectionProductDataSource(indexService->searchWorker_->documentManager_,
indexService->searchWorker_->indexManager_,
indexService->searchWorker_->idManager_,
indexService->searchWorker_->searchManager_,
config_->pm_config_,
config_->indexSchema_);
LOG(INFO)<<"Scd Processor init with id : "<<config_->productId_<<std::endl;
op_processor_ = new ScdOperationProcessor(config_->productId_, config_->collectionName_, scd_dir);
if (config_->pm_config_.enable_price_trend)
{
price_trend_ = new ProductPriceTrend(config_->cassandraConfig_,
dir,
config_->pm_config_.group_property_names,
config_->pm_config_.time_interval_days);
ProductCronJobHandler* handler = ProductCronJobHandler::getInstance();
if (!handler->cronStart(config_->cron_))
{
std::cerr << "Init price trend cron task failed." << std::endl;
}
handler->addCollection(price_trend_);
}
std::string work_dir = dir+"/work_dir";
if(config_->mode_ == "m")
{
config_->pm_config_.enable_clustering_algo = true;
}
else if(config_->mode_ == "o")
{
config_->pm_config_.enable_clustering_algo = false;
}
boost::shared_ptr<ProductManager> product_manager(new ProductManager(work_dir,
indexService->searchWorker_->documentManager_,
data_source_,
op_processor_,
price_trend_,
config_->pm_config_));
return product_manager;
}
void ProductBundleActivator::addIndexHook_(IndexTaskService* indexService) const
{
indexService->indexWorker_->hooker_.reset(new ProductIndexHooker(productManager_));
}
void ProductBundleActivator::removedService( const ServiceReference& ref )
{
}
bool ProductBundleActivator::openDataDirectories_()
{
std::vector<std::string>& directories = config_->collectionDataDirectories_;
if( directories.size() == 0 )
{
LOG(ERROR)<<"no data dir config";
return false;
}
directoryRotator_.setCapacity(directories.size());
typedef std::vector<std::string>::const_iterator iterator;
for (iterator it = directories.begin(); it != directories.end(); ++it)
{
bfs::path dataDir = bfs::path( getCollectionDataPath_() ) / *it;
if (!directoryRotator_.appendDirectory(dataDir))
{
std::string msg = dataDir.string() + " corrupted, delete it!";
LOG(ERROR) << msg;
//clean the corrupt dir
boost::filesystem::remove_all( dataDir );
directoryRotator_.appendDirectory(dataDir);
}
}
directoryRotator_.rotateToNewest();
boost::shared_ptr<Directory> newest = directoryRotator_.currentDirectory();
if (newest)
{
bfs::path p = newest->path();
currentCollectionDataName_ = p.filename().string();
//std::cout << "Current Index Directory: " << indexPath_() << std::endl;
return true;
}
return false;
}
std::string ProductBundleActivator::getCurrentCollectionDataPath_() const
{
return config_->collPath_.getCollectionDataPath()+"/"+currentCollectionDataName_;
}
std::string ProductBundleActivator::getCollectionDataPath_() const
{
return config_->collPath_.getCollectionDataPath();
}
std::string ProductBundleActivator::getQueryDataPath_() const
{
return config_->collPath_.getQueryDataPath();
}
}
|
#include "ProductBundleActivator.h"
#include "ProductSearchService.h"
#include "ProductTaskService.h"
#include "ProductIndexHooker.h"
#include "ProductScdReceiver.h"
#include <bundles/index/IndexTaskService.h>
#include <bundles/index/IndexSearchService.h>
#include <common/SFLogger.h>
#include <index-manager/IndexManager.h>
#include <document-manager/DocumentManager.h>
#include <aggregator-manager/SearchWorker.h>
#include <aggregator-manager/IndexWorker.h>
#include <product-manager/product_manager.h>
#include <product-manager/collection_product_data_source.h>
#include <product-manager/scd_operation_processor.h>
#include <product-manager/product_price_trend.h>
#include <product-manager/product_cron_job_handler.h>
#include <util/singleton.h>
#include <boost/filesystem.hpp>
#include <memory> // for auto_ptr
namespace bfs = boost::filesystem;
using namespace izenelib::util;
namespace sf1r
{
using namespace izenelib::osgi;
ProductBundleActivator::ProductBundleActivator()
: searchTracker_(0)
, taskTracker_(0)
, context_(0)
, searchService_(0)
, searchServiceReg_(0)
, taskService_(0)
, taskServiceReg_(0)
, refIndexTaskService_(0)
, config_(0)
, data_source_(0)
, op_processor_(0)
, price_trend_(0)
, scd_receiver_(0)
{
}
ProductBundleActivator::~ProductBundleActivator()
{
if (data_source_)
{
delete data_source_;
}
if (op_processor_)
{
delete op_processor_;
}
if (price_trend_)
{
delete price_trend_;
}
if (scd_receiver_)
{
delete scd_receiver_;
}
}
void ProductBundleActivator::start( IBundleContext::ConstPtr context )
{
context_ = context;
boost::shared_ptr<BundleConfiguration> bundleConfigPtr = context->getBundleConfig();
config_ = static_cast<ProductBundleConfiguration*>(bundleConfigPtr.get());
searchTracker_ = new ServiceTracker( context, "IndexSearchService", this );
searchTracker_->startTracking();
taskTracker_ = new ServiceTracker( context, "IndexTaskService", this );
taskTracker_->startTracking();
}
void ProductBundleActivator::stop( IBundleContext::ConstPtr context )
{
if(searchTracker_)
{
searchTracker_->stopTracking();
delete searchTracker_;
searchTracker_ = 0;
}
if(taskTracker_)
{
taskTracker_->stopTracking();
delete taskTracker_;
taskTracker_ = 0;
}
if(searchServiceReg_)
{
searchServiceReg_->unregister();
delete searchServiceReg_;
delete searchService_;
searchServiceReg_ = 0;
searchService_ = 0;
}
if(taskServiceReg_)
{
taskServiceReg_->unregister();
delete taskServiceReg_;
delete taskService_;
taskServiceReg_ = 0;
taskService_ = 0;
}
}
bool ProductBundleActivator::addingService( const ServiceReference& ref )
{
if ( ref.getServiceName() == "IndexSearchService" )
{
Properties props = ref.getServiceProperties();
if ( props.get( "collection" ) == config_->collectionName_)
{
IndexSearchService* service = reinterpret_cast<IndexSearchService*> ( const_cast<IService*>(ref.getService()) );
std::cout << "[ProductBundleActivator#addingService] Calling IndexSearchService..." << std::endl;
if(config_->mode_=="m" || config_->mode_=="o")//in m
{
productManager_ = createProductManager_(service);
searchService_ = new ProductSearchService(config_);
searchService_->productManager_ = productManager_;
if(refIndexTaskService_ )
{
addIndexHook_(refIndexTaskService_);
}
}
taskService_ = new ProductTaskService(config_);
searchServiceReg_ = context_->registerService( "ProductSearchService", searchService_, props );
taskServiceReg_ = context_->registerService( "ProductTaskService", taskService_, props );
return true;
}
else
{
return false;
}
}
else if( ref.getServiceName() == "IndexTaskService" )
{
Properties props = ref.getServiceProperties();
if ( props.get( "collection" ) == config_->collectionName_)
{
refIndexTaskService_ = reinterpret_cast<IndexTaskService*> ( const_cast<IService*>(ref.getService()) );
if(config_->mode_=="m" || config_->mode_=="o")//in m
{
if(productManager_)
{
addIndexHook_(refIndexTaskService_);
}
}
else if(config_->mode_=="a")//in a
{
LOG(INFO)<<"Scd Reciever init with id : "<<config_->productId_<<std::endl;
scd_receiver_ = new ProductScdReceiver(config_->productId_, config_->collectionName_, config_->callback_);
scd_receiver_->Set(refIndexTaskService_);
}
}
else
{
return false;
}
}
else
{
return false;
}
return true;
}
boost::shared_ptr<ProductManager>
ProductBundleActivator::createProductManager_(IndexSearchService* indexService)
{
std::cout<<"ProductBundleActivator::createProductManager_"<<std::endl;
openDataDirectories_();
std::string dir = getCurrentCollectionDataPath_()+"/product";
std::cout<<"product dir : "<<dir<<std::endl;
boost::filesystem::create_directories(dir);
std::string scd_dir = config_->collPath_.getScdPath() +"/product_scd";
boost::filesystem::create_directories(scd_dir);
data_source_ = new CollectionProductDataSource(indexService->searchWorker_->documentManager_,
indexService->searchWorker_->indexManager_,
indexService->searchWorker_->idManager_,
indexService->searchWorker_->searchManager_,
config_->pm_config_,
config_->indexSchema_);
LOG(INFO)<<"Scd Processor init with id : "<<config_->productId_<<std::endl;
op_processor_ = new ScdOperationProcessor(config_->productId_, config_->collectionName_, scd_dir);
if (config_->pm_config_.enable_price_trend)
{
price_trend_ = new ProductPriceTrend(config_->cassandraConfig_,
dir,
config_->pm_config_.group_property_names,
config_->pm_config_.time_interval_days);
ProductCronJobHandler* handler = ProductCronJobHandler::getInstance();
if (!handler->cronStart(config_->cron_))
{
std::cerr << "Init price trend cron task failed." << std::endl;
}
handler->addCollection(price_trend_);
}
std::string work_dir = dir+"/work_dir";
if(config_->mode_ == "m")
{
config_->pm_config_.enable_clustering_algo = true;
}
else if(config_->mode_ == "o")
{
config_->pm_config_.enable_clustering_algo = false;
}
boost::shared_ptr<ProductManager> product_manager(new ProductManager(work_dir,
indexService->searchWorker_->documentManager_,
data_source_,
op_processor_,
price_trend_,
config_->pm_config_));
return product_manager;
}
void ProductBundleActivator::addIndexHook_(IndexTaskService* indexService) const
{
indexService->indexWorker_->hooker_.reset(new ProductIndexHooker(productManager_));
}
void ProductBundleActivator::removedService( const ServiceReference& ref )
{
}
bool ProductBundleActivator::openDataDirectories_()
{
std::vector<std::string>& directories = config_->collectionDataDirectories_;
if( directories.size() == 0 )
{
LOG(ERROR)<<"no data dir config";
return false;
}
directoryRotator_.setCapacity(directories.size());
typedef std::vector<std::string>::const_iterator iterator;
for (iterator it = directories.begin(); it != directories.end(); ++it)
{
bfs::path dataDir = bfs::path( getCollectionDataPath_() ) / *it;
if (!directoryRotator_.appendDirectory(dataDir))
{
std::string msg = dataDir.string() + " corrupted, delete it!";
LOG(ERROR) << msg;
//clean the corrupt dir
boost::filesystem::remove_all( dataDir );
directoryRotator_.appendDirectory(dataDir);
}
}
directoryRotator_.rotateToNewest();
boost::shared_ptr<Directory> newest = directoryRotator_.currentDirectory();
if (newest)
{
bfs::path p = newest->path();
currentCollectionDataName_ = p.filename().string();
//std::cout << "Current Index Directory: " << indexPath_() << std::endl;
return true;
}
return false;
}
std::string ProductBundleActivator::getCurrentCollectionDataPath_() const
{
return config_->collPath_.getCollectionDataPath()+"/"+currentCollectionDataName_;
}
std::string ProductBundleActivator::getCollectionDataPath_() const
{
return config_->collPath_.getCollectionDataPath();
}
std::string ProductBundleActivator::getQueryDataPath_() const
{
return config_->collPath_.getQueryDataPath();
}
}
|
move product scd files to scd directory
|
move product scd files to scd directory
|
C++
|
apache-2.0
|
izenecloud/sf1r-ad-delivery,pombredanne/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-ad-delivery,pombredanne/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-ad-delivery
|
3b9e0e3aaf508bfe45307eb129912b6bdc09b576
|
ui/test/vcframe/vcframe_test.cpp
|
ui/test/vcframe/vcframe_test.cpp
|
/*
Q Light Controller Plus - Test Unit
vcframe_test.cpp
Copyright (C) Heikki Junnila
Massimo Callegari
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 <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QFrame>
#include <QtTest>
#include <QMenu>
#include <QSet>
#define protected public
#include "qlcfixturedefcache.h"
#include "virtualconsole.h"
#include "vcframe_test.h"
#include "mastertimer.h"
#include "vcbutton.h"
#include "vcwidget.h"
#include "vcframe.h"
#include "vcframe.h"
#include "doc.h"
#undef protected
void VCFrame_Test::initTestCase()
{
m_doc = NULL;
}
void VCFrame_Test::init()
{
m_doc = new Doc(this);
new VirtualConsole(NULL, m_doc);
}
void VCFrame_Test::cleanup()
{
delete VirtualConsole::instance();
delete m_doc;
}
void VCFrame_Test::initial()
{
QWidget w;
VCFrame frame(&w, m_doc);
QCOMPARE(frame.objectName(), QString("VCFrame"));
QCOMPARE(frame.frameStyle(), QFrame::Panel | QFrame::Sunken);
}
void VCFrame_Test::copy()
{
QWidget w;
VCFrame parent(&w, m_doc);
VCFrame frame(&parent, m_doc);
VCButton* btn = new VCButton(&frame, m_doc);
btn->setCaption("Foobar");
VCWidget* frame2 = frame.createCopy(&parent);
QVERIFY(frame2 != NULL && frame2 != &frame);
QCOMPARE(frame2->objectName(), QString("VCFrame"));
QCOMPARE(frame2->parentWidget(), &parent);
// Also children should get copied
QList <VCButton*> list = frame2->findChildren<VCButton*>();
QCOMPARE(list.size(), 1);
QCOMPARE(list[0]->caption(), QString("Foobar"));
QVERIFY(frame.copyFrom(NULL) == false);
}
void VCFrame_Test::loadXML()
{
QWidget w;
QBuffer buffer;
buffer.open(QIODevice::ReadWrite | QIODevice::Text);
QXmlStreamWriter xmlWriter(&buffer);
xmlWriter.writeStartElement("Frame");
xmlWriter.writeStartElement("WindowState");
xmlWriter.writeAttribute("Width", "42");
xmlWriter.writeAttribute("Height", "69");
xmlWriter.writeAttribute("X", "3");
xmlWriter.writeAttribute("Y", "4");
xmlWriter.writeAttribute("Visible", "True");
xmlWriter.writeEndElement();
xmlWriter.writeTextElement("AllowChildren", "False");
xmlWriter.writeTextElement("AllowResize", "False");
xmlWriter.writeStartElement("Frame");
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("Label");
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("Button");
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("XYPad");
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("Slider");
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("SoloFrame");
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("CueList");
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("Foobar");
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
xmlWriter.setDevice(NULL);
buffer.seek(0);
QXmlStreamReader xmlReader(&buffer);
xmlReader.readNextStartElement();
VCFrame parent(&w, m_doc);
QVERIFY(parent.loadXML(xmlReader) == true);
parent.postLoad();
QCOMPARE(parent.geometry().width(), 42);
QCOMPARE(parent.geometry().height(), 69);
QCOMPARE(parent.geometry().x(), 3);
QCOMPARE(parent.geometry().y(), 4);
QVERIFY(parent.allowChildren() == false);
QVERIFY(parent.allowResize() == false);
QSet <QString> childSet;
QCOMPARE(parent.children().size(), 7);
foreach (QObject* child, parent.children())
childSet << child->metaObject()->className();
QVERIFY(childSet.contains("VCFrame"));
QVERIFY(childSet.contains("VCLabel"));
QVERIFY(childSet.contains("VCButton"));
QVERIFY(childSet.contains("VCXYPad"));
QVERIFY(childSet.contains("VCSlider"));
QVERIFY(childSet.contains("VCSoloFrame"));
QVERIFY(childSet.contains("VCCueList"));
buffer.close();
QByteArray bData = buffer.data();
bData.replace("<Frame", "<Farme");
buffer.setData(bData);
buffer.open(QIODevice::ReadOnly | QIODevice::Text);
buffer.seek(0);
xmlReader.setDevice(&buffer);
xmlReader.readNextStartElement();
QVERIFY(parent.loadXML(xmlReader) == false);
}
void VCFrame_Test::saveXML()
{
QWidget w;
VCFrame parent(&w, m_doc);
parent.setCaption("Parent");
VCFrame child(&parent, m_doc);
child.setCaption("Child");
VCFrame grandChild(&child, m_doc);
grandChild.setCaption("Grandchild");
child.setAllowChildren(false);
child.setAllowResize(false);
QBuffer buffer;
buffer.open(QIODevice::WriteOnly | QIODevice::Text);
QXmlStreamWriter xmlWriter(&buffer);
QVERIFY(parent.saveXML(&xmlWriter) == true);
xmlWriter.setDevice(NULL);
buffer.close();
buffer.open(QIODevice::ReadOnly | QIODevice::Text);
QXmlStreamReader xmlReader(&buffer);
QVERIFY(xmlReader.readNextStartElement() == true);
QCOMPARE(xmlReader.name().toString(), QString("Frame"));
int appearance = 0, windowstate = 0, frame = 0, allowChildren = 0, allowResize = 0;
int collapsed = 0, showheader = 0, disabled = 0, enableInput = 0, showEnableButton = 0;
//qDebug() << "Buffer:" << buffer.data();
// Parent
while (xmlReader.readNextStartElement())
{
if (xmlReader.name() == QString("Appearance"))
{
appearance++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("WindowState"))
{
windowstate++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("Frame"))
{
frame++;
QCOMPARE(appearance, 1);
QCOMPARE(windowstate, 0);
QCOMPARE(collapsed, 0);
QCOMPARE(frame, 1);
// Child
while (xmlReader.readNextStartElement())
{
if (xmlReader.name() == QString("Appearance"))
{
appearance++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("WindowState"))
{
windowstate++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("AllowChildren"))
{
allowChildren++;
QCOMPARE(xmlReader.readElementText(), QString("False"));
}
else if (xmlReader.name() == QString("AllowResize"))
{
allowResize++;
QCOMPARE(xmlReader.readElementText(), QString("False"));
}
else if (xmlReader.name() == QString("Collapsed"))
{
collapsed++;
QCOMPARE(xmlReader.readElementText(), QString("False"));
}
else if (xmlReader.name() == QString("ShowHeader"))
{
showheader++;
QCOMPARE(xmlReader.readElementText(), QString("True"));
}
else if (xmlReader.name() == QString("ShowEnableButton"))
{
showEnableButton++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("Disabled"))
{
disabled++;
QCOMPARE(xmlReader.readElementText(), QString("False"));
}
else if (xmlReader.name() == QString("Enable"))
{
enableInput++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("Frame"))
{
frame++;
QCOMPARE(appearance, 2);
QCOMPARE(windowstate, 1);
QCOMPARE(allowChildren, 1);
QCOMPARE(allowResize, 1);
QCOMPARE(collapsed, 1);
QCOMPARE(showheader, 1);
QCOMPARE(disabled, 1);
QCOMPARE(frame, 2);
// Grandchild
while (xmlReader.readNextStartElement())
{
if (xmlReader.name() == QString("Appearance"))
{
appearance++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("WindowState"))
{
windowstate++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("AllowChildren"))
{
allowChildren++;
QCOMPARE(xmlReader.readElementText(), QString("True"));
}
else if (xmlReader.name() == QString("AllowResize"))
{
allowResize++;
QCOMPARE(xmlReader.readElementText(), QString("True"));
}
else if (xmlReader.name() == QString("Collapsed"))
{
collapsed++;
QCOMPARE(xmlReader.readElementText(), QString("False"));
}
else if (xmlReader.name() == QString("ShowHeader"))
{
showheader++;
QCOMPARE(xmlReader.readElementText(), QString("True"));
}
else if (xmlReader.name() == QString("Disabled"))
{
disabled++;
QCOMPARE(xmlReader.readElementText(), QString("False"));
}
else if (xmlReader.name() == QString("Enable"))
{
enableInput++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("ShowEnableButton"))
{
showEnableButton++;
xmlReader.skipCurrentElement();
}
else
{
QFAIL(QString("Unexpected tag: %1").arg(xmlReader.name().toString()).toUtf8().constData());
}
}
}
}
}
else if (xmlReader.name() == QString("Collapsed"))
{
collapsed++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("Disabled"))
{
disabled++;
QCOMPARE(xmlReader.readElementText(), QString("False"));
}
else if (xmlReader.name() == QString("Enable"))
{
enableInput++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("ShowHeader"))
{
showheader++;
xmlReader.skipCurrentElement();
}
else
{
QFAIL(QString("Unexpected tag: %1").arg(xmlReader.name().toString()).toUtf8().constData());
}
}
QCOMPARE(appearance, 3);
QCOMPARE(windowstate, 2);
QCOMPARE(collapsed, 2);
QCOMPARE(showheader, 2);
QCOMPARE(disabled, 2);
QCOMPARE(enableInput, 2);
QCOMPARE(showEnableButton, 2);
QCOMPARE(frame, 2);
}
void VCFrame_Test::customMenu()
{
VCFrame* frame = VirtualConsole::instance()->contents();
QVERIFY(frame != NULL);
QMenu menu;
QMenu* customMenu = frame->customMenu(&menu);
QVERIFY(customMenu != NULL);
QCOMPARE(customMenu->title(), tr("Add"));
delete customMenu;
}
void VCFrame_Test::handleWidgetSelection()
{
VCFrame* frame = VirtualConsole::instance()->contents();
QVERIFY(frame->isBottomFrame() == true);
QMouseEvent ev(QEvent::MouseButtonPress, QPoint(0, 0), Qt::LeftButton,
Qt::LeftButton, Qt::NoModifier);
frame->handleWidgetSelection(&ev);
// Select bottom frame (->no selection)
frame->handleWidgetSelection(&ev);
QCOMPARE(VirtualConsole::instance()->selectedWidgets().size(), 0);
// Select a child frame
VCFrame* child = new VCFrame(frame, m_doc);
QVERIFY(child->isBottomFrame() == false);
child->handleWidgetSelection(&ev);
QCOMPARE(VirtualConsole::instance()->selectedWidgets().size(), 1);
// Again select bottom frame
frame->handleWidgetSelection(&ev);
QCOMPARE(VirtualConsole::instance()->selectedWidgets().size(), 0);
}
void VCFrame_Test::mouseMoveEvent()
{
// Well, there isn't much that can be checked here... Actual moving happens in VCWidget.
QMouseEvent ev(QEvent::MouseButtonPress, QPoint(0, 0), Qt::LeftButton,
Qt::LeftButton, Qt::NoModifier);
QWidget w;
VCFrame frame(&w, m_doc);
QVERIFY(frame.isBottomFrame() == true);
frame.move(QPoint(0, 0));
frame.mouseMoveEvent(&ev);
QCOMPARE(frame.pos(), QPoint(0, 0));
VCFrame child(&frame, m_doc);
QVERIFY(child.isBottomFrame() == false);
child.mouseMoveEvent(&ev);
QCOMPARE(child.pos(), QPoint(0, 0));
}
QTEST_MAIN(VCFrame_Test)
|
/*
Q Light Controller Plus - Test Unit
vcframe_test.cpp
Copyright (C) Heikki Junnila
Massimo Callegari
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 <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QFrame>
#include <QtTest>
#include <QMenu>
#include <QSet>
#define protected public
#include "qlcfixturedefcache.h"
#include "virtualconsole.h"
#include "vcframe_test.h"
#include "mastertimer.h"
#include "vcbutton.h"
#include "vcwidget.h"
#include "vcframe.h"
#include "vcframe.h"
#include "doc.h"
#undef protected
void VCFrame_Test::initTestCase()
{
m_doc = NULL;
}
void VCFrame_Test::init()
{
m_doc = new Doc(this);
new VirtualConsole(NULL, m_doc);
}
void VCFrame_Test::cleanup()
{
delete VirtualConsole::instance();
delete m_doc;
}
void VCFrame_Test::initial()
{
QWidget w;
VCFrame frame(&w, m_doc);
QCOMPARE(frame.objectName(), QString("VCFrame"));
QCOMPARE(frame.frameStyle(), QFrame::Panel | QFrame::Sunken);
}
void VCFrame_Test::copy()
{
QWidget w;
VCFrame parent(&w, m_doc);
VCFrame frame(&parent, m_doc);
VCButton* btn = new VCButton(&frame, m_doc);
btn->setCaption("Foobar");
VCWidget* frame2 = frame.createCopy(&parent);
QVERIFY(frame2 != NULL && frame2 != &frame);
QCOMPARE(frame2->objectName(), QString("VCFrame"));
QCOMPARE(frame2->parentWidget(), &parent);
// Also children should get copied
QList <VCButton*> list = frame2->findChildren<VCButton*>();
QCOMPARE(list.size(), 1);
QCOMPARE(list[0]->caption(), QString("Foobar"));
QVERIFY(frame.copyFrom(NULL) == false);
}
void VCFrame_Test::loadXML()
{
QWidget w;
QBuffer buffer;
buffer.open(QIODevice::ReadWrite | QIODevice::Text);
QXmlStreamWriter xmlWriter(&buffer);
xmlWriter.writeStartElement("Frame");
xmlWriter.writeStartElement("WindowState");
xmlWriter.writeAttribute("Width", "42");
xmlWriter.writeAttribute("Height", "69");
xmlWriter.writeAttribute("X", "3");
xmlWriter.writeAttribute("Y", "4");
xmlWriter.writeAttribute("Visible", "True");
xmlWriter.writeEndElement();
xmlWriter.writeTextElement("AllowChildren", "False");
xmlWriter.writeTextElement("AllowResize", "False");
xmlWriter.writeStartElement("Frame");
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("Label");
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("Button");
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("XYPad");
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("Slider");
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("SoloFrame");
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("CueList");
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("Foobar");
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
xmlWriter.setDevice(NULL);
buffer.seek(0);
QXmlStreamReader xmlReader(&buffer);
xmlReader.readNextStartElement();
VCFrame parent(&w, m_doc);
QVERIFY(parent.loadXML(xmlReader) == true);
parent.postLoad();
QCOMPARE(parent.geometry().width(), 42);
QCOMPARE(parent.geometry().height(), 69);
QCOMPARE(parent.geometry().x(), 3);
QCOMPARE(parent.geometry().y(), 4);
QVERIFY(parent.allowChildren() == false);
QVERIFY(parent.allowResize() == false);
QSet <QString> childSet;
QCOMPARE(parent.children().size(), 7);
foreach (QObject* child, parent.children())
childSet << child->metaObject()->className();
QVERIFY(childSet.contains("VCFrame"));
QVERIFY(childSet.contains("VCLabel"));
QVERIFY(childSet.contains("VCButton"));
QVERIFY(childSet.contains("VCXYPad"));
QVERIFY(childSet.contains("VCSlider"));
QVERIFY(childSet.contains("VCSoloFrame"));
QVERIFY(childSet.contains("VCCueList"));
buffer.close();
QByteArray bData = buffer.data();
bData.replace("<Frame", "<Farme");
buffer.setData(bData);
buffer.open(QIODevice::ReadOnly | QIODevice::Text);
buffer.seek(0);
xmlReader.setDevice(&buffer);
xmlReader.readNextStartElement();
QVERIFY(parent.loadXML(xmlReader) == false);
}
void VCFrame_Test::saveXML()
{
QWidget w;
VCFrame parent(&w, m_doc);
parent.setCaption("Parent");
VCFrame child(&parent, m_doc);
child.setCaption("Child");
VCFrame grandChild(&child, m_doc);
grandChild.setCaption("Grandchild");
child.setAllowChildren(false);
child.setAllowResize(false);
QBuffer buffer;
buffer.open(QIODevice::WriteOnly | QIODevice::Text);
QXmlStreamWriter xmlWriter(&buffer);
QVERIFY(parent.saveXML(&xmlWriter) == true);
xmlWriter.setDevice(NULL);
buffer.close();
buffer.open(QIODevice::ReadOnly | QIODevice::Text);
QXmlStreamReader xmlReader(&buffer);
QVERIFY(xmlReader.readNextStartElement() == true);
QCOMPARE(xmlReader.name().toString(), QString("Frame"));
int appearance = 0, windowstate = 0, frame = 0, allowChildren = 0, allowResize = 0;
int collapsed = 0, showheader = 0, disabled = 0, enableInput = 0, showEnableButton = 0;
//qDebug() << "Buffer:" << buffer.data();
// Parent
while (xmlReader.readNextStartElement())
{
if (xmlReader.name() == QString("Appearance"))
{
appearance++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("WindowState"))
{
windowstate++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("Frame"))
{
frame++;
QCOMPARE(appearance, 1);
QCOMPARE(windowstate, 0);
QCOMPARE(collapsed, 0);
QCOMPARE(frame, 1);
// Child
while (xmlReader.readNextStartElement())
{
if (xmlReader.name() == QString("Appearance"))
{
appearance++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("WindowState"))
{
windowstate++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("AllowChildren"))
{
allowChildren++;
QCOMPARE(xmlReader.readElementText(), QString("False"));
}
else if (xmlReader.name() == QString("AllowResize"))
{
allowResize++;
QCOMPARE(xmlReader.readElementText(), QString("False"));
}
else if (xmlReader.name() == QString("Collapsed"))
{
collapsed++;
QCOMPARE(xmlReader.readElementText(), QString("False"));
}
else if (xmlReader.name() == QString("ShowHeader"))
{
showheader++;
QCOMPARE(xmlReader.readElementText(), QString("True"));
}
else if (xmlReader.name() == QString("ShowEnableButton"))
{
showEnableButton++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("Disabled"))
{
disabled++;
QCOMPARE(xmlReader.readElementText(), QString("False"));
}
else if (xmlReader.name() == QString("Enable"))
{
enableInput++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("Frame"))
{
frame++;
QCOMPARE(appearance, 2);
QCOMPARE(windowstate, 1);
QCOMPARE(allowChildren, 1);
QCOMPARE(allowResize, 1);
QCOMPARE(collapsed, 1);
QCOMPARE(showheader, 1);
QCOMPARE(disabled, 1);
QCOMPARE(frame, 2);
// Grandchild
while (xmlReader.readNextStartElement())
{
if (xmlReader.name() == QString("Appearance"))
{
appearance++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("WindowState"))
{
windowstate++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("AllowChildren"))
{
allowChildren++;
QCOMPARE(xmlReader.readElementText(), QString("True"));
}
else if (xmlReader.name() == QString("AllowResize"))
{
allowResize++;
QCOMPARE(xmlReader.readElementText(), QString("True"));
}
else if (xmlReader.name() == QString("Collapsed"))
{
collapsed++;
QCOMPARE(xmlReader.readElementText(), QString("False"));
}
else if (xmlReader.name() == QString("ShowHeader"))
{
showheader++;
QCOMPARE(xmlReader.readElementText(), QString("True"));
}
else if (xmlReader.name() == QString("Disabled"))
{
disabled++;
QCOMPARE(xmlReader.readElementText(), QString("False"));
}
else if (xmlReader.name() == QString("Enable"))
{
enableInput++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("ShowEnableButton"))
{
showEnableButton++;
xmlReader.skipCurrentElement();
}
else
{
QFAIL(QString("Unexpected tag: %1").arg(xmlReader.name().toString()).toUtf8().constData());
}
}
}
}
}
else if (xmlReader.name() == QString("Collapsed"))
{
collapsed++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("Disabled"))
{
disabled++;
QCOMPARE(xmlReader.readElementText(), QString("False"));
}
else if (xmlReader.name() == QString("Enable"))
{
enableInput++;
xmlReader.skipCurrentElement();
}
else if (xmlReader.name() == QString("ShowHeader"))
{
showheader++;
xmlReader.skipCurrentElement();
}
else
{
QFAIL(QString("Unexpected tag: %1").arg(xmlReader.name().toString()).toUtf8().constData());
}
}
QCOMPARE(appearance, 3);
QCOMPARE(windowstate, 2);
QCOMPARE(collapsed, 2);
QCOMPARE(showheader, 2);
QCOMPARE(disabled, 2);
QCOMPARE(enableInput, 0);
QCOMPARE(showEnableButton, 2);
QCOMPARE(frame, 2);
}
void VCFrame_Test::customMenu()
{
VCFrame* frame = VirtualConsole::instance()->contents();
QVERIFY(frame != NULL);
QMenu menu;
QMenu* customMenu = frame->customMenu(&menu);
QVERIFY(customMenu != NULL);
QCOMPARE(customMenu->title(), tr("Add"));
delete customMenu;
}
void VCFrame_Test::handleWidgetSelection()
{
VCFrame* frame = VirtualConsole::instance()->contents();
QVERIFY(frame->isBottomFrame() == true);
QMouseEvent ev(QEvent::MouseButtonPress, QPoint(0, 0), Qt::LeftButton,
Qt::LeftButton, Qt::NoModifier);
frame->handleWidgetSelection(&ev);
// Select bottom frame (->no selection)
frame->handleWidgetSelection(&ev);
QCOMPARE(VirtualConsole::instance()->selectedWidgets().size(), 0);
// Select a child frame
VCFrame* child = new VCFrame(frame, m_doc);
QVERIFY(child->isBottomFrame() == false);
child->handleWidgetSelection(&ev);
QCOMPARE(VirtualConsole::instance()->selectedWidgets().size(), 1);
// Again select bottom frame
frame->handleWidgetSelection(&ev);
QCOMPARE(VirtualConsole::instance()->selectedWidgets().size(), 0);
}
void VCFrame_Test::mouseMoveEvent()
{
// Well, there isn't much that can be checked here... Actual moving happens in VCWidget.
QMouseEvent ev(QEvent::MouseButtonPress, QPoint(0, 0), Qt::LeftButton,
Qt::LeftButton, Qt::NoModifier);
QWidget w;
VCFrame frame(&w, m_doc);
QVERIFY(frame.isBottomFrame() == true);
frame.move(QPoint(0, 0));
frame.mouseMoveEvent(&ev);
QCOMPARE(frame.pos(), QPoint(0, 0));
VCFrame child(&frame, m_doc);
QVERIFY(child.isBottomFrame() == false);
child.mouseMoveEvent(&ev);
QCOMPARE(child.pos(), QPoint(0, 0));
}
QTEST_MAIN(VCFrame_Test)
|
Fix VCFrame test unit
|
Fix VCFrame test unit
|
C++
|
apache-2.0
|
mcallegari/qlcplus,kripton/qlcplus,mcallegari/qlcplus,nedmech/qlcplus,mcallegari/qlcplus,kripton/qlcplus,mcallegari/qlcplus,mcallegari/qlcplus,plugz/qlcplus,plugz/qlcplus,kripton/qlcplus,nedmech/qlcplus,plugz/qlcplus,nedmech/qlcplus,sbenejam/qlcplus,mcallegari/qlcplus,kripton/qlcplus,plugz/qlcplus,nedmech/qlcplus,nedmech/qlcplus,sbenejam/qlcplus,kripton/qlcplus,plugz/qlcplus,sbenejam/qlcplus,sbenejam/qlcplus,nedmech/qlcplus,sbenejam/qlcplus,kripton/qlcplus,plugz/qlcplus,kripton/qlcplus,plugz/qlcplus,sbenejam/qlcplus,sbenejam/qlcplus,mcallegari/qlcplus
|
81586d86e1be1ace0c180c79c2010c1f5ce6a1dd
|
test/test_server.cpp
|
test/test_server.cpp
|
#include <MediaServerService.h>
#include <MediaSessionService.h>
#include <NetworkConnectionService.h>
#include <thrift/config.h>
#include <thrift/transport/TSocket.h>
// #include <thrift/transport/TBufferTransports.h>
#include <thrift/protocol/TBinaryProtocol.h>
// #include <thrift/protocol/TDebugProtocol.h>
#include <boost/concept_check.hpp>
#include <gst/gst.h>
#include <sstream>
using ::com::kurento::kms::api::MediaSessionServiceClient;
using ::com::kurento::kms::api::MediaServerServiceClient;
using ::com::kurento::kms::api::MediaSession;
using ::com::kurento::kms::api::ServerConfig;
using ::com::kurento::kms::api::NetworkConnection;
using ::com::kurento::kms::api::NetworkConnectionConfig;
using ::com::kurento::kms::api::NetworkConnectionServiceClient;
using ::com::kurento::kms::api::StreamType;
using ::com::kurento::commons::mediaspec::SessionSpec;
using ::com::kurento::commons::mediaspec::MediaSpec;
using ::com::kurento::commons::mediaspec::Payload;
using ::com::kurento::commons::mediaspec::Direction;
using ::com::kurento::commons::mediaspec::MediaType;
using ::apache::thrift::protocol::TBinaryProtocol;
// using ::apache::thrift::protocol::TDebugProtocol;
using ::apache::thrift::transport::TSocket;
// using ::apache::thrift::transport::TMemoryBuffer;
#define DEFAULT_PORT 5050
#define LOCAL_ADDRESS "193.147.51.16"
static void
send_receive_media(SessionSpec &spec) {
MediaSpec media = *(spec.medias.begin());
Payload pay = *(media.payloads.begin());
std::stringstream stream;
if (media.direction == Direction::SENDONLY) {
std::cout << "Sendonly" << std::endl;
std::cout << "Port: " << media.transport.rtp.port << std::endl;
std::cout << "Codec name: " << pay.rtp.codecName << std::endl;
stream << "autovideosrc ! "
"video/x-raw-yuv,framerate=30/1,width=352 ! "
"ffenc_h263 ! rtph263ppay ! "
"application/x-rtp,media=video,clock-rate=(int)" <<
pay.rtp.clockRate << ",encoding-name=(string)H263-1998,"
"payload=(int)" << pay.rtp.id << " ! udpsink port=" <<
media.transport.rtp.port << " host=" <<
media.transport.rtp.address;
} else if (media.direction == Direction::RECVONLY) {
std::cout << "recvonly" << std::endl;
std::cout << "Port: " << DEFAULT_PORT << std::endl;
std::cout << "Codec name: " << pay.rtp.codecName << std::endl;
stream << "udpsrc port=" << DEFAULT_PORT <<
" ! application/x-rtp,encoding-name=" <<
pay.rtp.codecName << ",clock-rate=" <<
pay.rtp.clockRate << ",payload=" <<
pay.rtp.id << " ! rtpmp4vdepay ! ffdec_mpeg4 ! "
"autovideosink";
}
GstElement *pipe;
GError *err = NULL;
std::string pipe_str = stream.str();
std::cout << pipe_str << std::endl;
pipe = gst_parse_launch(pipe_str.c_str(), &err);
if (err != NULL) {
std::cout << "Error: " << err->message << std::endl;
g_error_free(err);
err = NULL;
} else if (pipe == NULL) {
std::cout << "Cannot create pipe" << std::endl;
} else {
gst_element_set_state(pipe, GST_STATE_PLAYING);
}
std::cout << "---" << std::endl;
}
static void
print_session_spec(SessionSpec &spec) {
// boost::shared_ptr<TMemoryBuffer> buffer(new TMemoryBuffer());
// TDebugProtocol proto(buffer);
// spec.write(&proto);
//
// std::cout << buffer->getBufferAsString() << std::endl;
}
static void
create_session_spec(SessionSpec &spec) {
Payload pay;
pay.__isset.rtp = true;
pay.rtp.codecName = "MP4V-ES";
pay.rtp.id = 96;
pay.rtp.clockRate = 90000;
MediaSpec ms;
ms.transport.rtp.address = LOCAL_ADDRESS;
ms.transport.rtp.port = DEFAULT_PORT;
ms.transport.__isset.rtp = true;
ms.direction = Direction::type::SENDONLY;
ms.type.insert(MediaType::VIDEO);
ms.payloads.push_back(pay);
spec.id = "1234";
spec.medias.push_back(ms);
}
static void
create_second_session_spec(SessionSpec &spec) {
Payload pay;
pay.__isset.rtp = true;
pay.rtp.codecName = "H263-1998";
pay.rtp.id = 96;
pay.rtp.clockRate = 90000;
MediaSpec ms;
ms.transport.rtp.address = LOCAL_ADDRESS;
ms.transport.rtp.port = DEFAULT_PORT;
ms.transport.__isset.rtp = true;
ms.direction = Direction::type::RECVONLY;
ms.type.insert(MediaType::VIDEO);
ms.payloads.push_back(pay);
spec.id = "1234";
spec.medias.push_back(ms);
}
static void
create_newtork_connection(NetworkConnection &_nc, ServerConfig &mc, MediaSession &ms) {
if (!mc.__isset.mediaSessionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.mediaSessionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
MediaSessionServiceClient mservice(prot);
transport->open();
std::vector<NetworkConnectionConfig::type> config;
config.push_back(NetworkConnectionConfig::type::RTP);
mservice.createNetworkConnection(_nc, ms, config);
}
static void
negotiate_connection(ServerConfig &mc, NetworkConnection& nc, SessionSpec& spec) {
if (!mc.__isset.networkConnectionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.networkConnectionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
NetworkConnectionServiceClient service(prot);
transport->open();
SessionSpec reply;
service.processOffer(reply, nc, spec);
print_session_spec(reply);
send_receive_media(reply);
}
static void
join_network_connections(ServerConfig &mc, NetworkConnection& nc,
NetworkConnection& nc2) {
if (!mc.__isset.networkConnectionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.networkConnectionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
NetworkConnectionServiceClient service(prot);
transport->open();
service.joinStream(nc.joinable, nc2.joinable, StreamType::type::VIDEO,
Direction::SENDRECV);
}
static void
ping_media_session(ServerConfig &mc, MediaSession& ms, int iter, int interval) {
if (!mc.__isset.mediaSessionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.mediaSessionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
MediaSessionServiceClient service(prot);
transport->open();
for (; iter > 0; iter--) {
service.ping(ms, interval + 1);
sleep(interval);
}
}
static void
start_client() {
boost::shared_ptr<TSocket> transport(new TSocket("localhost", 9090));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
MediaServerServiceClient mservice(prot);
transport->open();
ServerConfig mc;
MediaSession ms;
NetworkConnection nc, nc2;
SessionSpec spec;
SessionSpec spec2;
mservice.getServerconfig(mc);
mservice.createMediaSession(ms);
std::cout << "Session id: " << ms.object.id << std::endl;
create_newtork_connection(nc, mc, ms);
std::cout << "NetworkConnection: " << nc.joinable.object.id << std::endl;
create_session_spec(spec);
negotiate_connection(mc, nc, spec);
create_newtork_connection(nc2, mc, ms);
std::cout << "NetworkConnection: " << nc2.joinable.object.id << std::endl;
create_second_session_spec(spec2);
negotiate_connection(mc, nc2, spec2);
join_network_connections(mc, nc, nc2);
ping_media_session(mc, ms, 4, 30);
mservice.deleteMediaSession(ms);
}
int
main(int argc, char **argv) {
gst_init(&argc, &argv);
// TODO: Evaluate if server should be launched here
start_client();
}
|
#include <MediaServerService.h>
#include <MediaSessionService.h>
#include <NetworkConnectionService.h>
#include <thrift/config.h>
#include <thrift/transport/TSocket.h>
// #include <thrift/transport/TBufferTransports.h>
#include <thrift/protocol/TBinaryProtocol.h>
// #include <thrift/protocol/TDebugProtocol.h>
#include <boost/concept_check.hpp>
#include <gst/gst.h>
#include <sstream>
using ::com::kurento::kms::api::MediaSessionServiceClient;
using ::com::kurento::kms::api::MediaServerServiceClient;
using ::com::kurento::kms::api::MediaSession;
using ::com::kurento::kms::api::ServerConfig;
using ::com::kurento::kms::api::NetworkConnection;
using ::com::kurento::kms::api::NetworkConnectionConfig;
using ::com::kurento::kms::api::NetworkConnectionServiceClient;
using ::com::kurento::kms::api::StreamType;
using ::com::kurento::commons::mediaspec::SessionSpec;
using ::com::kurento::commons::mediaspec::MediaSpec;
using ::com::kurento::commons::mediaspec::Payload;
using ::com::kurento::commons::mediaspec::Direction;
using ::com::kurento::commons::mediaspec::MediaType;
using ::apache::thrift::protocol::TBinaryProtocol;
// using ::apache::thrift::protocol::TDebugProtocol;
using ::apache::thrift::transport::TSocket;
// using ::apache::thrift::transport::TMemoryBuffer;
#define DEFAULT_PORT 5050
#define LOCAL_ADDRESS "193.147.51.16"
static void
send_receive_media(SessionSpec &spec) {
MediaSpec media = *(spec.medias.begin());
Payload pay = *(media.payloads.begin());
std::stringstream stream;
if (media.direction == Direction::RECVONLY) {
std::cout << "server recvonly" << std::endl;
std::cout << "Port: " << media.transport.rtp.port << std::endl;
std::cout << "Codec name: " << pay.rtp.codecName << std::endl;
stream << "autovideosrc ! "
"video/x-raw-yuv,framerate=30/1,width=352 ! "
"ffenc_h263 ! rtph263ppay ! "
"application/x-rtp,media=video,clock-rate=(int)" <<
pay.rtp.clockRate << ",encoding-name=(string)H263-1998,"
"payload=(int)" << pay.rtp.id << " ! udpsink port=" <<
media.transport.rtp.port << " host=" <<
media.transport.rtp.address;
} else if (media.direction == Direction::SENDONLY) {
std::cout << "server sendonly" << std::endl;
std::cout << "Port: " << DEFAULT_PORT << std::endl;
std::cout << "Codec name: " << pay.rtp.codecName << std::endl;
stream << "udpsrc port=" << DEFAULT_PORT <<
" ! application/x-rtp,encoding-name=" <<
pay.rtp.codecName << ",clock-rate=" <<
pay.rtp.clockRate << ",payload=" <<
pay.rtp.id << " ! rtpmp4vdepay ! ffdec_mpeg4 ! "
"autovideosink";
}
GstElement *pipe;
GError *err = NULL;
std::string pipe_str = stream.str();
std::cout << pipe_str << std::endl;
pipe = gst_parse_launch(pipe_str.c_str(), &err);
if (err != NULL) {
std::cout << "Error: " << err->message << std::endl;
g_error_free(err);
err = NULL;
} else if (pipe == NULL) {
std::cout << "Cannot create pipe" << std::endl;
} else {
gst_element_set_state(pipe, GST_STATE_PLAYING);
}
std::cout << "---" << std::endl;
}
static void
print_session_spec(SessionSpec &spec) {
// boost::shared_ptr<TMemoryBuffer> buffer(new TMemoryBuffer());
// TDebugProtocol proto(buffer);
// spec.write(&proto);
//
// std::cout << buffer->getBufferAsString() << std::endl;
}
static void
create_session_spec(SessionSpec &spec) {
Payload pay;
pay.__isset.rtp = true;
pay.rtp.codecName = "MP4V-ES";
pay.rtp.id = 96;
pay.rtp.clockRate = 90000;
MediaSpec ms;
ms.transport.rtp.address = LOCAL_ADDRESS;
ms.transport.rtp.port = DEFAULT_PORT;
ms.transport.__isset.rtp = true;
ms.direction = Direction::type::RECVONLY;
ms.type.insert(MediaType::VIDEO);
ms.payloads.push_back(pay);
spec.id = "1234";
spec.medias.push_back(ms);
}
static void
create_second_session_spec(SessionSpec &spec) {
Payload pay;
pay.__isset.rtp = true;
pay.rtp.codecName = "H263-1998";
pay.rtp.id = 96;
pay.rtp.clockRate = 90000;
MediaSpec ms;
ms.transport.rtp.address = LOCAL_ADDRESS;
ms.transport.rtp.port = DEFAULT_PORT;
ms.transport.__isset.rtp = true;
ms.direction = Direction::type::SENDONLY;
ms.type.insert(MediaType::VIDEO);
ms.payloads.push_back(pay);
spec.id = "1234";
spec.medias.push_back(ms);
}
static void
create_newtork_connection(NetworkConnection &_nc, ServerConfig &mc, MediaSession &ms) {
if (!mc.__isset.mediaSessionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.mediaSessionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
MediaSessionServiceClient mservice(prot);
transport->open();
std::vector<NetworkConnectionConfig::type> config;
config.push_back(NetworkConnectionConfig::type::RTP);
mservice.createNetworkConnection(_nc, ms, config);
}
static void
negotiate_connection(ServerConfig &mc, NetworkConnection& nc, SessionSpec& spec) {
if (!mc.__isset.networkConnectionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.networkConnectionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
NetworkConnectionServiceClient service(prot);
transport->open();
SessionSpec reply;
service.processOffer(reply, nc, spec);
print_session_spec(reply);
send_receive_media(reply);
}
static void
join_network_connections(ServerConfig &mc, NetworkConnection& nc,
NetworkConnection& nc2) {
if (!mc.__isset.networkConnectionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.networkConnectionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
NetworkConnectionServiceClient service(prot);
transport->open();
service.joinStream(nc.joinable, nc2.joinable, StreamType::type::VIDEO,
Direction::RECVONLY);
}
static void
ping_media_session(ServerConfig &mc, MediaSession& ms, int iter, int interval) {
if (!mc.__isset.mediaSessionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.mediaSessionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
MediaSessionServiceClient service(prot);
transport->open();
for (; iter > 0; iter--) {
service.ping(ms, interval + 1);
sleep(interval);
}
}
static void
start_client() {
boost::shared_ptr<TSocket> transport(new TSocket("localhost", 9090));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
MediaServerServiceClient mservice(prot);
transport->open();
ServerConfig mc;
MediaSession ms;
NetworkConnection nc, nc2;
SessionSpec spec;
SessionSpec spec2;
mservice.getServerconfig(mc);
mservice.createMediaSession(ms);
std::cout << "Session id: " << ms.object.id << std::endl;
create_newtork_connection(nc, mc, ms);
std::cout << "NetworkConnection: " << nc.joinable.object.id << std::endl;
create_session_spec(spec);
negotiate_connection(mc, nc, spec);
create_newtork_connection(nc2, mc, ms);
std::cout << "NetworkConnection: " << nc2.joinable.object.id << std::endl;
create_second_session_spec(spec2);
negotiate_connection(mc, nc2, spec2);
join_network_connections(mc, nc, nc2);
ping_media_session(mc, ms, 4, 30);
mservice.deleteMediaSession(ms);
}
int
main(int argc, char **argv) {
gst_init(&argc, &argv);
// TODO: Evaluate if server should be launched here
start_client();
}
|
Fix direction on test_server
|
Fix direction on test_server
|
C++
|
lgpl-2.1
|
shelsonjava/kurento-media-server,todotobe1/kurento-media-server,Kurento/kurento-media-server,shelsonjava/kurento-media-server,lulufei/kurento-media-server,mparis/kurento-media-server,TribeMedia/kurento-media-server,todotobe1/kurento-media-server,mparis/kurento-media-server,TribeMedia/kurento-media-server,lulufei/kurento-media-server,Kurento/kurento-media-server
|
3e6c41c48f4fbbc226892bd7946a2073d8a8a523
|
webrtc/voice_engine/test/auto_test/standard/dtmf_test.cc
|
webrtc/voice_engine/test/auto_test/standard/dtmf_test.cc
|
/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/voice_engine/test/auto_test/fixtures/after_streaming_fixture.h"
#include "webrtc/voice_engine/voice_engine_defines.h"
class DtmfTest : public AfterStreamingFixture {
protected:
void RunSixteenDtmfEvents(bool out_of_band) {
TEST_LOG("Sending telephone events:\n");
EXPECT_EQ(0, voe_dtmf_->SetDtmfFeedbackStatus(false));
for (int i = 0; i < 16; i++) {
TEST_LOG("%d ", i);
TEST_LOG_FLUSH;
EXPECT_EQ(0, voe_dtmf_->SendTelephoneEvent(
channel_, i, out_of_band, 160, 10));
Sleep(500);
}
TEST_LOG("\n");
}
};
TEST_F(DtmfTest, DtmfFeedbackIsEnabledByDefaultButNotDirectFeedback) {
bool dtmf_feedback = false;
bool dtmf_direct_feedback = false;
EXPECT_EQ(0, voe_dtmf_->GetDtmfFeedbackStatus(dtmf_feedback,
dtmf_direct_feedback));
EXPECT_TRUE(dtmf_feedback);
EXPECT_FALSE(dtmf_direct_feedback);
}
TEST_F(DtmfTest, DISABLED_ManualSuccessfullySendsInBandTelephoneEvents) {
RunSixteenDtmfEvents(false);
}
TEST_F(DtmfTest, DISABLED_ManualSuccessfullySendsOutOfBandTelephoneEvents) {
RunSixteenDtmfEvents(true);
}
TEST_F(DtmfTest, TestTwoNonDtmfEvents) {
EXPECT_EQ(0, voe_dtmf_->SendTelephoneEvent(channel_, 32, true));
EXPECT_EQ(0, voe_dtmf_->SendTelephoneEvent(channel_, 110, true));
}
#ifndef WEBRTC_IOS
TEST_F(DtmfTest, ManualCanDisableDtmfPlayoutExceptOnIphone) {
TEST_LOG("Disabling DTMF playout (no tone should be heard) \n");
EXPECT_EQ(0, voe_dtmf_->SetDtmfPlayoutStatus(channel_, false));
EXPECT_EQ(0, voe_dtmf_->SendTelephoneEvent(channel_, 0, true));
Sleep(500);
TEST_LOG("Enabling DTMF playout (tone should be heard) \n");
EXPECT_EQ(0, voe_dtmf_->SetDtmfPlayoutStatus(channel_, true));
EXPECT_EQ(0, voe_dtmf_->SendTelephoneEvent(channel_, 0, true));
Sleep(500);
}
#endif
// This test modifies the DTMF payload type from the default 106 to 88
// and then runs through 16 DTMF out.of-band events.
TEST_F(DtmfTest, ManualCanChangeDtmfPayloadType) {
webrtc::CodecInst codec_instance;
TEST_LOG("Changing DTMF payload type.\n");
// Start by modifying the receiving side.
for (int i = 0; i < voe_codec_->NumOfCodecs(); i++) {
EXPECT_EQ(0, voe_codec_->GetCodec(i, codec_instance));
if (!_stricmp("telephone-event", codec_instance.plname)) {
codec_instance.pltype = 88; // Use 88 instead of default 106.
EXPECT_EQ(0, voe_base_->StopSend(channel_));
EXPECT_EQ(0, voe_base_->StopPlayout(channel_));
EXPECT_EQ(0, voe_base_->StopReceive(channel_));
EXPECT_EQ(0, voe_codec_->SetRecPayloadType(channel_, codec_instance));
EXPECT_EQ(0, voe_base_->StartReceive(channel_));
EXPECT_EQ(0, voe_base_->StartPlayout(channel_));
EXPECT_EQ(0, voe_base_->StartSend(channel_));
break;
}
}
Sleep(500);
// Next, we must modify the sending side as well.
EXPECT_EQ(0, voe_dtmf_->SetSendTelephoneEventPayloadType(
channel_, codec_instance.pltype));
RunSixteenDtmfEvents(true);
EXPECT_EQ(0, voe_dtmf_->SetDtmfFeedbackStatus(true, false));
}
|
/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/voice_engine/test/auto_test/fixtures/after_streaming_fixture.h"
#include "webrtc/voice_engine/voice_engine_defines.h"
class DtmfTest : public AfterStreamingFixture {
protected:
void RunSixteenDtmfEvents(bool out_of_band) {
TEST_LOG("Sending telephone events:\n");
EXPECT_EQ(0, voe_dtmf_->SetDtmfFeedbackStatus(false));
for (int i = 0; i < 16; i++) {
TEST_LOG("%d ", i);
TEST_LOG_FLUSH;
EXPECT_EQ(0, voe_dtmf_->SendTelephoneEvent(
channel_, i, out_of_band, 160, 10));
Sleep(500);
}
TEST_LOG("\n");
}
};
TEST_F(DtmfTest, DtmfFeedbackIsEnabledByDefaultButNotDirectFeedback) {
bool dtmf_feedback = false;
bool dtmf_direct_feedback = false;
EXPECT_EQ(0, voe_dtmf_->GetDtmfFeedbackStatus(dtmf_feedback,
dtmf_direct_feedback));
EXPECT_TRUE(dtmf_feedback);
EXPECT_FALSE(dtmf_direct_feedback);
}
TEST_F(DtmfTest, ManualSuccessfullySendsInBandTelephoneEvents) {
RunSixteenDtmfEvents(false);
}
TEST_F(DtmfTest, ManualSuccessfullySendsOutOfBandTelephoneEvents) {
RunSixteenDtmfEvents(true);
}
TEST_F(DtmfTest, TestTwoNonDtmfEvents) {
EXPECT_EQ(0, voe_dtmf_->SendTelephoneEvent(channel_, 32, true));
EXPECT_EQ(0, voe_dtmf_->SendTelephoneEvent(channel_, 110, true));
}
#ifndef WEBRTC_IOS
TEST_F(DtmfTest, ManualCanDisableDtmfPlayoutExceptOnIphone) {
TEST_LOG("Disabling DTMF playout (no tone should be heard) \n");
EXPECT_EQ(0, voe_dtmf_->SetDtmfPlayoutStatus(channel_, false));
EXPECT_EQ(0, voe_dtmf_->SendTelephoneEvent(channel_, 0, true));
Sleep(500);
TEST_LOG("Enabling DTMF playout (tone should be heard) \n");
EXPECT_EQ(0, voe_dtmf_->SetDtmfPlayoutStatus(channel_, true));
EXPECT_EQ(0, voe_dtmf_->SendTelephoneEvent(channel_, 0, true));
Sleep(500);
}
#endif
// This test modifies the DTMF payload type from the default 106 to 88
// and then runs through 16 DTMF out.of-band events.
TEST_F(DtmfTest, ManualCanChangeDtmfPayloadType) {
webrtc::CodecInst codec_instance;
TEST_LOG("Changing DTMF payload type.\n");
// Start by modifying the receiving side.
for (int i = 0; i < voe_codec_->NumOfCodecs(); i++) {
EXPECT_EQ(0, voe_codec_->GetCodec(i, codec_instance));
if (!_stricmp("telephone-event", codec_instance.plname)) {
codec_instance.pltype = 88; // Use 88 instead of default 106.
EXPECT_EQ(0, voe_base_->StopSend(channel_));
EXPECT_EQ(0, voe_base_->StopPlayout(channel_));
EXPECT_EQ(0, voe_base_->StopReceive(channel_));
EXPECT_EQ(0, voe_codec_->SetRecPayloadType(channel_, codec_instance));
EXPECT_EQ(0, voe_base_->StartReceive(channel_));
EXPECT_EQ(0, voe_base_->StartPlayout(channel_));
EXPECT_EQ(0, voe_base_->StartSend(channel_));
break;
}
}
Sleep(500);
// Next, we must modify the sending side as well.
EXPECT_EQ(0, voe_dtmf_->SetSendTelephoneEventPayloadType(
channel_, codec_instance.pltype));
RunSixteenDtmfEvents(true);
EXPECT_EQ(0, voe_dtmf_->SetDtmfFeedbackStatus(true, false));
}
|
Revert "Disable the test: DtmfTest.ManualSuccessfullySendsIn/OutOfBandTelephoneEvents"
|
Revert "Disable the test: DtmfTest.ManualSuccessfullySendsIn/OutOfBandTelephoneEvents"
This reverts commit r5479.
[email protected]
BUG=2880
Review URL: https://webrtc-codereview.appspot.com/7989004
git-svn-id: 917f5d3ca488f358c4d40eaec14422cf392ccec9@5485 4adac7df-926f-26a2-2b94-8c16560cd09d
|
C++
|
bsd-3-clause
|
mwgoldsmith/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,mwgoldsmith/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,mwgoldsmith/libilbc,TimothyGu/libilbc,mwgoldsmith/ilbc,mwgoldsmith/ilbc,mwgoldsmith/ilbc,ShiftMediaProject/libilbc,mwgoldsmith/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,mwgoldsmith/ilbc
|
6308bb7c7aacfbad90e1a60434c5ea0125ad5edc
|
ch15/ex15.5.6/bulk_quote.cpp
|
ch15/ex15.5.6/bulk_quote.cpp
|
#include "bulk_quote.h"
double Bulk_quote::net_price(std::size_t n) const
{
return n * price * ( n >= min_qty ? 1 - discount : 1);
}
|
#include <cstddef>
#include "Bulk_quote.h"
double Bulk_quote::net_price(size_t n) const
{
return n*price*(n>=min_qty ? 1-discount : 1);
}
|
Update bulk_quote.cpp
|
Update bulk_quote.cpp
|
C++
|
cc0-1.0
|
zhangzhizhongz3/CppPrimer,zhangzhizhongz3/CppPrimer
|
f01e9ed5dc341f504897b6cce086f8136f4b32b2
|
PWGDQ/dielectron/macrosLMEE/AddTask_acapon_Efficiency.C
|
PWGDQ/dielectron/macrosLMEE/AddTask_acapon_Efficiency.C
|
// Names should contain a comma seperated list of cut settings
// Current options: all, electrons, kCutSet1, TTreeCuts, V0_TPCcorr, V0_ITScorr
AliAnalysisTaskElectronEfficiencyV2* AddTask_acapon_Efficiency(TString names = "kCutSet1",
Int_t whichGen = 0, // 0=all sources, 1=Jpsi, 2=HS
Int_t wagonnr = 0,
TString centrality = "0;100;V0A", // min;max;estimator
Bool_t SDDstatus = kTRUE,
Bool_t applyPIDcorr = kTRUE,
std::string resoFilename = "", // Leave blank to not use resolution files
Bool_t DoPairing = kTRUE,
Bool_t DoULSLS = kTRUE,
Bool_t DeactivateLS = kTRUE,
Bool_t DoCocktailWeighting = kFALSE,
Bool_t GetCocktailFromAlien = kFALSE,
std::string CocktailFilename = "",
Bool_t cutlibPreloaded = kFALSE,
Bool_t getFromAlien = kFALSE)
{
std::cout << "########################################\nADDTASK of ANALYSIS started\n########################################" << std::endl;
TObjArray* arrNames = names.Tokenize(";");
Int_t nDie = arrNames->GetEntries();
Printf("Number of implemented cuts: %i", nDie);
std::string resoFilenameFromAlien = "/alice/cern.ch/user/a/acapon/ResolutionFiles/";
resoFilenameFromAlien.append(resoFilename);
std::string CocktailFilenameFromAlien = "/alice/cern.ch/user/a/acapon/Cocktails/";
CocktailFilenameFromAlien.append(CocktailFilename);
// #########################################################
// Configuring Analysis Manager
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
TString fileName = AliAnalysisManager::GetCommonFileName();
fileName = "AnalysisResults.root"; // create a subfolder in the file
// #########################################################
// Loading individual config file either local or from Alien
TString configBasePath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/");
TString configFile("Config_acapon_Efficiency.C");
TString configLMEECutLib("LMEECutLib_acapon.C");
// Load updated macros from private ALIEN path
if(getFromAlien //&&
&& (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/a/acapon/PWGDQ/dielectron/macrosLMEE/%s .",configFile.Data())))
&& (!gSystem->Exec("alien_cp alien:///alice/cern.ch/user/a/acapon/PWGDQ/dielectron/macrosLMEE/LMEECutLib_acapon.C ."))
){
configBasePath=Form("%s/",gSystem->pwd());
}
TString configFilePath(configBasePath+configFile);
TString configLMEECutLibPath(configBasePath+configLMEECutLib);
// Load dielectron configuration files
if(!gROOT->GetListOfGlobalFunctions()->FindObject(configLMEECutLib.Data())){
gROOT->LoadMacro(configLMEECutLibPath.Data());
}
if(!gROOT->GetListOfGlobalFunctions()->FindObject(configFile.Data())){
gROOT->LoadMacro(configFilePath.Data());
}
// #########################################################
// Creating an instance of the task
AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form("%s%d",names.Data(), wagonnr));
// #########################################################
// Possibility to set generator. If nothing set all generators are taken into account
if(whichGen == 0){
std::cout << "No generator specified. Looking at all sources" << std::endl;
task->SetGeneratorMCSignalName("");
task->SetGeneratorULSSignalName("");
}
else if(whichGen == 1){
std::cout << "Generator names specified -> Jpsi2ee_1 and B2Jpsi2ee_1" << std::endl;
task->SetGeneratorMCSignalName("Jpsi2ee_1;B2Jpsi2ee_1");
task->SetGeneratorULSSignalName("Jpsi2ee_1;B2Jpsi2ee_1");
}
else if(whichGen == 2){
std::cout << "Generator names specified -> Pythia CC_1, Pythia BB_1 and Pythia B_1" << std::endl;
task->SetGeneratorMCSignalName("Pythia CC_1;Pythia BB_1;Pythia B_1");
task->SetGeneratorULSSignalName("Pythia CC_1;Pythia BB_1;Pythia B_1");
}
// #########################################################
// Cut lib
LMEECutLib* cutlib = new LMEECutLib(SDDstatus);
// Event selection is the same for all cut settings
task->SetEnablePhysicsSelection(kTRUE);
task->SetTriggerMask(triggerNames);
task->SetEventFilter(cutlib->GetEventCuts(kFALSE, kFALSE));
// Set centrality requirements
// There is certainly a better way to do this next section....
TObjArray* centDetails = centrality.Tokenize(";");
TString tempMinFloat = TString(centDetails->At(0)->GetName());
TString tempMaxFloat = TString(centDetails->At(1)->GetName());
Float_t minCent = tempMinFloat.Atoi();
Float_t maxCent = tempMaxFloat.Atoi();
std::cout << "CentMin = " << minCent << " CentMax = " << maxCent << std::endl;
task->SetCentrality(minCent, maxCent);
TString whichCentEst = TString(centDetails->At(2)->GetName());
task->SetCentralityEstimator(whichCentEst);
// #########################################################
// Set minimum and maximum values of generated tracks. Only used to save computing power.
// Do not set here your analysis pt-cuts
task->SetMinPtGen(minGenPt);
task->SetMaxPtGen(maxGenPt);
task->SetMinEtaGen(minGenEta);
task->SetMaxEtaGen(maxGenEta);
// #########################################################
// Set kinematic cuts for pairing
task->SetKinematicCuts(minPtCut, maxPtCut, minEtaCut, maxEtaCut);
// #########################################################
// Set Binning
if(usePtVector == kTRUE){
std::vector<Double_t> ptBinsVec;
for(UInt_t i = 0; i < nBinsPt+1; ++i){
ptBinsVec.push_back(ptBins[i]);
}
task->SetPtBins(ptBinsVec);
}
else{
task->SetPtBinsLinear(minPtBin, maxPtBin, stepsPtBin);
}
task->SetEtaBinsLinear (minEtaBin, maxEtaBin, stepsEtaBin);
task->SetPhiBinsLinear (minPhiBin, maxPhiBin, stepsPhiBin);
task->SetThetaBinsLinear(minThetaBin, maxThetaBin, stepsThetaBin);
// Mass and pairPt binning should match kMee and kPtee in Config_acapon.C
Double_t massBinsArr[] = {0.00,0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09,
0.10,0.11,0.12,0.13,0.14,0.15,0.16,0.17,0.18,0.19,
0.20,0.21,0.22,0.23,0.24,0.25,0.26,0.27,0.28,0.29,
0.30,0.31,0.32,0.33,0.34,0.35,0.36,0.37,0.38,0.39,
0.40,0.41,0.42,0.43,0.44,0.45,0.46,0.47,0.48,0.49,
0.50,0.51,0.52,0.53,0.54,0.55,0.56,0.57,0.58,0.59,
0.60,0.61,0.62,0.63,0.64,0.65,0.66,0.67,0.68,0.69,
0.70,0.71,0.72,0.73,0.74,0.75,0.76,0.77,0.78,0.79,
0.80,0.81,0.82,0.83,0.84,0.85,0.86,0.87,0.88,0.89,
0.90,0.91,0.92,0.93,0.94,0.95,0.96,0.97,0.98,0.99,
1.00,1.01,1.02,1.03,1.04,1.05,1.06,1.07,1.08,1.09,
1.10,1.20,1.30,1.40,1.50,1.60,1.70,1.80,1.90,2.00,
2.10,2.20,2.30,2.40,2.50,2.60,2.70,2.80,2.90,3.00,
3.01,3.02,3.03,3.04,3.05,3.06,3.07,3.08,3.09,3.10,
3.11,3.12,3.30,3.50,4.00,4.50,5.00};
std::vector<Double_t> massBins;
for(Int_t j = 0; j < sizeof(massBinsArr)/sizeof(massBinsArr[0]); j++){
massBins.push_back(massBinsArr[j]);
}
task->SetMassBins(massBins);
Double_t pairPtBinsArr[] = {0.000,0.025,0.050,0.075,0.100,0.125,0.150,0.175,0.200,0.225,0.250,
0.275,0.300,0.325,0.350,0.375,0.400,0.425,0.450,0.475,0.500,0.550,
0.600,0.650,0.700,0.750,0.800,0.850,0.900,0.950,1.000,1.050,1.100,
1.150,1.200,1.250,1.300,1.350,1.400,1.450,1.500,1.550,1.600,1.650,
1.700,1.750,1.800,1.850,1.900,1.950,2.000,2.050,2.100,2.150,2.200,
2.250,2.300,2.350,2.400,2.450,2.500,2.600,2.700,2.800,2.900,3.000,
3.100,3.200,3.300,3.400,3.500,3.600,3.700,3.800,3.900,4.000,4.100,
4.200,4.300,4.400,4.500,5.000,5.500,6.000,6.500,7.000,8.000,10.00};
std::vector<Double_t> pairPtBins;
for(Int_t k = 0; k < sizeof(pairPtBinsArr)/sizeof(pairPtBinsArr[0]); k++){
pairPtBins.push_back(pairPtBinsArr[k]);
}
task->SetPairPtBins(pairPtBins);
// #########################################################
// #########################################################
// Resolution File, If resoFilename = "" no correction is applied
task->SetResolutionFile(resoFilename);
task->SetResolutionFileFromAlien(resoFilenameFromAlien);
task->SetSmearGenerated(SetGeneratedSmearingHistos);
task->SetResolutionDeltaPtBinsLinear (DeltaMomMin, DeltaMomMax, NbinsDeltaMom);
task->SetResolutionRelPtBinsLinear (RelMomMin, RelMomMax, NbinsRelMom);
task->SetResolutionEtaBinsLinear (DeltaEtaMin, DeltaEtaMax, NbinsDeltaEta);
task->SetResolutionPhiBinsLinear (DeltaPhiMin, DeltaPhiMax, NbinsDeltaPhi);
task->SetResolutionThetaBinsLinear(DeltaThetaMin, DeltaThetaMax, NbinsDeltaTheta);
// #########################################################
// #########################################################
// Set centrality correction. If resoFilename = "" no correction is applied
task->SetCentralityFile(centralityFilename);
// #########################################################
// #########################################################
// Set MCSignal and Cutsetting to fill the support histograms
task->SetSupportHistoMCSignalAndCutsetting(nMCSignal, nCutsetting);
// #########################################################
// #########################################################
// Set Cocktail weighting
task->SetDoCocktailWeighting(DoCocktailWeighting);
task->SetCocktailWeighting(CocktailFilename);
task->SetCocktailWeightingFromAlien(CocktailFilenameFromAlien);
// #########################################################
// #########################################################
// Pairing related config
task->SetDoPairing(DoPairing);
task->SetULSandLS(DoULSLS);
task->SetDeactivateLS(DeactivateLS);
// #########################################################
// #########################################################
// Add MCSignals
// Add single track signal definition, and return vector used for calculating
// efficiencies from non resonant dielectron pairs. E.g use all ULS pairs,
// electrons from D or B decays etc
std::vector<Bool_t> DielectronsPairNotFromSameMother = AddSingleLegMCSignal(task);
task->AddMCSignalsWhereDielectronPairNotFromSameMother(DielectronsPairNotFromSameMother);
// Add standard "same-mother" dielectron pair signal
AddPairMCSignal(task);
// #########################################################
// Adding cut settings
for(Int_t iCut = 0; iCut < nDie; ++iCut){
TString cutDefinition(arrNames->At(iCut)->GetName());
AliAnalysisFilter* filter = SetupTrackCutsAndSettings(cutDefinition, SDDstatus);
if(!filter){
std::cout << "Invalid cut setting specified!!" << std::endl;
return 0x0;
}
task->AddTrackCuts(filter);
Printf("Successfully added task with cut set: %s\n", cutDefinition);
// Apply PID post calibration to ITS(0) and TOF(1)
if(applyPIDcorr){
ApplyPIDpostCalibration(task, 0, SDDstatus);
ApplyPIDpostCalibration(task, 1, SDDstatus);
}
}
mgr->AddTask(task);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, mgr->CreateContainer(Form("efficiency%d", wagonnr), TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
return task;
}
|
// Names should contain a comma seperated list of cut settings
// Current options: all, electrons, kCutSet1, TTreeCuts, V0_TPCcorr, V0_ITScorr
AliAnalysisTaskElectronEfficiencyV2* AddTask_acapon_Efficiency(TString names = "kCutSet1",
Int_t whichGen = 0, // 0=all sources, 1=Jpsi, 2=HS
Int_t wagonnr = 0,
TString centrality = "0;100;V0A", // min;max;estimator
Bool_t SDDstatus = kTRUE,
Bool_t applyPIDcorr = kTRUE,
std::string resoFilename = "", // Leave blank to not use resolution files
Bool_t DoPairing = kTRUE,
Bool_t DoULSLS = kTRUE,
Bool_t DeactivateLS = kTRUE,
Bool_t DoCocktailWeighting = kFALSE,
Bool_t GetCocktailFromAlien = kFALSE,
std::string CocktailFilename = "",
Bool_t cutlibPreloaded = kFALSE,
Bool_t getFromAlien = kFALSE)
{
std::cout << "########################################\nADDTASK of ANALYSIS started\n########################################" << std::endl;
TObjArray* arrNames = names.Tokenize(";");
Int_t nDie = arrNames->GetEntries();
Printf("Number of implemented cuts: %i", nDie);
std::string resoFilenameFromAlien = "/alice/cern.ch/user/a/acapon/ResolutionFiles/";
resoFilenameFromAlien.append(resoFilename);
std::string CocktailFilenameFromAlien = "/alice/cern.ch/user/a/acapon/Cocktails/";
CocktailFilenameFromAlien.append(CocktailFilename);
// #########################################################
// Configuring Analysis Manager
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
TString fileName = AliAnalysisManager::GetCommonFileName();
fileName = "AnalysisResults.root"; // create a subfolder in the file
// #########################################################
// Loading individual config file either local or from Alien
TString configBasePath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/");
TString configFile("Config_acapon_Efficiency.C");
TString configLMEECutLib("LMEECutLib_acapon.C");
// Load updated macros from private ALIEN path
if(getFromAlien //&&
&& (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/a/acapon/PWGDQ/dielectron/macrosLMEE/%s .",configFile.Data())))
&& (!gSystem->Exec("alien_cp alien:///alice/cern.ch/user/a/acapon/PWGDQ/dielectron/macrosLMEE/LMEECutLib_acapon.C ."))
){
configBasePath=Form("%s/",gSystem->pwd());
}
TString configFilePath(configBasePath+configFile);
TString configLMEECutLibPath(configBasePath+configLMEECutLib);
// Load dielectron configuration files
if(!gROOT->GetListOfGlobalFunctions()->FindObject(configLMEECutLib.Data())){
gROOT->LoadMacro(configLMEECutLibPath.Data());
}
if(!gROOT->GetListOfGlobalFunctions()->FindObject(configFile.Data())){
gROOT->LoadMacro(configFilePath.Data());
}
// #########################################################
// Creating an instance of the task
AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form("%s%d",names.Data(), wagonnr));
// #########################################################
// Possibility to set generator. If nothing set all generators are taken into account
if(whichGen == 0){
std::cout << "No generator specified. Looking at all sources" << std::endl;
task->SetGeneratorMCSignalName("");
task->SetGeneratorULSSignalName("");
}
else if(whichGen == 1){
std::cout << "Generator names specified -> Jpsi2ee_1 and B2Jpsi2ee_1" << std::endl;
task->SetGeneratorMCSignalName("Jpsi2ee_1;B2Jpsi2ee_1");
task->SetGeneratorULSSignalName("Jpsi2ee_1;B2Jpsi2ee_1");
}
else if(whichGen == 2){
std::cout << "Generator names specified -> Pythia CC_1, Pythia BB_1 and Pythia B_1" << std::endl;
task->SetGeneratorMCSignalName("Pythia CC_1;Pythia BB_1;Pythia B_1");
task->SetGeneratorULSSignalName("Pythia CC_1;Pythia BB_1;Pythia B_1");
}
// #########################################################
// Cut lib
LMEECutLib* cutlib = new LMEECutLib(SDDstatus);
// Event selection is the same for all cut settings
task->SetEnablePhysicsSelection(kTRUE);
task->SetTriggerMask(triggerNames);
task->SetEventFilter(cutlib->GetEventCuts(kFALSE, kFALSE));
task->SetRejectParticleFromOOB(kTRUE);
// Set centrality requirements
// There is certainly a better way to do this next section....
TObjArray* centDetails = centrality.Tokenize(";");
TString tempMinFloat = TString(centDetails->At(0)->GetName());
TString tempMaxFloat = TString(centDetails->At(1)->GetName());
Float_t minCent = tempMinFloat.Atoi();
Float_t maxCent = tempMaxFloat.Atoi();
std::cout << "CentMin = " << minCent << " CentMax = " << maxCent << std::endl;
task->SetCentrality(minCent, maxCent);
TString whichCentEst = TString(centDetails->At(2)->GetName());
task->SetCentralityEstimator(whichCentEst);
// #########################################################
// Set minimum and maximum values of generated tracks. Only used to save computing power.
// Do not set here your analysis pt-cuts
task->SetMinPtGen(minGenPt);
task->SetMaxPtGen(maxGenPt);
task->SetMinEtaGen(minGenEta);
task->SetMaxEtaGen(maxGenEta);
// #########################################################
// Set kinematic cuts for pairing
task->SetKinematicCuts(minPtCut, maxPtCut, minEtaCut, maxEtaCut);
// #########################################################
// Set Binning
if(usePtVector == kTRUE){
std::vector<Double_t> ptBinsVec;
for(UInt_t i = 0; i < nBinsPt+1; ++i){
ptBinsVec.push_back(ptBins[i]);
}
task->SetPtBins(ptBinsVec);
}
else{
task->SetPtBinsLinear(minPtBin, maxPtBin, stepsPtBin);
}
task->SetEtaBinsLinear (minEtaBin, maxEtaBin, stepsEtaBin);
task->SetPhiBinsLinear (minPhiBin, maxPhiBin, stepsPhiBin);
task->SetThetaBinsLinear(minThetaBin, maxThetaBin, stepsThetaBin);
// Mass and pairPt binning should match kMee and kPtee in Config_acapon.C
Double_t massBinsArr[] = {0.00,0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09,
0.10,0.11,0.12,0.13,0.14,0.15,0.16,0.17,0.18,0.19,
0.20,0.21,0.22,0.23,0.24,0.25,0.26,0.27,0.28,0.29,
0.30,0.31,0.32,0.33,0.34,0.35,0.36,0.37,0.38,0.39,
0.40,0.41,0.42,0.43,0.44,0.45,0.46,0.47,0.48,0.49,
0.50,0.51,0.52,0.53,0.54,0.55,0.56,0.57,0.58,0.59,
0.60,0.61,0.62,0.63,0.64,0.65,0.66,0.67,0.68,0.69,
0.70,0.71,0.72,0.73,0.74,0.75,0.76,0.77,0.78,0.79,
0.80,0.81,0.82,0.83,0.84,0.85,0.86,0.87,0.88,0.89,
0.90,0.91,0.92,0.93,0.94,0.95,0.96,0.97,0.98,0.99,
1.00,1.01,1.02,1.03,1.04,1.05,1.06,1.07,1.08,1.09,
1.10,1.20,1.30,1.40,1.50,1.60,1.70,1.80,1.90,2.00,
2.10,2.20,2.30,2.40,2.50,2.60,2.70,2.80,2.90,3.00,
3.01,3.02,3.03,3.04,3.05,3.06,3.07,3.08,3.09,3.10,
3.11,3.12,3.30,3.50,4.00,4.50,5.00};
std::vector<Double_t> massBins;
for(Int_t j = 0; j < sizeof(massBinsArr)/sizeof(massBinsArr[0]); j++){
massBins.push_back(massBinsArr[j]);
}
task->SetMassBins(massBins);
Double_t pairPtBinsArr[] = {0.000,0.025,0.050,0.075,0.100,0.125,0.150,0.175,0.200,0.225,0.250,
0.275,0.300,0.325,0.350,0.375,0.400,0.425,0.450,0.475,0.500,0.550,
0.600,0.650,0.700,0.750,0.800,0.850,0.900,0.950,1.000,1.050,1.100,
1.150,1.200,1.250,1.300,1.350,1.400,1.450,1.500,1.550,1.600,1.650,
1.700,1.750,1.800,1.850,1.900,1.950,2.000,2.050,2.100,2.150,2.200,
2.250,2.300,2.350,2.400,2.450,2.500,2.600,2.700,2.800,2.900,3.000,
3.100,3.200,3.300,3.400,3.500,3.600,3.700,3.800,3.900,4.000,4.100,
4.200,4.300,4.400,4.500,5.000,5.500,6.000,6.500,7.000,8.000,10.00};
std::vector<Double_t> pairPtBins;
for(Int_t k = 0; k < sizeof(pairPtBinsArr)/sizeof(pairPtBinsArr[0]); k++){
pairPtBins.push_back(pairPtBinsArr[k]);
}
task->SetPairPtBins(pairPtBins);
// #########################################################
// #########################################################
// Resolution File, If resoFilename = "" no correction is applied
task->SetResolutionFile(resoFilename);
task->SetResolutionFileFromAlien(resoFilenameFromAlien);
task->SetSmearGenerated(SetGeneratedSmearingHistos);
task->SetResolutionDeltaPtBinsLinear (DeltaMomMin, DeltaMomMax, NbinsDeltaMom);
task->SetResolutionRelPtBinsLinear (RelMomMin, RelMomMax, NbinsRelMom);
task->SetResolutionEtaBinsLinear (DeltaEtaMin, DeltaEtaMax, NbinsDeltaEta);
task->SetResolutionPhiBinsLinear (DeltaPhiMin, DeltaPhiMax, NbinsDeltaPhi);
task->SetResolutionThetaBinsLinear(DeltaThetaMin, DeltaThetaMax, NbinsDeltaTheta);
// #########################################################
// #########################################################
// Set centrality correction. If resoFilename = "" no correction is applied
task->SetCentralityFile(centralityFilename);
// #########################################################
// #########################################################
// Set MCSignal and Cutsetting to fill the support histograms
task->SetSupportHistoMCSignalAndCutsetting(nMCSignal, nCutsetting);
// #########################################################
// #########################################################
// Set Cocktail weighting
task->SetDoCocktailWeighting(DoCocktailWeighting);
task->SetCocktailWeighting(CocktailFilename);
task->SetCocktailWeightingFromAlien(CocktailFilenameFromAlien);
// #########################################################
// #########################################################
// Pairing related config
task->SetDoPairing(DoPairing);
task->SetULSandLS(DoULSLS);
task->SetDeactivateLS(DeactivateLS);
// #########################################################
// #########################################################
// Add MCSignals
// Add single track signal definition, and return vector used for calculating
// efficiencies from non resonant dielectron pairs. E.g use all ULS pairs,
// electrons from D or B decays etc
std::vector<Bool_t> DielectronsPairNotFromSameMother = AddSingleLegMCSignal(task);
task->AddMCSignalsWhereDielectronPairNotFromSameMother(DielectronsPairNotFromSameMother);
// Add standard "same-mother" dielectron pair signal
AddPairMCSignal(task);
// #########################################################
// Adding cut settings
for(Int_t iCut = 0; iCut < nDie; ++iCut){
TString cutDefinition(arrNames->At(iCut)->GetName());
AliAnalysisFilter* filter = SetupTrackCutsAndSettings(cutDefinition, SDDstatus);
if(!filter){
std::cout << "Invalid cut setting specified!!" << std::endl;
return 0x0;
}
task->AddTrackCuts(filter);
Printf("Successfully added task with cut set: %s\n", cutDefinition);
// Apply PID post calibration to ITS(0) and TOF(1)
if(applyPIDcorr){
ApplyPIDpostCalibration(task, 0, SDDstatus);
ApplyPIDpostCalibration(task, 1, SDDstatus);
}
}
mgr->AddTask(task);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, mgr->CreateContainer(Form("efficiency%d", wagonnr), TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
return task;
}
|
Update AddTask_acapon_Efficiency.C
|
Update AddTask_acapon_Efficiency.C
Adding possibility to reject particles from out-of-bunch pilepu
|
C++
|
bsd-3-clause
|
amaringarcia/AliPhysics,amaringarcia/AliPhysics,alisw/AliPhysics,fcolamar/AliPhysics,alisw/AliPhysics,AMechler/AliPhysics,rihanphys/AliPhysics,adriansev/AliPhysics,rbailhac/AliPhysics,pchrista/AliPhysics,rihanphys/AliPhysics,adriansev/AliPhysics,mpuccio/AliPhysics,rbailhac/AliPhysics,rihanphys/AliPhysics,AMechler/AliPhysics,AMechler/AliPhysics,AMechler/AliPhysics,amaringarcia/AliPhysics,adriansev/AliPhysics,nschmidtALICE/AliPhysics,rbailhac/AliPhysics,amaringarcia/AliPhysics,rihanphys/AliPhysics,fcolamar/AliPhysics,mpuccio/AliPhysics,victor-gonzalez/AliPhysics,victor-gonzalez/AliPhysics,pchrista/AliPhysics,rbailhac/AliPhysics,amaringarcia/AliPhysics,adriansev/AliPhysics,rbailhac/AliPhysics,fcolamar/AliPhysics,mpuccio/AliPhysics,fcolamar/AliPhysics,mpuccio/AliPhysics,fcolamar/AliPhysics,rbailhac/AliPhysics,amaringarcia/AliPhysics,alisw/AliPhysics,rihanphys/AliPhysics,AMechler/AliPhysics,nschmidtALICE/AliPhysics,victor-gonzalez/AliPhysics,adriansev/AliPhysics,nschmidtALICE/AliPhysics,pchrista/AliPhysics,pchrista/AliPhysics,victor-gonzalez/AliPhysics,AMechler/AliPhysics,mpuccio/AliPhysics,nschmidtALICE/AliPhysics,alisw/AliPhysics,adriansev/AliPhysics,adriansev/AliPhysics,AMechler/AliPhysics,alisw/AliPhysics,mpuccio/AliPhysics,mpuccio/AliPhysics,pchrista/AliPhysics,amaringarcia/AliPhysics,nschmidtALICE/AliPhysics,victor-gonzalez/AliPhysics,rihanphys/AliPhysics,pchrista/AliPhysics,pchrista/AliPhysics,fcolamar/AliPhysics,fcolamar/AliPhysics,victor-gonzalez/AliPhysics,nschmidtALICE/AliPhysics,rihanphys/AliPhysics,victor-gonzalez/AliPhysics,nschmidtALICE/AliPhysics,alisw/AliPhysics,alisw/AliPhysics,rbailhac/AliPhysics
|
95b85bd1ba98141c9ec70a4593eaf4671347e472
|
tests/AAClipTest.cpp
|
tests/AAClipTest.cpp
|
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkAAClip.h"
#include "SkPath.h"
#include "SkRandom.h"
static const SkRegion::Op gRgnOps[] = {
SkRegion::kDifference_Op,
SkRegion::kIntersect_Op,
SkRegion::kUnion_Op,
SkRegion::kXOR_Op,
SkRegion::kReverseDifference_Op,
SkRegion::kReplace_Op
};
static const char* gRgnOpNames[] = {
"DIFF", "INTERSECT", "UNION", "XOR", "REVERSE_DIFF", "REPLACE"
};
static void imoveTo(SkPath& path, int x, int y) {
path.moveTo(SkIntToScalar(x), SkIntToScalar(y));
}
static void icubicTo(SkPath& path, int x0, int y0, int x1, int y1, int x2, int y2) {
path.cubicTo(SkIntToScalar(x0), SkIntToScalar(y0),
SkIntToScalar(x1), SkIntToScalar(y1),
SkIntToScalar(x2), SkIntToScalar(y2));
}
static void test_path_bounds(skiatest::Reporter* reporter) {
SkPath path;
SkAAClip clip;
const int height = 40;
const SkScalar sheight = SkIntToScalar(height);
path.addOval(SkRect::MakeWH(sheight, sheight));
REPORTER_ASSERT(reporter, sheight == path.getBounds().height());
clip.setPath(path, NULL, true);
REPORTER_ASSERT(reporter, height == clip.getBounds().height());
// this is the trimmed height of this cubic (with aa). The critical thing
// for this test is that it is less than height, which represents just
// the bounds of the path's control-points.
//
// This used to fail until we tracked the MinY in the BuilderBlitter.
//
const int teardrop_height = 12;
path.reset();
imoveTo(path, 0, 20);
icubicTo(path, 40, 40, 40, 0, 0, 20);
REPORTER_ASSERT(reporter, sheight == path.getBounds().height());
clip.setPath(path, NULL, true);
REPORTER_ASSERT(reporter, teardrop_height == clip.getBounds().height());
}
static void test_empty(skiatest::Reporter* reporter) {
SkAAClip clip0, clip1;
REPORTER_ASSERT(reporter, clip0.isEmpty());
REPORTER_ASSERT(reporter, clip0.getBounds().isEmpty());
REPORTER_ASSERT(reporter, clip1 == clip0);
clip0.translate(10, 10); // should have no effect on empty
REPORTER_ASSERT(reporter, clip0.isEmpty());
REPORTER_ASSERT(reporter, clip0.getBounds().isEmpty());
REPORTER_ASSERT(reporter, clip1 == clip0);
SkIRect r = { 10, 10, 40, 50 };
clip0.setRect(r);
REPORTER_ASSERT(reporter, !clip0.isEmpty());
REPORTER_ASSERT(reporter, !clip0.getBounds().isEmpty());
REPORTER_ASSERT(reporter, clip0 != clip1);
REPORTER_ASSERT(reporter, clip0.getBounds() == r);
clip0.setEmpty();
REPORTER_ASSERT(reporter, clip0.isEmpty());
REPORTER_ASSERT(reporter, clip0.getBounds().isEmpty());
REPORTER_ASSERT(reporter, clip1 == clip0);
SkMask mask;
mask.fImage = NULL;
clip0.copyToMask(&mask);
REPORTER_ASSERT(reporter, NULL == mask.fImage);
REPORTER_ASSERT(reporter, mask.fBounds.isEmpty());
}
static void rand_irect(SkIRect* r, int N, SkRandom& rand) {
r->setXYWH(0, 0, rand.nextU() % N, rand.nextU() % N);
int dx = rand.nextU() % (2*N);
int dy = rand.nextU() % (2*N);
// use int dx,dy to make the subtract be signed
r->offset(N - dx, N - dy);
}
static void test_irect(skiatest::Reporter* reporter) {
SkRandom rand;
for (int i = 0; i < 10000; i++) {
SkAAClip clip0, clip1;
SkRegion rgn0, rgn1;
SkIRect r0, r1;
rand_irect(&r0, 10, rand);
rand_irect(&r1, 10, rand);
clip0.setRect(r0);
clip1.setRect(r1);
rgn0.setRect(r0);
rgn1.setRect(r1);
for (size_t j = 0; j < SK_ARRAY_COUNT(gRgnOps); ++j) {
SkRegion::Op op = gRgnOps[j];
SkAAClip clip2;
SkRegion rgn2;
bool nonEmptyAA = clip2.op(clip0, clip1, op);
bool nonEmptyBW = rgn2.op(rgn0, rgn1, op);
if (nonEmptyAA != nonEmptyBW || clip2.getBounds() != rgn2.getBounds()) {
SkDebugf("[%d %d %d %d] %s [%d %d %d %d] = BW:[%d %d %d %d] AA:[%d %d %d %d]\n",
r0.fLeft, r0.fTop, r0.right(), r0.bottom(),
gRgnOpNames[j],
r1.fLeft, r1.fTop, r1.right(), r1.bottom(),
rgn2.getBounds().fLeft, rgn2.getBounds().fTop,
rgn2.getBounds().right(), rgn2.getBounds().bottom(),
clip2.getBounds().fLeft, clip2.getBounds().fTop,
clip2.getBounds().right(), clip2.getBounds().bottom());
}
REPORTER_ASSERT(reporter, nonEmptyAA == nonEmptyBW);
REPORTER_ASSERT(reporter, clip2.getBounds() == rgn2.getBounds());
}
}
}
static void TestAAClip(skiatest::Reporter* reporter) {
test_empty(reporter);
test_path_bounds(reporter);
test_irect(reporter);
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("AAClip", AAClipTestClass, TestAAClip)
|
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkAAClip.h"
#include "SkCanvas.h"
#include "SkMask.h"
#include "SkPath.h"
#include "SkRandom.h"
static bool operator==(const SkMask& a, const SkMask& b) {
if (a.fFormat != b.fFormat || a.fBounds != b.fBounds) {
return false;
}
if (!a.fImage && !b.fImage) {
return true;
}
if (!a.fImage || !b.fImage) {
return false;
}
size_t wbytes = a.fBounds.width();
switch (a.fFormat) {
case SkMask::kBW_Format:
wbytes = (wbytes + 7) >> 3;
break;
case SkMask::kA8_Format:
case SkMask::k3D_Format:
break;
case SkMask::kLCD16_Format:
wbytes <<= 1;
break;
case SkMask::kLCD32_Format:
case SkMask::kARGB32_Format:
wbytes <<= 2;
break;
default:
SkASSERT(!"unknown mask format");
return false;
}
const int h = a.fBounds.height();
const char* aptr = (const char*)a.fImage;
const char* bptr = (const char*)b.fImage;
for (int y = 0; y < h; ++y) {
if (memcmp(aptr, bptr, wbytes)) {
return false;
}
aptr += wbytes;
bptr += wbytes;
}
return true;
}
static void copyToMask(const SkRegion& rgn, SkMask* mask) {
if (rgn.isEmpty()) {
mask->fImage = NULL;
mask->fBounds.setEmpty();
mask->fRowBytes = 0;
return;
}
mask->fBounds = rgn.getBounds();
mask->fRowBytes = mask->fBounds.width();
mask->fFormat = SkMask::kA8_Format;
mask->fImage = SkMask::AllocImage(mask->computeImageSize());
sk_bzero(mask->fImage, mask->computeImageSize());
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kA8_Config, mask->fBounds.width(),
mask->fBounds.height(), mask->fRowBytes);
bitmap.setPixels(mask->fImage);
// canvas expects its coordinate system to always be 0,0 in the top/left
// so we translate the rgn to match that before drawing into the mask.
//
SkRegion tmpRgn(rgn);
tmpRgn.translate(-rgn.getBounds().fLeft, -rgn.getBounds().fTop);
SkCanvas canvas(bitmap);
canvas.clipRegion(tmpRgn);
canvas.drawColor(SK_ColorBLACK);
}
static SkIRect rand_rect(SkRandom& rand, int n) {
int x = rand.nextS() % n;
int y = rand.nextS() % n;
int w = rand.nextU() % n;
int h = rand.nextU() % n;
return SkIRect::MakeXYWH(x, y, w, h);
}
static void make_rand_rgn(SkRegion* rgn, SkRandom& rand) {
int count = rand.nextU() % 20;
for (int i = 0; i < count; ++i) {
rgn->op(rand_rect(rand, 100), SkRegion::kXOR_Op);
}
}
// aaclip.setRegion should create idential masks to the region
static void test_rgn(skiatest::Reporter* reporter) {
SkRandom rand;
for (int i = 0; i < 1000; i++) {
SkRegion rgn;
make_rand_rgn(&rgn, rand);
SkMask mask0;
copyToMask(rgn, &mask0);
SkAAClip aaclip;
aaclip.setRegion(rgn);
SkMask mask1;
aaclip.copyToMask(&mask1);
REPORTER_ASSERT(reporter, mask0 == mask1);
SkMask::FreeImage(mask0.fImage);
SkMask::FreeImage(mask1.fImage);
}
}
static const SkRegion::Op gRgnOps[] = {
SkRegion::kDifference_Op,
SkRegion::kIntersect_Op,
SkRegion::kUnion_Op,
SkRegion::kXOR_Op,
SkRegion::kReverseDifference_Op,
SkRegion::kReplace_Op
};
static const char* gRgnOpNames[] = {
"DIFF", "INTERSECT", "UNION", "XOR", "REVERSE_DIFF", "REPLACE"
};
static void imoveTo(SkPath& path, int x, int y) {
path.moveTo(SkIntToScalar(x), SkIntToScalar(y));
}
static void icubicTo(SkPath& path, int x0, int y0, int x1, int y1, int x2, int y2) {
path.cubicTo(SkIntToScalar(x0), SkIntToScalar(y0),
SkIntToScalar(x1), SkIntToScalar(y1),
SkIntToScalar(x2), SkIntToScalar(y2));
}
static void test_path_bounds(skiatest::Reporter* reporter) {
SkPath path;
SkAAClip clip;
const int height = 40;
const SkScalar sheight = SkIntToScalar(height);
path.addOval(SkRect::MakeWH(sheight, sheight));
REPORTER_ASSERT(reporter, sheight == path.getBounds().height());
clip.setPath(path, NULL, true);
REPORTER_ASSERT(reporter, height == clip.getBounds().height());
// this is the trimmed height of this cubic (with aa). The critical thing
// for this test is that it is less than height, which represents just
// the bounds of the path's control-points.
//
// This used to fail until we tracked the MinY in the BuilderBlitter.
//
const int teardrop_height = 12;
path.reset();
imoveTo(path, 0, 20);
icubicTo(path, 40, 40, 40, 0, 0, 20);
REPORTER_ASSERT(reporter, sheight == path.getBounds().height());
clip.setPath(path, NULL, true);
REPORTER_ASSERT(reporter, teardrop_height == clip.getBounds().height());
}
static void test_empty(skiatest::Reporter* reporter) {
SkAAClip clip0, clip1;
REPORTER_ASSERT(reporter, clip0.isEmpty());
REPORTER_ASSERT(reporter, clip0.getBounds().isEmpty());
REPORTER_ASSERT(reporter, clip1 == clip0);
clip0.translate(10, 10); // should have no effect on empty
REPORTER_ASSERT(reporter, clip0.isEmpty());
REPORTER_ASSERT(reporter, clip0.getBounds().isEmpty());
REPORTER_ASSERT(reporter, clip1 == clip0);
SkIRect r = { 10, 10, 40, 50 };
clip0.setRect(r);
REPORTER_ASSERT(reporter, !clip0.isEmpty());
REPORTER_ASSERT(reporter, !clip0.getBounds().isEmpty());
REPORTER_ASSERT(reporter, clip0 != clip1);
REPORTER_ASSERT(reporter, clip0.getBounds() == r);
clip0.setEmpty();
REPORTER_ASSERT(reporter, clip0.isEmpty());
REPORTER_ASSERT(reporter, clip0.getBounds().isEmpty());
REPORTER_ASSERT(reporter, clip1 == clip0);
SkMask mask;
mask.fImage = NULL;
clip0.copyToMask(&mask);
REPORTER_ASSERT(reporter, NULL == mask.fImage);
REPORTER_ASSERT(reporter, mask.fBounds.isEmpty());
}
static void rand_irect(SkIRect* r, int N, SkRandom& rand) {
r->setXYWH(0, 0, rand.nextU() % N, rand.nextU() % N);
int dx = rand.nextU() % (2*N);
int dy = rand.nextU() % (2*N);
// use int dx,dy to make the subtract be signed
r->offset(N - dx, N - dy);
}
static void test_irect(skiatest::Reporter* reporter) {
SkRandom rand;
for (int i = 0; i < 10000; i++) {
SkAAClip clip0, clip1;
SkRegion rgn0, rgn1;
SkIRect r0, r1;
rand_irect(&r0, 10, rand);
rand_irect(&r1, 10, rand);
clip0.setRect(r0);
clip1.setRect(r1);
rgn0.setRect(r0);
rgn1.setRect(r1);
for (size_t j = 0; j < SK_ARRAY_COUNT(gRgnOps); ++j) {
SkRegion::Op op = gRgnOps[j];
SkAAClip clip2;
SkRegion rgn2;
bool nonEmptyAA = clip2.op(clip0, clip1, op);
bool nonEmptyBW = rgn2.op(rgn0, rgn1, op);
if (nonEmptyAA != nonEmptyBW || clip2.getBounds() != rgn2.getBounds()) {
SkDebugf("[%d %d %d %d] %s [%d %d %d %d] = BW:[%d %d %d %d] AA:[%d %d %d %d]\n",
r0.fLeft, r0.fTop, r0.right(), r0.bottom(),
gRgnOpNames[j],
r1.fLeft, r1.fTop, r1.right(), r1.bottom(),
rgn2.getBounds().fLeft, rgn2.getBounds().fTop,
rgn2.getBounds().right(), rgn2.getBounds().bottom(),
clip2.getBounds().fLeft, clip2.getBounds().fTop,
clip2.getBounds().right(), clip2.getBounds().bottom());
}
REPORTER_ASSERT(reporter, nonEmptyAA == nonEmptyBW);
REPORTER_ASSERT(reporter, clip2.getBounds() == rgn2.getBounds());
}
}
}
static void TestAAClip(skiatest::Reporter* reporter) {
test_empty(reporter);
test_path_bounds(reporter);
test_irect(reporter);
test_rgn(reporter);
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("AAClip", AAClipTestClass, TestAAClip)
|
add test that aaclip.setRegion creates the same mask as the region ... in prep for optimizatin work on setRegion.
|
add test that aaclip.setRegion creates the same mask as the region
... in prep for optimizatin work on setRegion.
git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@2739 2bbb7eff-a529-9590-31e7-b0007b416f81
|
C++
|
bsd-3-clause
|
chenlian2015/skia_from_google,HalCanary/skia-hc,geekboxzone/mmallow_external_skia,TeamTwisted/external_skia,mozilla-b2g/external_skia,codeaurora-unoffical/platform-external-skia,MonkeyZZZZ/platform_external_skia,PAC-ROM/android_external_skia,F-AOSP/platform_external_skia,pacerom/external_skia,F-AOSP/platform_external_skia,MyAOSP/external_chromium_org_third_party_skia,DiamondLovesYou/skia-sys,PAC-ROM/android_external_skia,MinimalOS-AOSP/platform_external_skia,TeamExodus/external_skia,Igalia/skia,mozilla-b2g/external_skia,pacerom/external_skia,DiamondLovesYou/skia-sys,RadonX-ROM/external_skia,qrealka/skia-hc,AOSP-YU/platform_external_skia,suyouxin/android_external_skia,Android-AOSP/external_skia,sudosurootdev/external_skia,Samsung/skia,android-ia/platform_external_chromium_org_third_party_skia,MarshedOut/android_external_skia,sombree/android_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,Infinitive-OS/platform_external_skia,MIPS/external-chromium_org-third_party-skia,ench0/external_chromium_org_third_party_skia,vanish87/skia,tmpvar/skia.cc,FusionSP/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,NamelessRom/android_external_skia,larsbergstrom/skia,ctiao/platform-external-skia,rubenvb/skia,tmpvar/skia.cc,Fusion-Rom/external_chromium_org_third_party_skia,NamelessRom/android_external_skia,TeslaProject/external_skia,Android-AOSP/external_skia,TeslaProject/external_skia,OneRom/external_skia,AOSPU/external_chromium_org_third_party_skia,Jichao/skia,boulzordev/android_external_skia,HealthyHoney/temasek_SKIA,jtg-gg/skia,UBERMALLOW/external_skia,Pure-Aosp/android_external_skia,PAC-ROM/android_external_skia,google/skia,Pure-Aosp/android_external_skia,Euphoria-OS-Legacy/android_external_skia,Tesla-Redux/android_external_skia,mmatyas/skia,nox/skia,Android-AOSP/external_skia,ench0/external_chromium_org_third_party_skia,FusionSP/external_chromium_org_third_party_skia,BrokenROM/external_skia,geekboxzone/mmallow_external_skia,temasek/android_external_skia,MinimalOS/external_skia,F-AOSP/platform_external_skia,Igalia/skia,MIPS/external-chromium_org-third_party-skia,Purity-Lollipop/platform_external_skia,akiss77/skia,Hikari-no-Tenshi/android_external_skia,noselhq/skia,MinimalOS-AOSP/platform_external_skia,invisiblek/android_external_skia,MarshedOut/android_external_skia,Asteroid-Project/android_external_skia,TeamExodus/external_skia,ench0/external_skia,scroggo/skia,MinimalOS/external_chromium_org_third_party_skia,mydongistiny/external_chromium_org_third_party_skia,Asteroid-Project/android_external_skia,scroggo/skia,DARKPOP/external_chromium_org_third_party_skia,Samsung/skia,Asteroid-Project/android_external_skia,HealthyHoney/temasek_SKIA,wildermason/external_skia,w3nd1go/android_external_skia,aospo/platform_external_skia,geekboxzone/lollipop_external_skia,sigysmund/platform_external_skia,nfxosp/platform_external_skia,google/skia,rubenvb/skia,geekboxzone/lollipop_external_skia,android-ia/platform_external_skia,MyAOSP/external_chromium_org_third_party_skia,vanish87/skia,timduru/platform-external-skia,TeamTwisted/external_skia,Igalia/skia,InfinitiveOS/external_skia,Infusion-OS/android_external_skia,Euphoria-OS-Legacy/android_external_skia,PAC-ROM/android_external_skia,w3nd1go/android_external_skia,rubenvb/skia,TeslaOS/android_external_skia,VRToxin-AOSP/android_external_skia,HalCanary/skia-hc,TeslaProject/external_skia,sombree/android_external_skia,mmatyas/skia,vanish87/skia,android-ia/platform_external_skia,timduru/platform-external-skia,geekboxzone/mmallow_external_skia,nfxosp/platform_external_skia,Omegaphora/external_skia,Omegaphora/external_chromium_org_third_party_skia,InfinitiveOS/external_skia,AsteroidOS/android_external_skia,TeslaOS/android_external_skia,BrokenROM/external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,MinimalOS/external_chromium_org_third_party_skia,vvuk/skia,FusionSP/external_chromium_org_third_party_skia,akiss77/skia,HealthyHoney/temasek_SKIA,codeaurora-unoffical/platform-external-skia,VRToxin-AOSP/android_external_skia,Plain-Andy/android_platform_external_skia,mmatyas/skia,Android-AOSP/external_skia,qrealka/skia-hc,todotodoo/skia,Asteroid-Project/android_external_skia,Khaon/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,mozilla-b2g/external_skia,RadonX-ROM/external_skia,InfinitiveOS/external_skia,Khaon/android_external_skia,AndroidOpenDevelopment/android_external_skia,nvoron23/skia,Euphoria-OS-Legacy/android_external_skia,mydongistiny/android_external_skia,MinimalOS/android_external_skia,w3nd1go/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,temasek/android_external_skia,Samsung/skia,ench0/external_chromium_org_third_party_skia,DesolationStaging/android_external_skia,nvoron23/skia,RadonX-ROM/external_skia,Omegaphora/external_chromium_org_third_party_skia,vanish87/skia,TeamEOS/external_chromium_org_third_party_skia,ominux/skia,SlimSaber/android_external_skia,OptiPop/external_chromium_org_third_party_skia,Android-AOSP/external_skia,MarshedOut/android_external_skia,shahrzadmn/skia,sigysmund/platform_external_skia,xzzz9097/android_external_skia,TeamTwisted/external_skia,geekboxzone/mmallow_external_skia,boulzordev/android_external_skia,Infinitive-OS/platform_external_skia,google/skia,HalCanary/skia-hc,MonkeyZZZZ/platform_external_skia,Omegaphora/external_skia,Plain-Andy/android_platform_external_skia,YUPlayGodDev/platform_external_skia,sudosurootdev/external_skia,F-AOSP/platform_external_skia,zhaochengw/platform_external_skia,nfxosp/platform_external_skia,xzzz9097/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,scroggo/skia,fire855/android_external_skia,HalCanary/skia-hc,chenlian2015/skia_from_google,scroggo/skia,xzzz9097/android_external_skia,Hikari-no-Tenshi/android_external_skia,tmpvar/skia.cc,OptiPop/external_skia,larsbergstrom/skia,MIPS/external-chromium_org-third_party-skia,w3nd1go/android_external_skia,MinimalOS/external_skia,jtg-gg/skia,timduru/platform-external-skia,Hybrid-Rom/external_skia,scroggo/skia,Hybrid-Rom/external_skia,fire855/android_external_skia,google/skia,TeslaProject/external_skia,temasek/android_external_skia,TeamTwisted/external_skia,amyvmiwei/skia,NamelessRom/android_external_skia,xzzz9097/android_external_skia,ctiao/platform-external-skia,FusionSP/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,todotodoo/skia,xin3liang/platform_external_chromium_org_third_party_skia,OptiPop/external_skia,Hikari-no-Tenshi/android_external_skia,MarshedOut/android_external_skia,ench0/external_skia,ench0/external_chromium_org_third_party_skia,fire855/android_external_skia,TeslaProject/external_skia,AOSPB/external_skia,scroggo/skia,BrokenROM/external_skia,houst0nn/external_skia,F-AOSP/platform_external_skia,aosp-mirror/platform_external_skia,nox/skia,Omegaphora/external_chromium_org_third_party_skia,FusionSP/android_external_skia,SlimSaber/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,chenlian2015/skia_from_google,HalCanary/skia-hc,Fusion-Rom/external_chromium_org_third_party_skia,aospo/platform_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,AsteroidOS/android_external_skia,MinimalOS/external_skia,scroggo/skia,w3nd1go/android_external_skia,pcwalton/skia,xzzz9097/android_external_skia,mozilla-b2g/external_skia,VentureROM-L/android_external_skia,MinimalOS/android_external_skia,ench0/external_chromium_org_third_party_skia,xin3liang/platform_external_chromium_org_third_party_skia,wildermason/external_skia,AndroidOpenDevelopment/android_external_skia,InfinitiveOS/external_skia,AOSPA-L/android_external_skia,GladeRom/android_external_skia,YUPlayGodDev/platform_external_skia,MonkeyZZZZ/platform_external_skia,MinimalOS-AOSP/platform_external_skia,noselhq/skia,BrokenROM/external_skia,amyvmiwei/skia,CyanogenMod/android_external_chromium_org_third_party_skia,chenlian2015/skia_from_google,rubenvb/skia,Infusion-OS/android_external_skia,Omegaphora/external_chromium_org_third_party_skia,AsteroidOS/android_external_skia,Hybrid-Rom/external_skia,vanish87/skia,AndroidOpenDevelopment/android_external_skia,DiamondLovesYou/skia-sys,qrealka/skia-hc,android-ia/platform_external_chromium_org_third_party_skia,tmpvar/skia.cc,OptiPop/external_skia,MinimalOS/android_external_chromium_org_third_party_skia,vvuk/skia,AOSPA-L/android_external_skia,MinimalOS/external_skia,Hybrid-Rom/external_skia,rubenvb/skia,ench0/external_skia,byterom/android_external_skia,Plain-Andy/android_platform_external_skia,noselhq/skia,MinimalOS-AOSP/platform_external_skia,android-ia/platform_external_skia,Khaon/android_external_skia,geekboxzone/mmallow_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,sudosurootdev/external_skia,spezi77/android_external_skia,fire855/android_external_skia,jtg-gg/skia,ench0/external_chromium_org_third_party_skia,Infusion-OS/android_external_skia,rubenvb/skia,houst0nn/external_skia,TeslaProject/external_skia,F-AOSP/platform_external_skia,GladeRom/android_external_skia,Fusion-Rom/android_external_skia,tmpvar/skia.cc,nfxosp/platform_external_skia,android-ia/platform_external_chromium_org_third_party_skia,fire855/android_external_skia,ominux/skia,FusionSP/android_external_skia,Hikari-no-Tenshi/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,InfinitiveOS/external_skia,wildermason/external_skia,Plain-Andy/android_platform_external_skia,TeslaProject/external_skia,todotodoo/skia,TeslaOS/android_external_skia,invisiblek/android_external_skia,TeamExodus/external_skia,MIPS/external-chromium_org-third_party-skia,OneRom/external_skia,Fusion-Rom/android_external_skia,Khaon/android_external_skia,Samsung/skia,google/skia,sudosurootdev/external_skia,Purity-Lollipop/platform_external_skia,wildermason/external_skia,Fusion-Rom/android_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,Euphoria-OS-Legacy/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,jtg-gg/skia,TeslaOS/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,suyouxin/android_external_skia,AOSPU/external_chromium_org_third_party_skia,AOSP-YU/platform_external_skia,pacerom/external_skia,AOSPB/external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,Infinitive-OS/platform_external_skia,nfxosp/platform_external_skia,wildermason/external_skia,AndroidOpenDevelopment/android_external_skia,GladeRom/android_external_skia,nox/skia,OptiPop/external_chromium_org_third_party_skia,AOSP-YU/platform_external_skia,aospo/platform_external_skia,zhaochengw/platform_external_skia,vvuk/skia,NamelessRom/android_external_skia,suyouxin/android_external_skia,Infinitive-OS/platform_external_skia,pcwalton/skia,Hikari-no-Tenshi/android_external_skia,codeaurora-unoffical/platform-external-skia,MonkeyZZZZ/platform_external_skia,UBERMALLOW/external_skia,codeaurora-unoffical/platform-external-skia,FusionSP/android_external_skia,MyAOSP/external_chromium_org_third_party_skia,AOSPA-L/android_external_skia,MonkeyZZZZ/platform_external_skia,SlimSaber/android_external_skia,ominux/skia,pcwalton/skia,larsbergstrom/skia,Hikari-no-Tenshi/android_external_skia,Pure-Aosp/android_external_skia,FusionSP/external_chromium_org_third_party_skia,AOSPB/external_skia,OneRom/external_skia,ench0/external_skia,geekboxzone/lollipop_external_skia,TeamBliss-LP/android_external_skia,TeamExodus/external_skia,Android-AOSP/external_skia,MinimalOS-AOSP/platform_external_skia,FusionSP/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,AOSP-YU/platform_external_skia,MinimalOS-AOSP/platform_external_skia,Fusion-Rom/android_external_skia,invisiblek/android_external_skia,OptiPop/external_skia,temasek/android_external_skia,geekboxzone/mmallow_external_skia,Jichao/skia,RadonX-ROM/external_skia,MinimalOS-AOSP/platform_external_skia,sigysmund/platform_external_skia,nvoron23/skia,AsteroidOS/android_external_skia,TeslaOS/android_external_skia,samuelig/skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,Jichao/skia,sudosurootdev/external_skia,sigysmund/platform_external_skia,nfxosp/platform_external_skia,sudosurootdev/external_skia,aosp-mirror/platform_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,byterom/android_external_skia,fire855/android_external_skia,AOSPA-L/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,FusionSP/external_chromium_org_third_party_skia,TeamExodus/external_skia,DesolationStaging/android_external_skia,OptiPop/external_skia,fire855/android_external_skia,samuelig/skia,TeamEOS/external_chromium_org_third_party_skia,Jichao/skia,todotodoo/skia,wildermason/external_skia,boulzordev/android_external_skia,mmatyas/skia,GladeRom/android_external_skia,scroggo/skia,Tesla-Redux/android_external_skia,chenlian2015/skia_from_google,OneRom/external_skia,tmpvar/skia.cc,jtg-gg/skia,MarshedOut/android_external_skia,codeaurora-unoffical/platform-external-skia,temasek/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,OptiPop/external_chromium_org_third_party_skia,VRToxin-AOSP/android_external_skia,BrokenROM/external_skia,TeamTwisted/external_skia,MinimalOS/android_external_chromium_org_third_party_skia,invisiblek/android_external_skia,Khaon/android_external_skia,MinimalOS/external_skia,noselhq/skia,ctiao/platform-external-skia,Hikari-no-Tenshi/android_external_skia,RadonX-ROM/external_skia,ctiao/platform-external-skia,noselhq/skia,akiss77/skia,boulzordev/android_external_skia,ominux/skia,akiss77/skia,UBERMALLOW/external_skia,TeamEOS/external_skia,Pure-Aosp/android_external_skia,MinimalOS/android_external_skia,nfxosp/platform_external_skia,TeamEOS/external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,zhaochengw/platform_external_skia,FusionSP/external_chromium_org_third_party_skia,MinimalOS/android_external_chromium_org_third_party_skia,nox/skia,Omegaphora/external_skia,Fusion-Rom/external_chromium_org_third_party_skia,spezi77/android_external_skia,amyvmiwei/skia,HealthyHoney/temasek_SKIA,jtg-gg/skia,AOSPU/external_chromium_org_third_party_skia,Jichao/skia,google/skia,sombree/android_external_skia,MarshedOut/android_external_skia,Infinitive-OS/platform_external_skia,OneRom/external_skia,houst0nn/external_skia,TeamBliss-LP/android_external_skia,nox/skia,Pure-Aosp/android_external_skia,Hybrid-Rom/external_skia,AOSP-YU/platform_external_skia,HealthyHoney/temasek_SKIA,DiamondLovesYou/skia-sys,ominux/skia,Infusion-OS/android_external_skia,invisiblek/android_external_skia,mydongistiny/android_external_skia,ench0/external_chromium_org_third_party_skia,ench0/external_skia,xin3liang/platform_external_chromium_org_third_party_skia,jtg-gg/skia,noselhq/skia,tmpvar/skia.cc,mmatyas/skia,AsteroidOS/android_external_skia,Asteroid-Project/android_external_skia,VentureROM-L/android_external_skia,ench0/external_skia,Euphoria-OS-Legacy/android_external_skia,sombree/android_external_skia,TeamExodus/external_skia,timduru/platform-external-skia,Tesla-Redux/android_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,VRToxin-AOSP/android_external_skia,AOSPB/external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,mmatyas/skia,InfinitiveOS/external_skia,suyouxin/android_external_skia,UBERMALLOW/external_skia,TeamExodus/external_skia,OptiPop/external_chromium_org_third_party_skia,aospo/platform_external_skia,YUPlayGodDev/platform_external_skia,InfinitiveOS/external_skia,AsteroidOS/android_external_skia,aosp-mirror/platform_external_skia,TeamEOS/external_skia,BrokenROM/external_skia,Fusion-Rom/android_external_skia,mydongistiny/android_external_skia,TeamTwisted/external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,akiss77/skia,Purity-Lollipop/platform_external_skia,Igalia/skia,qrealka/skia-hc,HalCanary/skia-hc,TeslaOS/android_external_skia,android-ia/platform_external_chromium_org_third_party_skia,geekboxzone/lollipop_external_skia,spezi77/android_external_skia,YUPlayGodDev/platform_external_skia,TeamExodus/external_skia,YUPlayGodDev/platform_external_skia,Omegaphora/external_chromium_org_third_party_skia,HealthyHoney/temasek_SKIA,qrealka/skia-hc,byterom/android_external_skia,w3nd1go/android_external_skia,sombree/android_external_skia,nox/skia,TeamEOS/external_chromium_org_third_party_skia,shahrzadmn/skia,TeslaOS/android_external_skia,pcwalton/skia,AOSPA-L/android_external_skia,PAC-ROM/android_external_skia,codeaurora-unoffical/platform-external-skia,vvuk/skia,Tesla-Redux/android_external_skia,byterom/android_external_skia,temasek/android_external_skia,wildermason/external_skia,amyvmiwei/skia,Pure-Aosp/android_external_skia,akiss77/skia,TeamBliss-LP/android_external_skia,Tesla-Redux/android_external_skia,FusionSP/android_external_skia,todotodoo/skia,qrealka/skia-hc,SlimSaber/android_external_skia,mozilla-b2g/external_skia,MinimalOS/external_skia,ominux/skia,VentureROM-L/android_external_skia,AndroidOpenDevelopment/android_external_skia,larsbergstrom/skia,AOSP-YU/platform_external_skia,AOSPA-L/android_external_skia,Omegaphora/external_skia,mozilla-b2g/external_skia,todotodoo/skia,spezi77/android_external_skia,mmatyas/skia,YUPlayGodDev/platform_external_skia,codeaurora-unoffical/platform-external-skia,HalCanary/skia-hc,MIPS/external-chromium_org-third_party-skia,MinimalOS/external_skia,VentureROM-L/android_external_skia,MonkeyZZZZ/platform_external_skia,VentureROM-L/android_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,akiss77/skia,akiss77/skia,geekboxzone/mmallow_external_skia,TeamEOS/external_skia,larsbergstrom/skia,VRToxin-AOSP/android_external_skia,AOSPB/external_skia,mmatyas/skia,sigysmund/platform_external_skia,TeamEOS/external_chromium_org_third_party_skia,MinimalOS-AOSP/platform_external_skia,mydongistiny/android_external_skia,Purity-Lollipop/platform_external_skia,sombree/android_external_skia,HalCanary/skia-hc,nox/skia,xzzz9097/android_external_skia,geekboxzone/lollipop_external_skia,Samsung/skia,aosp-mirror/platform_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,OptiPop/external_skia,timduru/platform-external-skia,SlimSaber/android_external_skia,amyvmiwei/skia,geekboxzone/lollipop_external_skia,TeamEOS/external_skia,mydongistiny/android_external_skia,Purity-Lollipop/platform_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,Purity-Lollipop/platform_external_skia,invisiblek/android_external_skia,aospo/platform_external_skia,Infinitive-OS/platform_external_skia,Tesla-Redux/android_external_skia,DiamondLovesYou/skia-sys,BrokenROM/external_skia,DiamondLovesYou/skia-sys,MinimalOS/android_external_chromium_org_third_party_skia,zhaochengw/platform_external_skia,android-ia/platform_external_chromium_org_third_party_skia,mmatyas/skia,Purity-Lollipop/platform_external_skia,tmpvar/skia.cc,mydongistiny/external_chromium_org_third_party_skia,MinimalOS/android_external_skia,houst0nn/external_skia,google/skia,Hybrid-Rom/external_skia,OptiPop/external_chromium_org_third_party_skia,vanish87/skia,ench0/external_skia,FusionSP/external_chromium_org_third_party_skia,shahrzadmn/skia,MyAOSP/external_chromium_org_third_party_skia,OneRom/external_skia,Khaon/android_external_skia,Fusion-Rom/android_external_skia,MinimalOS-AOSP/platform_external_skia,w3nd1go/android_external_skia,SlimSaber/android_external_skia,w3nd1go/android_external_skia,Plain-Andy/android_platform_external_skia,AsteroidOS/android_external_skia,HealthyHoney/temasek_SKIA,Infusion-OS/android_external_skia,PAC-ROM/android_external_skia,Omegaphora/external_skia,AOSPU/external_chromium_org_third_party_skia,AOSPA-L/android_external_skia,AOSPU/external_chromium_org_third_party_skia,vvuk/skia,geekboxzone/mmallow_external_skia,google/skia,codeaurora-unoffical/platform-external-skia,Asteroid-Project/android_external_skia,MonkeyZZZZ/platform_external_skia,Android-AOSP/external_skia,Tesla-Redux/android_external_skia,Infinitive-OS/platform_external_skia,MarshedOut/android_external_skia,Omegaphora/external_skia,Hybrid-Rom/external_skia,TeslaProject/external_skia,Pure-Aosp/android_external_skia,DesolationStaging/android_external_skia,Samsung/skia,aosp-mirror/platform_external_skia,vvuk/skia,SlimSaber/android_external_skia,Samsung/skia,MyAOSP/external_chromium_org_third_party_skia,AOSPB/external_skia,Fusion-Rom/android_external_skia,larsbergstrom/skia,F-AOSP/platform_external_skia,Infusion-OS/android_external_skia,TeamEOS/external_skia,todotodoo/skia,android-ia/platform_external_chromium_org_third_party_skia,vvuk/skia,OptiPop/external_skia,Hikari-no-Tenshi/android_external_skia,GladeRom/android_external_skia,AndroidOpenDevelopment/android_external_skia,larsbergstrom/skia,samuelig/skia,android-ia/platform_external_skia,todotodoo/skia,Omegaphora/external_chromium_org_third_party_skia,sudosurootdev/external_skia,UBERMALLOW/external_skia,MarshedOut/android_external_skia,VentureROM-L/android_external_skia,geekboxzone/lollipop_external_skia,pacerom/external_skia,AndroidOpenDevelopment/android_external_skia,pcwalton/skia,vanish87/skia,Asteroid-Project/android_external_skia,Hybrid-Rom/external_skia,nvoron23/skia,CyanogenMod/android_external_chromium_org_third_party_skia,samuelig/skia,MonkeyZZZZ/platform_external_skia,Khaon/android_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,TeamEOS/external_skia,Omegaphora/external_skia,nfxosp/platform_external_skia,TeamBliss-LP/android_external_skia,pcwalton/skia,vanish87/skia,android-ia/platform_external_skia,nvoron23/skia,suyouxin/android_external_skia,boulzordev/android_external_skia,mydongistiny/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,BrokenROM/external_skia,Khaon/android_external_skia,wildermason/external_skia,aospo/platform_external_skia,Purity-Lollipop/platform_external_skia,UBERMALLOW/external_skia,Asteroid-Project/android_external_skia,mozilla-b2g/external_skia,AOSPB/external_skia,chenlian2015/skia_from_google,vvuk/skia,Plain-Andy/android_platform_external_skia,MinimalOS/android_external_skia,PAC-ROM/android_external_skia,sudosurootdev/external_skia,Omegaphora/external_chromium_org_third_party_skia,AOSPA-L/android_external_skia,aospo/platform_external_skia,GladeRom/android_external_skia,NamelessRom/android_external_skia,VRToxin-AOSP/android_external_skia,Tesla-Redux/android_external_skia,PAC-ROM/android_external_skia,byterom/android_external_skia,pcwalton/skia,zhaochengw/platform_external_skia,google/skia,tmpvar/skia.cc,sigysmund/platform_external_skia,YUPlayGodDev/platform_external_skia,Fusion-Rom/android_external_skia,zhaochengw/platform_external_skia,rubenvb/skia,MarshedOut/android_external_skia,DesolationStaging/android_external_skia,RadonX-ROM/external_skia,MIPS/external-chromium_org-third_party-skia,qrealka/skia-hc,GladeRom/android_external_skia,spezi77/android_external_skia,MyAOSP/external_chromium_org_third_party_skia,Igalia/skia,MonkeyZZZZ/platform_external_skia,w3nd1go/android_external_skia,MinimalOS/android_external_skia,android-ia/platform_external_skia,TeamTwisted/external_skia,Pure-Aosp/android_external_skia,ctiao/platform-external-skia,HealthyHoney/temasek_SKIA,NamelessRom/android_external_skia,fire855/android_external_skia,samuelig/skia,timduru/platform-external-skia,suyouxin/android_external_skia,pcwalton/skia,MinimalOS/android_external_skia,nvoron23/skia,Euphoria-OS-Legacy/android_external_skia,FusionSP/external_chromium_org_third_party_skia,nvoron23/skia,pacerom/external_skia,suyouxin/android_external_skia,GladeRom/android_external_skia,invisiblek/android_external_skia,TeamBliss-LP/android_external_skia,amyvmiwei/skia,AOSP-YU/platform_external_skia,android-ia/platform_external_skia,SlimSaber/android_external_skia,pcwalton/skia,larsbergstrom/skia,mydongistiny/android_external_skia,qrealka/skia-hc,F-AOSP/platform_external_skia,vanish87/skia,MinimalOS/external_chromium_org_third_party_skia,Plain-Andy/android_platform_external_skia,shahrzadmn/skia,samuelig/skia,NamelessRom/android_external_skia,YUPlayGodDev/platform_external_skia,InfinitiveOS/external_skia,Samsung/skia,boulzordev/android_external_skia,zhaochengw/platform_external_skia,OneRom/external_skia,sombree/android_external_skia,OptiPop/external_chromium_org_third_party_skia,boulzordev/android_external_skia,noselhq/skia,aosp-mirror/platform_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,mydongistiny/external_chromium_org_third_party_skia,geekboxzone/lollipop_external_skia,xzzz9097/android_external_skia,mydongistiny/android_external_skia,boulzordev/android_external_skia,TeamEOS/external_chromium_org_third_party_skia,mozilla-b2g/external_skia,TeamTwisted/external_skia,PAC-ROM/android_external_skia,Omegaphora/external_skia,samuelig/skia,VentureROM-L/android_external_skia,spezi77/android_external_skia,ominux/skia,sombree/android_external_skia,DesolationStaging/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,Infusion-OS/android_external_skia,aosp-mirror/platform_external_skia,shahrzadmn/skia,MinimalOS/android_external_chromium_org_third_party_skia,nox/skia,OneRom/external_skia,pacerom/external_skia,houst0nn/external_skia,OptiPop/external_chromium_org_third_party_skia,TeslaOS/android_external_skia,aosp-mirror/platform_external_skia,VentureROM-L/android_external_skia,Jichao/skia,MinimalOS/android_external_chromium_org_third_party_skia,AsteroidOS/android_external_skia,google/skia,Jichao/skia,TeamEOS/external_chromium_org_third_party_skia,houst0nn/external_skia,AOSPB/external_skia,ench0/external_skia,chenlian2015/skia_from_google,houst0nn/external_skia,android-ia/platform_external_chromium_org_third_party_skia,MyAOSP/external_chromium_org_third_party_skia,TeamBliss-LP/android_external_skia,OneRom/external_skia,OptiPop/external_chromium_org_third_party_skia,UBERMALLOW/external_skia,ctiao/platform-external-skia,mydongistiny/external_chromium_org_third_party_skia,shahrzadmn/skia,DesolationStaging/android_external_skia,rubenvb/skia,Jichao/skia,shahrzadmn/skia,FusionSP/external_chromium_org_third_party_skia,AOSPU/external_chromium_org_third_party_skia,AOSPB/external_skia,timduru/platform-external-skia,OptiPop/external_skia,sigysmund/platform_external_skia,DiamondLovesYou/skia-sys,samuelig/skia,VRToxin-AOSP/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,Infinitive-OS/platform_external_skia,byterom/android_external_skia,MinimalOS/external_skia,AOSP-YU/platform_external_skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,ominux/skia,aospo/platform_external_skia,VRToxin-AOSP/android_external_skia,Euphoria-OS-Legacy/android_external_skia,byterom/android_external_skia,Igalia/skia,nox/skia,nvoron23/skia,ominux/skia,noselhq/skia,Omegaphora/external_chromium_org_third_party_skia,UBERMALLOW/external_skia,temasek/android_external_skia,byterom/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,VRToxin-AOSP/android_external_skia,DesolationStaging/android_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,Igalia/skia,DARKPOP/external_chromium_org_third_party_skia,shahrzadmn/skia,geekboxzone/mmallow_external_skia,MIPS/external-chromium_org-third_party-skia,MIPS/external-chromium_org-third_party-skia,DesolationStaging/android_external_skia,amyvmiwei/skia,TeamExodus/external_skia,temasek/android_external_skia,xzzz9097/android_external_skia,TeamEOS/external_chromium_org_third_party_skia,vvuk/skia,shahrzadmn/skia,sigysmund/platform_external_skia,invisiblek/android_external_skia,nvoron23/skia,Infusion-OS/android_external_skia,RadonX-ROM/external_skia,larsbergstrom/skia,ctiao/platform-external-skia,noselhq/skia,NamelessRom/android_external_skia,pacerom/external_skia,rubenvb/skia,MinimalOS/android_external_skia,aosp-mirror/platform_external_skia,nfxosp/platform_external_skia,ench0/external_chromium_org_third_party_skia,MyAOSP/external_chromium_org_third_party_skia,todotodoo/skia,android-ia/platform_external_chromium_org_third_party_skia,MinimalOS/external_chromium_org_third_party_skia,AOSP-YU/platform_external_skia,amyvmiwei/skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,TeamBliss-LP/android_external_skia,akiss77/skia,HalCanary/skia-hc,TeamEOS/external_chromium_org_third_party_skia,boulzordev/android_external_skia,Infinitive-OS/platform_external_skia,android-ia/platform_external_skia,rubenvb/skia,Igalia/skia,zhaochengw/platform_external_skia,Jichao/skia,DARKPOP/external_chromium_org_third_party_skia,UBERMALLOW/external_skia,mydongistiny/external_chromium_org_third_party_skia,Euphoria-OS-Legacy/android_external_skia,YUPlayGodDev/platform_external_skia,TeamTwisted/external_skia,RadonX-ROM/external_skia,AOSPU/external_chromium_org_third_party_skia
|
660dfec590f50958e85a103ac2e2fe868088c8f6
|
source/Plugins/InstrumentationRuntime/AddressSanitizer/AddressSanitizerRuntime.cpp
|
source/Plugins/InstrumentationRuntime/AddressSanitizer/AddressSanitizerRuntime.cpp
|
//===-- AddressSanitizerRuntime.cpp -----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "AddressSanitizerRuntime.h"
#include "lldb/Core/PluginInterface.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/ModuleList.h"
#include "lldb/Symbol/SymbolContext.h"
#include "lldb/Core/Module.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Breakpoint/StoppointCallbackContext.h"
#include "lldb/Core/ValueObject.h"
#include "lldb/Target/InstrumentationRuntimeStopInfo.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Stream.h"
#include "lldb/Core/StreamFile.h"
using namespace lldb;
using namespace lldb_private;
lldb::InstrumentationRuntimeSP
AddressSanitizerRuntime::CreateInstance (const lldb::ProcessSP &process_sp)
{
return InstrumentationRuntimeSP(new AddressSanitizerRuntime(process_sp));
}
void
AddressSanitizerRuntime::Initialize()
{
PluginManager::RegisterPlugin (GetPluginNameStatic(),
"AddressSanitizer instrumentation runtime plugin.",
CreateInstance,
GetTypeStatic);
}
void
AddressSanitizerRuntime::Terminate()
{
PluginManager::UnregisterPlugin (CreateInstance);
}
lldb_private::ConstString
AddressSanitizerRuntime::GetPluginNameStatic()
{
return ConstString("AddressSanitizer");
}
lldb::InstrumentationRuntimeType
AddressSanitizerRuntime::GetTypeStatic()
{
return eInstrumentationRuntimeTypeAddressSanitizer;
}
AddressSanitizerRuntime::AddressSanitizerRuntime(const ProcessSP &process_sp) :
m_is_active(false),
m_runtime_module(),
m_process(process_sp),
m_breakpoint_id(0)
{
}
AddressSanitizerRuntime::~AddressSanitizerRuntime()
{
Deactivate();
}
bool ModuleContainsASanRuntime(Module * module)
{
SymbolContextList sc_list;
const bool include_symbols = true;
const bool append = true;
const bool include_inlines = true;
size_t num_matches = module->FindFunctions(ConstString("__asan_get_alloc_stack"), NULL, eFunctionNameTypeAuto, include_symbols, include_inlines, append, sc_list);
return num_matches > 0;
}
void
AddressSanitizerRuntime::ModulesDidLoad(lldb_private::ModuleList &module_list)
{
if (IsActive())
return;
if (m_runtime_module) {
Activate();
return;
}
Mutex::Locker modules_locker(module_list.GetMutex());
const size_t num_modules = module_list.GetSize();
for (size_t i = 0; i < num_modules; ++i)
{
Module *module_pointer = module_list.GetModulePointerAtIndexUnlocked(i);
const FileSpec & file_spec = module_pointer->GetFileSpec();
if (! file_spec)
continue;
static RegularExpression g_asan_runtime_regex("libclang_rt.asan_(.*)_dynamic\\.dylib");
if (g_asan_runtime_regex.Execute (file_spec.GetFilename().GetCString()) || module_pointer->IsExecutable())
{
if (ModuleContainsASanRuntime(module_pointer))
{
m_runtime_module = module_pointer->shared_from_this();
Activate();
return;
}
}
}
}
bool
AddressSanitizerRuntime::IsActive()
{
return m_is_active;
}
#define RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC 2*1000*1000
const char *
address_sanitizer_retrieve_report_data_command = R"(
struct {
int present;
void *pc, *bp, *sp, *address;
int access_type;
size_t access_size;
const char *description;
} t;
t.present = ((int (*) ())__asan_report_present)();
t.pc = ((void * (*) ())__asan_get_report_pc)();
/* commented out because rdar://problem/18533301
t.bp = ((void * (*) ())__asan_get_report_bp)();
t.sp = ((void * (*) ())__asan_get_report_sp)();
*/
t.address = ((void * (*) ())__asan_get_report_address)();
t.description = ((const char * (*) ())__asan_get_report_description)();
t.access_type = ((int (*) ())__asan_get_report_access_type)();
t.access_size = ((size_t (*) ())__asan_get_report_access_size)();
t;
)";
StructuredData::ObjectSP
AddressSanitizerRuntime::RetrieveReportData()
{
ThreadSP thread_sp = m_process->GetThreadList().GetSelectedThread();
StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
if (!frame_sp)
return StructuredData::ObjectSP();
EvaluateExpressionOptions options;
options.SetUnwindOnError(true);
options.SetTryAllThreads(true);
options.SetStopOthers(true);
options.SetIgnoreBreakpoints(true);
options.SetTimeoutUsec(RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC);
ValueObjectSP return_value_sp;
if (m_process->GetTarget().EvaluateExpression(address_sanitizer_retrieve_report_data_command, frame_sp.get(), return_value_sp, options) != eExpressionCompleted)
return StructuredData::ObjectSP();
int present = return_value_sp->GetValueForExpressionPath(".present")->GetValueAsUnsigned(0);
if (present != 1)
return StructuredData::ObjectSP();
addr_t pc = return_value_sp->GetValueForExpressionPath(".pc")->GetValueAsUnsigned(0);
addr_t bp = return_value_sp->GetValueForExpressionPath(".bp")->GetValueAsUnsigned(0);
addr_t sp = return_value_sp->GetValueForExpressionPath(".sp")->GetValueAsUnsigned(0);
addr_t address = return_value_sp->GetValueForExpressionPath(".address")->GetValueAsUnsigned(0);
addr_t access_type = return_value_sp->GetValueForExpressionPath(".access_type")->GetValueAsUnsigned(0);
addr_t access_size = return_value_sp->GetValueForExpressionPath(".access_size")->GetValueAsUnsigned(0);
addr_t description_ptr = return_value_sp->GetValueForExpressionPath(".description")->GetValueAsUnsigned(0);
std::string description;
Error error;
m_process->ReadCStringFromMemory(description_ptr, description, error);
StructuredData::Dictionary *dict = new StructuredData::Dictionary();
dict->AddStringItem("instrumentation_class", "AddressSanitizer");
dict->AddStringItem("stop_type", "fatal_error");
dict->AddIntegerItem("pc", pc);
dict->AddIntegerItem("bp", bp);
dict->AddIntegerItem("sp", sp);
dict->AddIntegerItem("address", address);
dict->AddIntegerItem("access_type", access_type);
dict->AddIntegerItem("access_size", access_size);
dict->AddStringItem("description", description);
return StructuredData::ObjectSP(dict);
}
std::string
AddressSanitizerRuntime::FormatDescription(StructuredData::ObjectSP report)
{
std::string description = report->GetAsDictionary()->GetValueForKey("description")->GetAsString()->GetValue();
if (description == "heap-use-after-free") {
return "Use of deallocated memory detected";
} else if (description == "heap-buffer-overflow") {
return "Heap buffer overflow detected";
} else if (description == "stack-buffer-underflow") {
return "Stack buffer underflow detected";
} else if (description == "initialization-order-fiasco") {
return "Initialization order problem detected";
} else if (description == "stack-buffer-overflow") {
return "Stack buffer overflow detected";
} else if (description == "stack-use-after-return") {
return "Use of returned stack memory detected";
} else if (description == "use-after-poison") {
return "Use of poisoned memory detected";
} else if (description == "container-overflow") {
return "Container overflow detected";
} else if (description == "stack-use-after-scope") {
return "Use of out-of-scope stack memory detected";
} else if (description == "global-buffer-overflow") {
return "Global buffer overflow detected";
} else if (description == "unknown-crash") {
return "Invalid memory access detected";
}
// for unknown report codes just show the code
return description;
}
bool
AddressSanitizerRuntime::NotifyBreakpointHit(void *baton, StoppointCallbackContext *context, user_id_t break_id, user_id_t break_loc_id)
{
assert (baton && "null baton");
if (!baton)
return false;
AddressSanitizerRuntime *const instance = static_cast<AddressSanitizerRuntime*>(baton);
StructuredData::ObjectSP report = instance->RetrieveReportData();
std::string description;
if (report) {
description = instance->FormatDescription(report);
}
ThreadSP thread = context->exe_ctx_ref.GetThreadSP();
thread->SetStopInfo(InstrumentationRuntimeStopInfo::CreateStopReasonWithInstrumentationData(*thread, description.c_str(), report));
instance->m_runtime_module->ReportWarning("AddressSanitizer report breakpoint hit. Use 'thread info -s' to get extended information about the report.\n");
// Return true to stop the target, false to just let the target run.
return true;
}
void
AddressSanitizerRuntime::Activate()
{
if (m_is_active)
return;
ConstString symbol_name ("__asan::AsanDie()");
const Symbol *symbol = m_runtime_module->FindFirstSymbolWithNameAndType (symbol_name, eSymbolTypeCode);
if (symbol == NULL)
return;
if (!symbol->GetAddress().IsValid())
return;
Target &target = m_process->GetTarget();
addr_t symbol_address = symbol->GetAddress().GetOpcodeLoadAddress(&target);
if (symbol_address == LLDB_INVALID_ADDRESS)
return;
bool internal = true;
bool hardware = false;
Breakpoint *breakpoint = m_process->GetTarget().CreateBreakpoint(symbol_address, internal, hardware).get();
breakpoint->SetCallback (AddressSanitizerRuntime::NotifyBreakpointHit, this, true);
breakpoint->SetBreakpointKind ("address-sanitizer-report");
m_breakpoint_id = breakpoint->GetID();
m_runtime_module->ReportWarning("AddressSanitizer debugger support is active. Memory error breakpoint has been installed and you can now use the 'memory history' command.\n");
m_is_active = true;
}
void
AddressSanitizerRuntime::Deactivate()
{
if (m_breakpoint_id != LLDB_INVALID_BREAK_ID)
{
m_process->GetTarget().RemoveBreakpointByID(m_breakpoint_id);
m_breakpoint_id = LLDB_INVALID_BREAK_ID;
}
m_is_active = false;
}
|
//===-- AddressSanitizerRuntime.cpp -----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "AddressSanitizerRuntime.h"
#include "lldb/Breakpoint/StoppointCallbackContext.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleList.h"
#include "lldb/Core/PluginInterface.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Stream.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Core/ValueObject.h"
#include "lldb/Interpreter/CommandReturnObject.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Symbol/SymbolContext.h"
#include "lldb/Target/InstrumentationRuntimeStopInfo.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
using namespace lldb;
using namespace lldb_private;
lldb::InstrumentationRuntimeSP
AddressSanitizerRuntime::CreateInstance (const lldb::ProcessSP &process_sp)
{
return InstrumentationRuntimeSP(new AddressSanitizerRuntime(process_sp));
}
void
AddressSanitizerRuntime::Initialize()
{
PluginManager::RegisterPlugin (GetPluginNameStatic(),
"AddressSanitizer instrumentation runtime plugin.",
CreateInstance,
GetTypeStatic);
}
void
AddressSanitizerRuntime::Terminate()
{
PluginManager::UnregisterPlugin (CreateInstance);
}
lldb_private::ConstString
AddressSanitizerRuntime::GetPluginNameStatic()
{
return ConstString("AddressSanitizer");
}
lldb::InstrumentationRuntimeType
AddressSanitizerRuntime::GetTypeStatic()
{
return eInstrumentationRuntimeTypeAddressSanitizer;
}
AddressSanitizerRuntime::AddressSanitizerRuntime(const ProcessSP &process_sp) :
m_is_active(false),
m_runtime_module(),
m_process(process_sp),
m_breakpoint_id(0)
{
}
AddressSanitizerRuntime::~AddressSanitizerRuntime()
{
Deactivate();
}
bool ModuleContainsASanRuntime(Module * module)
{
SymbolContextList sc_list;
const bool include_symbols = true;
const bool append = true;
const bool include_inlines = true;
size_t num_matches = module->FindFunctions(ConstString("__asan_get_alloc_stack"), NULL, eFunctionNameTypeAuto, include_symbols, include_inlines, append, sc_list);
return num_matches > 0;
}
void
AddressSanitizerRuntime::ModulesDidLoad(lldb_private::ModuleList &module_list)
{
if (IsActive())
return;
if (m_runtime_module) {
Activate();
return;
}
Mutex::Locker modules_locker(module_list.GetMutex());
const size_t num_modules = module_list.GetSize();
for (size_t i = 0; i < num_modules; ++i)
{
Module *module_pointer = module_list.GetModulePointerAtIndexUnlocked(i);
const FileSpec & file_spec = module_pointer->GetFileSpec();
if (! file_spec)
continue;
static RegularExpression g_asan_runtime_regex("libclang_rt.asan_(.*)_dynamic\\.dylib");
if (g_asan_runtime_regex.Execute (file_spec.GetFilename().GetCString()) || module_pointer->IsExecutable())
{
if (ModuleContainsASanRuntime(module_pointer))
{
m_runtime_module = module_pointer->shared_from_this();
Activate();
return;
}
}
}
}
bool
AddressSanitizerRuntime::IsActive()
{
return m_is_active;
}
#define RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC 2*1000*1000
const char *
address_sanitizer_retrieve_report_data_command = R"(
struct {
int present;
void *pc, *bp, *sp, *address;
int access_type;
size_t access_size;
const char *description;
} t;
t.present = ((int (*) ())__asan_report_present)();
t.pc = ((void * (*) ())__asan_get_report_pc)();
/* commented out because rdar://problem/18533301
t.bp = ((void * (*) ())__asan_get_report_bp)();
t.sp = ((void * (*) ())__asan_get_report_sp)();
*/
t.address = ((void * (*) ())__asan_get_report_address)();
t.description = ((const char * (*) ())__asan_get_report_description)();
t.access_type = ((int (*) ())__asan_get_report_access_type)();
t.access_size = ((size_t (*) ())__asan_get_report_access_size)();
t;
)";
StructuredData::ObjectSP
AddressSanitizerRuntime::RetrieveReportData()
{
ThreadSP thread_sp = m_process->GetThreadList().GetSelectedThread();
StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
if (!frame_sp)
return StructuredData::ObjectSP();
EvaluateExpressionOptions options;
options.SetUnwindOnError(true);
options.SetTryAllThreads(true);
options.SetStopOthers(true);
options.SetIgnoreBreakpoints(true);
options.SetTimeoutUsec(RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC);
ValueObjectSP return_value_sp;
if (m_process->GetTarget().EvaluateExpression(address_sanitizer_retrieve_report_data_command, frame_sp.get(), return_value_sp, options) != eExpressionCompleted)
return StructuredData::ObjectSP();
int present = return_value_sp->GetValueForExpressionPath(".present")->GetValueAsUnsigned(0);
if (present != 1)
return StructuredData::ObjectSP();
addr_t pc = return_value_sp->GetValueForExpressionPath(".pc")->GetValueAsUnsigned(0);
addr_t bp = return_value_sp->GetValueForExpressionPath(".bp")->GetValueAsUnsigned(0);
addr_t sp = return_value_sp->GetValueForExpressionPath(".sp")->GetValueAsUnsigned(0);
addr_t address = return_value_sp->GetValueForExpressionPath(".address")->GetValueAsUnsigned(0);
addr_t access_type = return_value_sp->GetValueForExpressionPath(".access_type")->GetValueAsUnsigned(0);
addr_t access_size = return_value_sp->GetValueForExpressionPath(".access_size")->GetValueAsUnsigned(0);
addr_t description_ptr = return_value_sp->GetValueForExpressionPath(".description")->GetValueAsUnsigned(0);
std::string description;
Error error;
m_process->ReadCStringFromMemory(description_ptr, description, error);
StructuredData::Dictionary *dict = new StructuredData::Dictionary();
dict->AddStringItem("instrumentation_class", "AddressSanitizer");
dict->AddStringItem("stop_type", "fatal_error");
dict->AddIntegerItem("pc", pc);
dict->AddIntegerItem("bp", bp);
dict->AddIntegerItem("sp", sp);
dict->AddIntegerItem("address", address);
dict->AddIntegerItem("access_type", access_type);
dict->AddIntegerItem("access_size", access_size);
dict->AddStringItem("description", description);
return StructuredData::ObjectSP(dict);
}
std::string
AddressSanitizerRuntime::FormatDescription(StructuredData::ObjectSP report)
{
std::string description = report->GetAsDictionary()->GetValueForKey("description")->GetAsString()->GetValue();
if (description == "heap-use-after-free") {
return "Use of deallocated memory detected";
} else if (description == "heap-buffer-overflow") {
return "Heap buffer overflow detected";
} else if (description == "stack-buffer-underflow") {
return "Stack buffer underflow detected";
} else if (description == "initialization-order-fiasco") {
return "Initialization order problem detected";
} else if (description == "stack-buffer-overflow") {
return "Stack buffer overflow detected";
} else if (description == "stack-use-after-return") {
return "Use of returned stack memory detected";
} else if (description == "use-after-poison") {
return "Use of poisoned memory detected";
} else if (description == "container-overflow") {
return "Container overflow detected";
} else if (description == "stack-use-after-scope") {
return "Use of out-of-scope stack memory detected";
} else if (description == "global-buffer-overflow") {
return "Global buffer overflow detected";
} else if (description == "unknown-crash") {
return "Invalid memory access detected";
}
// for unknown report codes just show the code
return description;
}
bool
AddressSanitizerRuntime::NotifyBreakpointHit(void *baton, StoppointCallbackContext *context, user_id_t break_id, user_id_t break_loc_id)
{
assert (baton && "null baton");
if (!baton)
return false;
AddressSanitizerRuntime *const instance = static_cast<AddressSanitizerRuntime*>(baton);
StructuredData::ObjectSP report = instance->RetrieveReportData();
std::string description;
if (report) {
description = instance->FormatDescription(report);
}
ThreadSP thread = context->exe_ctx_ref.GetThreadSP();
thread->SetStopInfo(InstrumentationRuntimeStopInfo::CreateStopReasonWithInstrumentationData(*thread, description.c_str(), report));
if (instance->m_process)
{
StreamFileSP stream_sp (instance->m_process->GetTarget().GetDebugger().GetOutputFile());
if (stream_sp)
{
stream_sp->Printf ("AddressSanitizer report breakpoint hit. Use 'thread info -s' to get extended information about the report.\n");
}
}
// Return true to stop the target, false to just let the target run.
return true;
}
void
AddressSanitizerRuntime::Activate()
{
if (m_is_active)
return;
ConstString symbol_name ("__asan::AsanDie()");
const Symbol *symbol = m_runtime_module->FindFirstSymbolWithNameAndType (symbol_name, eSymbolTypeCode);
if (symbol == NULL)
return;
if (!symbol->GetAddress().IsValid())
return;
Target &target = m_process->GetTarget();
addr_t symbol_address = symbol->GetAddress().GetOpcodeLoadAddress(&target);
if (symbol_address == LLDB_INVALID_ADDRESS)
return;
bool internal = true;
bool hardware = false;
Breakpoint *breakpoint = m_process->GetTarget().CreateBreakpoint(symbol_address, internal, hardware).get();
breakpoint->SetCallback (AddressSanitizerRuntime::NotifyBreakpointHit, this, true);
breakpoint->SetBreakpointKind ("address-sanitizer-report");
m_breakpoint_id = breakpoint->GetID();
if (m_process)
{
StreamFileSP stream_sp (m_process->GetTarget().GetDebugger().GetOutputFile());
if (stream_sp)
{
stream_sp->Printf ("AddressSanitizer debugger support is active. Memory error breakpoint has been installed and you can now use the 'memory history' command.\n");
}
}
m_is_active = true;
}
void
AddressSanitizerRuntime::Deactivate()
{
if (m_breakpoint_id != LLDB_INVALID_BREAK_ID)
{
m_process->GetTarget().RemoveBreakpointByID(m_breakpoint_id);
m_breakpoint_id = LLDB_INVALID_BREAK_ID;
}
m_is_active = false;
}
|
Change AddressSanitzierRuntime to print its info message via the Debugger's output stream instead of logging to the module.
|
Change AddressSanitzierRuntime to print its info message via
the Debugger's output stream instead of logging to the module.
http://reviews.llvm.org/D6577
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@223826 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb
|
743f34d9d20c67deecf6d18a5c8e58e83ab35c98
|
vcl/opengl/x11/X11DeviceInfo.cxx
|
vcl/opengl/x11/X11DeviceInfo.cxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "opengl/x11/X11DeviceInfo.hxx"
#include <vcl/opengl/glxtest.hxx>
#include <rtl/ustring.hxx>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <sys/utsname.h>
namespace glx {
static int glxtest_pipe = 0;
static pid_t glxtest_pid = 0;
}
pid_t* getGlxPid()
{
return &glx::glxtest_pid;
}
int* getGlxPipe()
{
return &glx::glxtest_pipe;
}
namespace {
const char*
strspnp_wrapper(const char* aDelims, const char* aStr)
{
const char* d;
do {
for (d = aDelims; *d != '\0'; ++d) {
if (*aStr == *d) {
++aStr;
break;
}
}
} while (*d);
return aStr;
}
char* strtok_wrapper(const char* aDelims, char** aStr)
{
if (!*aStr) {
return nullptr;
}
char* ret = (char*)strspnp_wrapper(aDelims, *aStr);
if (!*ret) {
*aStr = ret;
return nullptr;
}
char* i = ret;
do {
for (const char* d = aDelims; *d != '\0'; ++d) {
if (*i == *d) {
*i = '\0';
*aStr = ++i;
return ret;
}
}
++i;
} while (*i);
*aStr = nullptr;
return ret;
}
uint64_t version(uint32_t major, uint32_t minor, uint32_t revision = 0)
{
return (uint64_t(major) << 32) + (uint64_t(minor) << 16) + uint64_t(revision);
}
}
X11OpenGLDeviceInfo::X11OpenGLDeviceInfo():
mbIsMesa(false),
mbIsNVIDIA(false),
mbIsFGLRX(false),
mbIsNouveau(false),
mbIsIntel(false),
mbIsOldSwrast(false),
mbIsLlvmpipe(false),
mbHasTextureFromPixmap(false),
mnGLMajorVersion(0),
mnMajorVersion(0),
mnMinorVersion(0),
mnRevisionVersion(0)
{
GetData();
}
X11OpenGLDeviceInfo::~X11OpenGLDeviceInfo()
{
}
void X11OpenGLDeviceInfo::GetData()
{
if (!glx::glxtest_pipe)
return;
// to understand this function, see bug 639842. We retrieve the OpenGL driver information in a
// separate process to protect against bad drivers.
enum { buf_size = 1024 };
char buf[buf_size];
ssize_t bytesread = read(glx::glxtest_pipe,
&buf,
buf_size-1); // -1 because we'll append a zero
close(glx::glxtest_pipe);
glx::glxtest_pipe = 0;
// bytesread < 0 would mean that the above read() call failed.
// This should never happen. If it did, the outcome would be to blacklist anyway.
if (bytesread < 0)
bytesread = 0;
// let buf be a zero-terminated string
buf[bytesread] = 0;
// Wait for the glxtest process to finish. This serves 2 purposes:
// * avoid having a zombie glxtest process laying around
// * get the glxtest process status info.
int glxtest_status = 0;
bool wait_for_glxtest_process = true;
bool waiting_for_glxtest_process_failed = false;
int waitpid_errno = 0;
while(wait_for_glxtest_process) {
wait_for_glxtest_process = false;
if (waitpid(glx::glxtest_pid, &glxtest_status, 0) == -1) {
waitpid_errno = errno;
if (waitpid_errno == EINTR) {
wait_for_glxtest_process = true;
} else {
// Bug 718629
// ECHILD happens when the glxtest process got reaped got reaped after a PR_CreateProcess
// as per bug 227246. This shouldn't matter, as we still seem to get the data
// from the pipe, and if we didn't, the outcome would be to blacklist anyway.
waiting_for_glxtest_process_failed = (waitpid_errno != ECHILD);
}
}
}
bool exited_with_error_code = !waiting_for_glxtest_process_failed &&
WIFEXITED(glxtest_status) &&
WEXITSTATUS(glxtest_status) != EXIT_SUCCESS;
bool received_signal = !waiting_for_glxtest_process_failed &&
WIFSIGNALED(glxtest_status);
bool error = waiting_for_glxtest_process_failed || exited_with_error_code || received_signal;
OString textureFromPixmap;
OString *stringToFill = nullptr;
char *bufptr = buf;
if (!error) {
while(true) {
char *line = strtok_wrapper("\n", &bufptr);
if (!line)
break;
if (stringToFill) {
*stringToFill = OString(line);
stringToFill = nullptr;
}
else if(!strcmp(line, "VENDOR"))
stringToFill = &maVendor;
else if(!strcmp(line, "RENDERER"))
stringToFill = &maRenderer;
else if(!strcmp(line, "VERSION"))
stringToFill = &maVersion;
else if(!strcmp(line, "TFP"))
stringToFill = &textureFromPixmap;
}
}
if (!strcmp(textureFromPixmap.getStr(), "TRUE"))
mbHasTextureFromPixmap = true;
// only useful for Linux kernel version check for FGLRX driver.
// assumes X client == X server, which is sad.
struct utsname unameobj;
if (!uname(&unameobj))
{
maOS = OString(unameobj.sysname);
maOSRelease = OString(unameobj.release);
}
// determine the major OpenGL version. That's the first integer in the version string.
mnGLMajorVersion = strtol(maVersion.getStr(), 0, 10);
// determine driver type (vendor) and where in the version string
// the actual driver version numbers should be expected to be found (whereToReadVersionNumbers)
const char *whereToReadVersionNumbers = nullptr;
const char *Mesa_in_version_string = strstr(maVersion.getStr(), "Mesa");
if (Mesa_in_version_string) {
mbIsMesa = true;
// with Mesa, the version string contains "Mesa major.minor" and that's all the version information we get:
// there is no actual driver version info.
whereToReadVersionNumbers = Mesa_in_version_string + strlen("Mesa");
if (strcasestr(maVendor.getStr(), "nouveau"))
mbIsNouveau = true;
if (strcasestr(maRenderer.getStr(), "intel")) // yes, intel is in the renderer string
mbIsIntel = true;
if (strcasestr(maRenderer.getStr(), "llvmpipe"))
mbIsLlvmpipe = true;
if (strcasestr(maRenderer.getStr(), "software rasterizer"))
mbIsOldSwrast = true;
} else if (strstr(maVendor.getStr(), "NVIDIA Corporation")) {
mbIsNVIDIA = true;
// with the NVIDIA driver, the version string contains "NVIDIA major.minor"
// note that here the vendor and version strings behave differently, that's why we don't put this above
// alongside Mesa_in_version_string.
const char *NVIDIA_in_version_string = strstr(maVersion.getStr(), "NVIDIA");
if (NVIDIA_in_version_string)
whereToReadVersionNumbers = NVIDIA_in_version_string + strlen("NVIDIA");
} else if (strstr(maVendor.getStr(), "ATI Technologies Inc")) {
mbIsFGLRX = true;
// with the FGLRX driver, the version string only gives a OpenGL version :/ so let's return that.
// that can at least give a rough idea of how old the driver is.
whereToReadVersionNumbers = maVersion.getStr();
}
// read major.minor version numbers of the driver (not to be confused with the OpenGL version)
if (whereToReadVersionNumbers) {
// copy into writable buffer, for tokenization
strncpy(buf, whereToReadVersionNumbers, buf_size);
bufptr = buf;
// now try to read major.minor version numbers. In case of failure, gracefully exit: these numbers have
// been initialized as 0 anyways
char *token = strtok_wrapper(".", &bufptr);
if (token) {
mnMajorVersion = strtol(token, 0, 10);
token = strtok_wrapper(".", &bufptr);
if (token) {
mnMinorVersion = strtol(token, 0, 10);
token = strtok_wrapper(".", &bufptr);
if (token)
mnRevisionVersion = strtol(token, 0, 10);
}
}
}
}
bool X11OpenGLDeviceInfo::isDeviceBlocked()
{
// don't even try to use OpenGL 1.x
if (mnGLMajorVersion == 1)
return true;
SAL_INFO("vcl.opengl", "Vendor: " << maVendor);
SAL_INFO("vcl.opengl", "Renderer: " << maRenderer);
SAL_INFO("vcl.opengl", "Version: " << maVersion);
SAL_INFO("vcl.opengl", "OS: " << maOS);
SAL_INFO("vcl.opengl", "OSRelease: " << maOSRelease);
if (mbIsMesa) {
if (mbIsNouveau && version(mnMajorVersion, mnMinorVersion) < version(8,0)) {
SAL_WARN("vcl.opengl", "blocked driver version: old nouveau driver (requires mesa 8.0+)");
return true;
}
else if (version(mnMajorVersion, mnMinorVersion, mnRevisionVersion) < version(7,10,3)) {
SAL_WARN("vcl.opengl", "blocked driver version: requires at least mesa 7.10.3");
return true;
}
else if (mbIsOldSwrast) {
SAL_WARN("vcl.opengl", "blocked driver version: software rasterizer");
return true;
}
else if (mbIsLlvmpipe && version(mnMajorVersion, mnMinorVersion) < version(9, 1)) {
// bug 791905, Mesa bug 57733, fixed in Mesa 9.1 according to
// https://bugs.freedesktop.org/show_bug.cgi?id=57733#c3
SAL_WARN("vcl.opengl", "blocked driver version: fdo#57733");
return true;
}
} else if (mbIsNVIDIA) {
if (version(mnMajorVersion, mnMinorVersion, mnRevisionVersion) < version(257,21)) {
SAL_WARN("vcl.opengl", "blocked driver version: nvidia requires at least 257.21");
return true;
}
} else if (mbIsFGLRX) {
// FGLRX does not report a driver version number, so we have the OpenGL version instead.
// by requiring OpenGL 3, we effectively require recent drivers.
if (version(mnMajorVersion, mnMinorVersion, mnRevisionVersion) < version(3, 0)) {
SAL_WARN("vcl.opengl", "blocked driver version: require at least OpenGL 3 for fglrx");
return true;
}
// Bug 724640: FGLRX + Linux 2.6.32 is a crashy combo
bool unknownOS = maOS.isEmpty() || maOSRelease.isEmpty();
bool badOS = maOS.indexOf("Linux") != -1 &&
maOSRelease.indexOf("2.6.32") != -1;
if (unknownOS || badOS) {
SAL_WARN("vcl.opengl", "blocked OS version with fglrx");
return true;
}
} else {
// like on windows, let's block unknown vendors. Think of virtual machines.
// Also, this case is hit whenever the GLXtest probe failed to get driver info or crashed.
SAL_WARN("vcl.opengl", "unknown vendor => blocked");
return true;
}
return false;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "opengl/x11/X11DeviceInfo.hxx"
#include <vcl/opengl/glxtest.hxx>
#include <rtl/ustring.hxx>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <sys/utsname.h>
namespace glx {
static int glxtest_pipe = 0;
static pid_t glxtest_pid = 0;
}
pid_t* getGlxPid()
{
return &glx::glxtest_pid;
}
int* getGlxPipe()
{
return &glx::glxtest_pipe;
}
namespace {
const char*
strspnp_wrapper(const char* aDelims, const char* aStr)
{
const char* d;
do {
for (d = aDelims; *d != '\0'; ++d) {
if (*aStr == *d) {
++aStr;
break;
}
}
} while (*d);
return aStr;
}
char* strtok_wrapper(const char* aDelims, char** aStr)
{
if (!*aStr) {
return nullptr;
}
char* ret = (char*)strspnp_wrapper(aDelims, *aStr);
if (!*ret) {
*aStr = ret;
return nullptr;
}
char* i = ret;
do {
for (const char* d = aDelims; *d != '\0'; ++d) {
if (*i == *d) {
*i = '\0';
*aStr = ++i;
return ret;
}
}
++i;
} while (*i);
*aStr = nullptr;
return ret;
}
uint64_t version(uint32_t major, uint32_t minor, uint32_t revision = 0)
{
return (uint64_t(major) << 32) + (uint64_t(minor) << 16) + uint64_t(revision);
}
}
X11OpenGLDeviceInfo::X11OpenGLDeviceInfo():
mbIsMesa(false),
mbIsNVIDIA(false),
mbIsFGLRX(false),
mbIsNouveau(false),
mbIsIntel(false),
mbIsOldSwrast(false),
mbIsLlvmpipe(false),
mbHasTextureFromPixmap(false),
mnGLMajorVersion(0),
mnMajorVersion(0),
mnMinorVersion(0),
mnRevisionVersion(0)
{
GetData();
}
X11OpenGLDeviceInfo::~X11OpenGLDeviceInfo()
{
}
void X11OpenGLDeviceInfo::GetData()
{
if (!glx::glxtest_pipe)
return;
// to understand this function, see bug 639842. We retrieve the OpenGL driver information in a
// separate process to protect against bad drivers.
enum { buf_size = 1024 };
char buf[buf_size];
ssize_t bytesread = read(glx::glxtest_pipe,
&buf,
buf_size-1); // -1 because we'll append a zero
close(glx::glxtest_pipe);
glx::glxtest_pipe = 0;
// bytesread < 0 would mean that the above read() call failed.
// This should never happen. If it did, the outcome would be to blacklist anyway.
if (bytesread < 0)
bytesread = 0;
// let buf be a zero-terminated string
buf[bytesread] = 0;
// Wait for the glxtest process to finish. This serves 2 purposes:
// * avoid having a zombie glxtest process laying around
// * get the glxtest process status info.
int glxtest_status = 0;
bool wait_for_glxtest_process = true;
bool waiting_for_glxtest_process_failed = false;
int waitpid_errno = 0;
while(wait_for_glxtest_process) {
wait_for_glxtest_process = false;
if (waitpid(glx::glxtest_pid, &glxtest_status, 0) == -1) {
waitpid_errno = errno;
if (waitpid_errno == EINTR) {
wait_for_glxtest_process = true;
} else {
// Bug 718629
// ECHILD happens when the glxtest process got reaped got reaped after a PR_CreateProcess
// as per bug 227246. This shouldn't matter, as we still seem to get the data
// from the pipe, and if we didn't, the outcome would be to blacklist anyway.
waiting_for_glxtest_process_failed = (waitpid_errno != ECHILD);
}
}
}
bool exited_with_error_code = !waiting_for_glxtest_process_failed &&
WIFEXITED(glxtest_status) &&
WEXITSTATUS(glxtest_status) != EXIT_SUCCESS;
bool received_signal = !waiting_for_glxtest_process_failed &&
WIFSIGNALED(glxtest_status);
bool error = waiting_for_glxtest_process_failed || exited_with_error_code || received_signal;
OString textureFromPixmap;
OString *stringToFill = nullptr;
char *bufptr = buf;
if (!error) {
while(true) {
char *line = strtok_wrapper("\n", &bufptr);
if (!line)
break;
if (stringToFill) {
*stringToFill = OString(line);
stringToFill = nullptr;
}
else if(!strcmp(line, "VENDOR"))
stringToFill = &maVendor;
else if(!strcmp(line, "RENDERER"))
stringToFill = &maRenderer;
else if(!strcmp(line, "VERSION"))
stringToFill = &maVersion;
else if(!strcmp(line, "TFP"))
stringToFill = &textureFromPixmap;
}
}
if (!strcmp(textureFromPixmap.getStr(), "TRUE"))
mbHasTextureFromPixmap = true;
// only useful for Linux kernel version check for FGLRX driver.
// assumes X client == X server, which is sad.
struct utsname unameobj;
if (!uname(&unameobj))
{
maOS = OString(unameobj.sysname);
maOSRelease = OString(unameobj.release);
}
// determine the major OpenGL version. That's the first integer in the version string.
mnGLMajorVersion = strtol(maVersion.getStr(), 0, 10);
// determine driver type (vendor) and where in the version string
// the actual driver version numbers should be expected to be found (whereToReadVersionNumbers)
const char *whereToReadVersionNumbers = nullptr;
const char *Mesa_in_version_string = strstr(maVersion.getStr(), "Mesa");
if (Mesa_in_version_string) {
mbIsMesa = true;
// with Mesa, the version string contains "Mesa major.minor" and that's all the version information we get:
// there is no actual driver version info.
whereToReadVersionNumbers = Mesa_in_version_string + strlen("Mesa");
if (strcasestr(maVendor.getStr(), "nouveau"))
mbIsNouveau = true;
if (strcasestr(maRenderer.getStr(), "intel")) // yes, intel is in the renderer string
mbIsIntel = true;
if (strcasestr(maRenderer.getStr(), "llvmpipe"))
mbIsLlvmpipe = true;
if (strcasestr(maRenderer.getStr(), "software rasterizer"))
mbIsOldSwrast = true;
} else if (strstr(maVendor.getStr(), "NVIDIA Corporation")) {
mbIsNVIDIA = true;
// with the NVIDIA driver, the version string contains "NVIDIA major.minor"
// note that here the vendor and version strings behave differently, that's why we don't put this above
// alongside Mesa_in_version_string.
const char *NVIDIA_in_version_string = strstr(maVersion.getStr(), "NVIDIA");
if (NVIDIA_in_version_string)
whereToReadVersionNumbers = NVIDIA_in_version_string + strlen("NVIDIA");
} else if (strstr(maVendor.getStr(), "ATI Technologies Inc")) {
mbIsFGLRX = true;
// with the FGLRX driver, the version string only gives a OpenGL version :/ so let's return that.
// that can at least give a rough idea of how old the driver is.
whereToReadVersionNumbers = maVersion.getStr();
}
// read major.minor version numbers of the driver (not to be confused with the OpenGL version)
if (whereToReadVersionNumbers) {
// copy into writable buffer, for tokenization
strncpy(buf, whereToReadVersionNumbers, buf_size);
bufptr = buf;
// now try to read major.minor version numbers. In case of failure, gracefully exit: these numbers have
// been initialized as 0 anyways
char *token = strtok_wrapper(".", &bufptr);
if (token) {
mnMajorVersion = strtol(token, 0, 10);
token = strtok_wrapper(".", &bufptr);
if (token) {
mnMinorVersion = strtol(token, 0, 10);
token = strtok_wrapper(".", &bufptr);
if (token)
mnRevisionVersion = strtol(token, 0, 10);
}
}
}
}
bool X11OpenGLDeviceInfo::isDeviceBlocked()
{
// don't even try to use OpenGL 1.x
if (mnGLMajorVersion == 1)
return true;
SAL_INFO("vcl.opengl", "Vendor: " << maVendor);
SAL_INFO("vcl.opengl", "Renderer: " << maRenderer);
SAL_INFO("vcl.opengl", "Version: " << maVersion);
SAL_INFO("vcl.opengl", "OS: " << maOS);
SAL_INFO("vcl.opengl", "OSRelease: " << maOSRelease);
if (mbIsMesa) {
if (mbIsNouveau && version(mnMajorVersion, mnMinorVersion) < version(8,0)) {
SAL_WARN("vcl.opengl", "blocked driver version: old nouveau driver (requires mesa 8.0+)");
return true;
}
else if (version(mnMajorVersion, mnMinorVersion, mnRevisionVersion) < version(7,10,3)) {
SAL_WARN("vcl.opengl", "blocked driver version: requires at least mesa 7.10.3");
return true;
}
else if (mbIsOldSwrast) {
SAL_WARN("vcl.opengl", "blocked driver version: software rasterizer");
return true;
}
else if (mbIsLlvmpipe && version(mnMajorVersion, mnMinorVersion) < version(9, 1)) {
// bug 791905, Mesa bug 57733, fixed in Mesa 9.1 according to
// https://bugs.freedesktop.org/show_bug.cgi?id=57733#c3
SAL_WARN("vcl.opengl", "blocked driver version: fdo#57733");
return true;
}
} else if (mbIsNVIDIA) {
if (version(mnMajorVersion, mnMinorVersion, mnRevisionVersion) < version(257,21)) {
SAL_WARN("vcl.opengl", "blocked driver version: nvidia requires at least 257.21");
return true;
}
} else if (mbIsFGLRX) {
// FGLRX does not report a driver version number, so we have the OpenGL version instead.
// by requiring OpenGL 3, we effectively require recent drivers.
if (version(mnMajorVersion, mnMinorVersion, mnRevisionVersion) < version(3, 0)) {
SAL_WARN("vcl.opengl", "blocked driver version: require at least OpenGL 3 for fglrx");
return true;
}
// Bug 724640: FGLRX + Linux 2.6.32 is a crashy combo
bool unknownOS = maOS.isEmpty() || maOSRelease.isEmpty();
bool badOS = maOS.indexOf("Linux") != -1 &&
maOSRelease.indexOf("2.6.32") != -1;
if (unknownOS || badOS) {
SAL_WARN("vcl.opengl", "blocked OS version with fglrx");
return true;
}
} else {
// like on windows, let's block unknown vendors. Think of virtual machines.
// Also, this case is hit whenever the GLXtest probe failed to get driver info or crashed.
SAL_WARN("vcl.opengl", "unknown vendor => blocked");
return true;
}
return false;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
remove whitespace
|
remove whitespace
Change-Id: Ie41f7dee77d378bcdd963ea26b0b83d198762f53
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
f8ff7a532eeeeaaafb433ed0df59a920e63fbc3a
|
t/add_person.cc
|
t/add_person.cc
|
// See README.txt for information and build instructions.
#include <iostream>
#include <fstream>
#include <string>
#include "addressbook.pb.h"
using namespace std;
// This function fills in a Person message based on user input.
void PromptForAddress(tutorial::Person* person) {
cout << "Enter person ID number: ";
int id;
cin >> id;
person->set_id(id);
cin.ignore(256, '\n');
cout << "Enter name: ";
getline(cin, *person->mutable_name());
cout << "Enter email address (blank for none): ";
string email;
getline(cin, email);
if (!email.empty()) {
person->set_email(email);
}
while (true) {
cout << "Enter a phone number (or leave blank to finish): ";
string number;
getline(cin, number);
if (number.empty()) {
break;
}
tutorial::Person::PhoneNumber* phone_number = person->add_phone();
phone_number->set_number(number);
cout << "Is this a mobile, home, or work phone? ";
string type;
getline(cin, type);
if (type == "mobile") {
phone_number->set_type(tutorial::Person::MOBILE);
} else if (type == "home") {
phone_number->set_type(tutorial::Person::HOME);
} else if (type == "work") {
phone_number->set_type(tutorial::Person::WORK);
} else {
cout << "Unknown phone type. Using default." << endl;
}
}
double double_var;
cout << "Enter double_var (0 to skip): ";
cin >> double_var;
person->set_double_var(double_var);
cin.ignore(256, '\n');
float float_var;
cout << "Enter float_var (0 to skip): ";
cin >> float_var;
person->set_float_var(float_var);
cin.ignore(256, '\n');
int64_t int64_var;
cout << "Enter int64_var (0 to skip): ";
cin >> int64_var;
person->set_int64_var(int64_var);
cin.ignore(256, '\n');
uint32_t uint32_var;
cout << "Enter uint32_var (0 to skip): ";
cin >> uint32_var;
person->set_uint32_var(uint32_var);
cin.ignore(256, '\n');
uint64_t uint64_var;
cout << "Enter uint64_var (0 to skip): ";
cin >> uint64_var;
person->set_uint64_var(uint64_var);
cin.ignore(256, '\n');
int32_t sint32_var;
cout << "Enter sint32_var (0 to skip): ";
cin >> sint32_var;
person->set_sint32_var(sint32_var);
cin.ignore(256, '\n');
int64_t sint64_var;
cout << "Enter sint64_var (0 to skip): ";
cin >> sint64_var;
person->set_sint64_var(sint64_var);
cin.ignore(256, '\n');
uint32_t fixed32_var;
cout << "Enter fixed32_var (0 to skip): ";
cin >> fixed32_var;
person->set_fixed32_var(fixed32_var);
cin.ignore(256, '\n');
uint64_t fixed64_var;
cout << "Enter fixed64_var (0 to skip): ";
cin >> fixed64_var;
person->set_fixed64_var(fixed64_var);
cin.ignore(256, '\n');
int32_t sfixed32_var;
cout << "Enter sfixed32_var (0 to skip): ";
cin >> sfixed32_var;
person->set_sfixed32_var(sfixed32_var);
cin.ignore(256, '\n');
int64_t sfixed64_var;
cout << "Enter sfixed64_var (0 to skip): ";
cin >> sfixed64_var;
person->set_sfixed64_var(sfixed64_var);
cin.ignore(256, '\n');
int bool_var;
cout << "Enter bool_var (-1 to skip): ";
cin >> bool_var;
if (bool_var >= 0) {
person->set_bool_var(bool_var > 0);
}
cin.ignore(256, '\n');
string string_var;
cout << "Enter string_var (return to skip): ";
getline(cin, string_var);
if (!string_var.empty()) {
person->set_string_var(string_var);
}
string bytes_var;
cout << "Enter bytes_var (0 to skip): ";
getline(cin, bytes_var);
if (!bytes_var.empty()) {
person->set_bytes_var(bytes_var);
}
}
// Main function: Reads the entire address book from a file,
// adds one person based on user input, then writes it back out to the same
// file.
int main(int argc, char* argv[]) {
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
GOOGLE_PROTOBUF_VERIFY_VERSION;
if (argc != 2) {
cerr << "Usage: " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
return -1;
}
tutorial::AddressBook address_book;
{
// Read the existing address book.
fstream input(argv[1], ios::in | ios::binary);
if (!input) {
cout << argv[1] << ": File not found. Creating a new file." << endl;
} else if (!address_book.ParseFromIstream(&input)) {
cerr << "Failed to parse address book." << endl;
return -1;
}
}
// Add an address.
PromptForAddress(address_book.add_person());
{
// Write the new address book back to disk.
fstream output(argv[1], ios::out | ios::trunc | ios::binary);
if (!address_book.SerializeToOstream(&output)) {
cerr << "Failed to write address book." << endl;
return -1;
}
}
// Optional: Delete all global objects allocated by libprotobuf.
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
|
// See README.txt for information and build instructions.
#include <iostream>
#include <fstream>
#include <string>
#include "addressbook.pb.h"
using namespace std;
// This function fills in a Person message based on user input.
void PromptForAddress(tutorial::Person* person) {
cout << "Enter person ID number: ";
int id;
cin >> id;
person->set_id(id);
cin.ignore(256, '\n');
cout << "Enter name: ";
getline(cin, *person->mutable_name());
cout << "Enter email address (blank for none): ";
string email;
getline(cin, email);
if (!email.empty()) {
person->set_email(email);
}
while (true) {
cout << "Enter a phone number (or leave blank to finish): ";
string number;
getline(cin, number);
if (number.empty()) {
break;
}
tutorial::Person::PhoneNumber* phone_number = person->add_phone();
phone_number->set_number(number);
cout << "Is this a mobile, home, or work phone? ";
string type;
getline(cin, type);
if (type == "mobile") {
phone_number->set_type(tutorial::Person::MOBILE);
} else if (type == "home") {
phone_number->set_type(tutorial::Person::HOME);
} else if (type == "work") {
phone_number->set_type(tutorial::Person::WORK);
} else {
cout << "Unknown phone type. Using default." << endl;
}
}
double double_var;
cout << "Enter double_var (0 to skip): ";
cin >> double_var;
if (double_var)
person->set_double_var(double_var);
cin.ignore(256, '\n');
float float_var;
cout << "Enter float_var (0 to skip): ";
cin >> float_var;
if (float_var)
person->set_float_var(float_var);
cin.ignore(256, '\n');
int64_t int64_var;
cout << "Enter int64_var (0 to skip): ";
cin >> int64_var;
if (int64_var)
person->set_int64_var(int64_var);
cin.ignore(256, '\n');
uint32_t uint32_var;
cout << "Enter uint32_var (0 to skip): ";
cin >> uint32_var;
if (uint32_var)
person->set_uint32_var(uint32_var);
cin.ignore(256, '\n');
uint64_t uint64_var;
cout << "Enter uint64_var (0 to skip): ";
cin >> uint64_var;
if (uint64_var)
person->set_uint64_var(uint64_var);
cin.ignore(256, '\n');
int32_t sint32_var;
cout << "Enter sint32_var (0 to skip): ";
cin >> sint32_var;
if (sint32_var)
person->set_sint32_var(sint32_var);
cin.ignore(256, '\n');
int64_t sint64_var;
cout << "Enter sint64_var (0 to skip): ";
cin >> sint64_var;
if (sint64_var)
person->set_sint64_var(sint64_var);
cin.ignore(256, '\n');
uint32_t fixed32_var;
cout << "Enter fixed32_var (0 to skip): ";
cin >> fixed32_var;
if (fixed32_var)
person->set_fixed32_var(fixed32_var);
cin.ignore(256, '\n');
uint64_t fixed64_var;
cout << "Enter fixed64_var (0 to skip): ";
cin >> fixed64_var;
if (fixed64_var)
person->set_fixed64_var(fixed64_var);
cin.ignore(256, '\n');
int32_t sfixed32_var;
cout << "Enter sfixed32_var (0 to skip): ";
cin >> sfixed32_var;
if (sfixed32_var)
person->set_sfixed32_var(sfixed32_var);
cin.ignore(256, '\n');
int64_t sfixed64_var;
cout << "Enter sfixed64_var (0 to skip): ";
cin >> sfixed64_var;
person->set_sfixed64_var(sfixed64_var);
cin.ignore(256, '\n');
int bool_var;
cout << "Enter bool_var (-1 to skip): ";
cin >> bool_var;
if (bool_var >= 0) {
person->set_bool_var(bool_var > 0);
}
cin.ignore(256, '\n');
string string_var;
cout << "Enter string_var (return to skip): ";
getline(cin, string_var);
if (!string_var.empty()) {
person->set_string_var(string_var);
}
string file_name;
cout << "Enter file_name (0 to skip): ";
getline(cin, file_name);
if (!file_name.empty()) {
ifstream in(file_name.c_str(), ios::binary);
in.seekg(0, ios::end);
streamsize length = in.tellg();
in.seekg(0, ios::beg);
vector<char> buffer(length);
if (in.read(buffer.data(), length)) {
person->set_bytes_var(buffer.data(), length);
}
}
}
// Main function: Reads the entire address book from a file,
// adds one person based on user input, then writes it back out to the same
// file.
int main(int argc, char* argv[]) {
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
GOOGLE_PROTOBUF_VERIFY_VERSION;
if (argc != 2) {
cerr << "Usage: " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
return -1;
}
tutorial::AddressBook address_book;
{
// Read the existing address book.
fstream input(argv[1], ios::in | ios::binary);
if (!input) {
cout << argv[1] << ": File not found. Creating a new file." << endl;
} else if (!address_book.ParseFromIstream(&input)) {
cerr << "Failed to parse address book." << endl;
return -1;
}
}
// Add an address.
PromptForAddress(address_book.add_person());
{
// Write the new address book back to disk.
fstream output(argv[1], ios::out | ios::trunc | ios::binary);
if (!address_book.SerializeToOstream(&output)) {
cerr << "Failed to write address book." << endl;
return -1;
}
}
// Optional: Delete all global objects allocated by libprotobuf.
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
|
Load bytes field from file.
|
Load bytes field from file.
This way can get a look at how non-printable bytes are encoded.
|
C++
|
mit
|
protobuf-c/protobuf-c-text,protobuf-c/protobuf-c-text
|
56e89f5e0f6668e2ffd884a928e5a973e4bee987
|
libpqxx/test/test007.cxx
|
libpqxx/test/test007.cxx
|
#include <cassert>
#include <iostream>
#include <map>
#include <pqxx/connection>
#include <pqxx/transaction>
#include <pqxx/transactor>
#include <pqxx/result>
using namespace PGSTD;
using namespace pqxx;
// Example program for libpqxx. Modify the database, retaining transactional
// integrity using the transactor framework.
//
// Usage: test007 [connect-string]
//
// Where connect-string is a set of connection options in Postgresql's
// PQconnectdb() format, eg. "dbname=template1" to select from a database
// called template1, or "host=foo.bar.net user=smith" to connect to a
// backend running on host foo.bar.net, logging in as user smith.
//
// This assumes the existence of a database table "pqxxevents" containing a
// 2-digit "year" field, which is extended to a 4-digit format by assuming all
// year numbers of 70 or higher are in the 20th century, and all others in the
// 21st, and that no years before 1970 are possible.
namespace
{
// Global list of converted year numbers and what they've been converted to
map<int,int> theConversions;
// Convert year to 4-digit format.
int To4Digits(int Y)
{
int Result = Y;
if (Y < 0) throw runtime_error("Negative year: " + to_string(Y));
else if (Y < 70) Result += 2000;
else if (Y < 100) Result += 1900;
else if (Y < 1970) throw runtime_error("Unexpected year: " + to_string(Y));
return Result;
}
// Transaction definition for year-field update
class UpdateYears : public transactor<>
{
public:
UpdateYears() : transactor<>("YearUpdate") {}
// Transaction definition
void operator()(argument_type &T)
{
// First select all different years occurring in the table.
result R( T.exec("SELECT year FROM pqxxevents") );
// SELECT affects no rows.
assert(!R.affected_rows());
// See if we get reasonable type identifier for this column
const oid rctype = R.column_type(0);
const string rct = to_string(rctype);
if (rctype <= 0)
throw logic_error("Got strange type ID for column: " + rct);
const string rcol = R.column_name(0);
if (rcol.empty())
throw logic_error("Didn't get a name for column!");
const oid rcctype = R.column_type(rcol);
if (rcctype != rctype)
throw logic_error("Column has type " + rct + ", "
"but by name, it's " + to_string(rcctype));
const oid rawrcctype = R.column_type(rcol.c_str());
if (rawrcctype != rctype)
throw logic_error("Column has type " + rct + ", "
"but by C-style name it's " + to_string(rawrcctype));
// Note all different years currently occurring in the table, writing them
// and their correct mappings to m_Conversions
for (result::const_iterator r = R.begin(); r != R.end(); ++r)
{
int Y;
// Read year, and if it is non-null, note its converted value
if (r[0] >> Y) m_Conversions[Y] = To4Digits(Y);
// See if type identifiers are consistent
const oid tctype = r->column_type(0);
if (tctype != rctype)
throw logic_error("Column has type " + rct + ", "
"but tuple says it's " + to_string(tctype));
const oid ctctype = r->column_type(rcol);
if (ctctype != rctype)
throw logic_error("Column has type " + rct + ", "
"but by name, tuple says it's " + to_string(ctctype));
const oid rawctctype = r->column_type(rcol.c_str());
if (rawctctype != rctype)
throw logic_error("Column has type " + rct + ", "
"but by C-style name, tuple says it's " +
to_string(rawctctype));
const oid fctype = r[0].type();
if (fctype != rctype)
throw logic_error("Column has type " + rct + ", "
"but field says it's " + to_string(fctype));
}
result::size_type AffectedRows = 0;
// For each occurring year, write converted date back to whereever it may
// occur in the table. Since we're in a transaction, any changes made by
// others at the same time will not affect us.
for (map<int,int>::const_iterator c = m_Conversions.begin();
c != m_Conversions.end();
++c)
{
R = T.exec(("UPDATE pqxxevents "
"SET year=" + to_string(c->second) + " "
"WHERE year=" + to_string(c->first)).c_str());
AffectedRows += R.affected_rows();
}
cout << AffectedRows << " rows updated." << endl;
}
// Postprocessing code for successful execution
void OnCommit()
{
// Report the conversions performed once the transaction has completed
// successfully. Do not report conversions occurring in unsuccessful
// attempts, as some of those may have been removed from the table by
// somebody else between our attempts.
// Even if this fails (eg. because we run out of memory), the actual
// database transaction will still have been performed.
theConversions = m_Conversions;
}
// Postprocessing code for aborted execution attempt
void OnAbort(const char Reason[]) throw ()
{
try
{
// Notify user that the transaction attempt went wrong; we may retry.
cerr << "Transaction interrupted: " << Reason << endl;
}
catch (const exception &)
{
// Ignore any exceptions on cerr.
}
}
private:
// Local store of date conversions to be performed
map<int,int> m_Conversions;
};
} // namespace
int main(int, char *argv[])
{
try
{
connection C(argv[1]);
C.set_client_encoding("SQL_ASCII");
// Perform (an instantiation of) the UpdateYears transactor we've defined
// in the code above. This is where the work gets done.
C.perform(UpdateYears());
// Just for fun, report the exact conversions performed. Note that this
// list will be accurate even if other people were modifying the database
// at the same time; this property was established through use of the
// transactor framework.
for (map<int,int>::const_iterator i = theConversions.begin();
i != theConversions.end();
++i)
cout << '\t' << i->first << "\t-> " << i->second << endl;
}
catch (const sql_error &e)
{
// If we're interested in the text of a failed query, we can write separate
// exception handling code for this type of exception
cerr << "SQL error: " << e.what() << endl
<< "Query was: '" << e.query() << "'" << endl;
return 1;
}
catch (const exception &e)
{
// All exceptions thrown by libpqxx are derived from std::exception
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
// This is really unexpected (see above)
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
|
#include <cassert>
#include <iostream>
#include <map>
#include <pqxx/connection>
#include <pqxx/transaction>
#include <pqxx/transactor>
#include <pqxx/result>
using namespace PGSTD;
using namespace pqxx;
// Example program for libpqxx. Modify the database, retaining transactional
// integrity using the transactor framework.
//
// Usage: test007 [connect-string]
//
// Where connect-string is a set of connection options in Postgresql's
// PQconnectdb() format, eg. "dbname=template1" to select from a database
// called template1, or "host=foo.bar.net user=smith" to connect to a
// backend running on host foo.bar.net, logging in as user smith.
//
// This assumes the existence of a database table "pqxxevents" containing a
// 2-digit "year" field, which is extended to a 4-digit format by assuming all
// year numbers of 70 or higher are in the 20th century, and all others in the
// 21st, and that no years before 1970 are possible.
namespace
{
// Global list of converted year numbers and what they've been converted to
map<int,int> theConversions;
// Convert year to 4-digit format.
int To4Digits(int Y)
{
int Result = Y;
if (Y < 0) throw runtime_error("Negative year: " + to_string(Y));
else if (Y < 70) Result += 2000;
else if (Y < 100) Result += 1900;
else if (Y < 1970) throw runtime_error("Unexpected year: " + to_string(Y));
return Result;
}
// Transaction definition for year-field update
class UpdateYears : public transactor<>
{
public:
UpdateYears() : transactor<>("YearUpdate") {}
// Transaction definition
void operator()(argument_type &T)
{
// First select all different years occurring in the table.
result R( T.exec("SELECT year FROM pqxxevents") );
// SELECT affects no rows.
assert(!R.affected_rows());
// See if we get reasonable type identifier for this column
const oid rctype = R.column_type(0);
if (rctype != R.column_type(result::tuple::size_type(0)))
throw logic_error("Inconsistent result::column_type()");
const string rct = to_string(rctype);
if (rctype <= 0)
throw logic_error("Got strange type ID for column: " + rct);
const string rcol = R.column_name(0);
if (rcol.empty())
throw logic_error("Didn't get a name for column!");
const oid rcctype = R.column_type(rcol);
if (rcctype != rctype)
throw logic_error("Column has type " + rct + ", "
"but by name, it's " + to_string(rcctype));
const oid rawrcctype = R.column_type(rcol.c_str());
if (rawrcctype != rctype)
throw logic_error("Column has type " + rct + ", "
"but by C-style name it's " + to_string(rawrcctype));
// Note all different years currently occurring in the table, writing them
// and their correct mappings to m_Conversions
for (result::const_iterator r = R.begin(); r != R.end(); ++r)
{
int Y;
// Read year, and if it is non-null, note its converted value
if (r[0] >> Y) m_Conversions[Y] = To4Digits(Y);
// See if type identifiers are consistent
const oid tctype = r->column_type(0);
if (tctype != r->column_type(result::tuple::size_type(0)))
throw logic_error("Inconsistent result::tuple::column_type()");
if (tctype != rctype)
throw logic_error("Column has type " + rct + ", "
"but tuple says it's " + to_string(tctype));
const oid ctctype = r->column_type(rcol);
if (ctctype != rctype)
throw logic_error("Column has type " + rct + ", "
"but by name, tuple says it's " + to_string(ctctype));
const oid rawctctype = r->column_type(rcol.c_str());
if (rawctctype != rctype)
throw logic_error("Column has type " + rct + ", "
"but by C-style name, tuple says it's " +
to_string(rawctctype));
const oid fctype = r[0].type();
if (fctype != rctype)
throw logic_error("Column has type " + rct + ", "
"but field says it's " + to_string(fctype));
}
result::size_type AffectedRows = 0;
// For each occurring year, write converted date back to whereever it may
// occur in the table. Since we're in a transaction, any changes made by
// others at the same time will not affect us.
for (map<int,int>::const_iterator c = m_Conversions.begin();
c != m_Conversions.end();
++c)
{
R = T.exec(("UPDATE pqxxevents "
"SET year=" + to_string(c->second) + " "
"WHERE year=" + to_string(c->first)).c_str());
AffectedRows += R.affected_rows();
}
cout << AffectedRows << " rows updated." << endl;
}
// Postprocessing code for successful execution
void OnCommit()
{
// Report the conversions performed once the transaction has completed
// successfully. Do not report conversions occurring in unsuccessful
// attempts, as some of those may have been removed from the table by
// somebody else between our attempts.
// Even if this fails (eg. because we run out of memory), the actual
// database transaction will still have been performed.
theConversions = m_Conversions;
}
// Postprocessing code for aborted execution attempt
void OnAbort(const char Reason[]) throw ()
{
try
{
// Notify user that the transaction attempt went wrong; we may retry.
cerr << "Transaction interrupted: " << Reason << endl;
}
catch (const exception &)
{
// Ignore any exceptions on cerr.
}
}
private:
// Local store of date conversions to be performed
map<int,int> m_Conversions;
};
} // namespace
int main(int, char *argv[])
{
try
{
connection C(argv[1]);
C.set_client_encoding("SQL_ASCII");
// Perform (an instantiation of) the UpdateYears transactor we've defined
// in the code above. This is where the work gets done.
C.perform(UpdateYears());
// Just for fun, report the exact conversions performed. Note that this
// list will be accurate even if other people were modifying the database
// at the same time; this property was established through use of the
// transactor framework.
for (map<int,int>::const_iterator i = theConversions.begin();
i != theConversions.end();
++i)
cout << '\t' << i->first << "\t-> " << i->second << endl;
}
catch (const sql_error &e)
{
// If we're interested in the text of a failed query, we can write separate
// exception handling code for this type of exception
cerr << "SQL error: " << e.what() << endl
<< "Query was: '" << e.query() << "'" << endl;
return 1;
}
catch (const exception &e)
{
// All exceptions thrown by libpqxx are derived from std::exception
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
// This is really unexpected (see above)
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
|
Test result::tuple::column_type() for both int and size_type
|
Test result::tuple::column_type() for both int and size_type
|
C++
|
bsd-3-clause
|
mpapierski/pqxx,mpapierski/pqxx,mpapierski/pqxx
|
9aa38a05e76d3cf8bf17e3146a7e233c5dc60b45
|
NetIO/SockIO.cpp
|
NetIO/SockIO.cpp
|
/******************************************************************************
* This file is part of dirtsand. *
* *
* dirtsand is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* dirtsand is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with dirtsand. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************/
#include "SockIO.h"
#include "errors.h"
#include "settings.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/sendfile.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <mutex>
static const int SOCK_NO = 0;
static const int SOCK_YES = 1;
struct SocketHandle_Private
{
int m_sockfd;
union {
sockaddr m_addr;
sockaddr_in m_in4addr;
sockaddr_in6 m_in6addr;
sockaddr_storage m_addrMax;
};
socklen_t m_addrLen;
SocketHandle_Private() : m_addrLen(sizeof(m_addrMax)) { }
};
static void* get_in_addr(SocketHandle_Private* sock)
{
if (sock->m_addr.sa_family == AF_INET)
return &sock->m_in4addr.sin_addr;
return &sock->m_in6addr.sin6_addr;
}
static uint16_t get_in_port(SocketHandle_Private* sock)
{
if (sock->m_addr.sa_family == AF_INET)
return ntohs(sock->m_in4addr.sin_port);
return ntohs(sock->m_in6addr.sin6_port);
}
DS::SocketHandle DS::BindSocket(const char* address, const char* port)
{
int result;
int sockfd;
addrinfo info;
memset(&info, 0, sizeof(info));
info.ai_family = AF_UNSPEC;
info.ai_socktype = SOCK_STREAM;
info.ai_flags = AI_PASSIVE;
addrinfo* addrList;
result = getaddrinfo(address, port, &info, &addrList);
DS_PASSERT(result == 0);
addrinfo* addr_iter;
for (addr_iter = addrList; addr_iter != 0; addr_iter = addr_iter->ai_next) {
sockfd = socket(addr_iter->ai_family, addr_iter->ai_socktype,
addr_iter->ai_protocol);
if (sockfd == -1)
continue;
// Avoid annoying "Address already in use" messages when restarting
// the server.
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &SOCK_YES, sizeof(SOCK_YES));
if (bind(sockfd, addr_iter->ai_addr, addr_iter->ai_addrlen) == 0)
break;
fprintf(stderr, "[Bind] %s\n", strerror(errno));
// Couldn't bind, try the next one
close(sockfd);
}
freeaddrinfo(addrList);
// Die if we didn't get a successful socket
DS_PASSERT(addr_iter);
SocketHandle_Private* sockinfo = new SocketHandle_Private();
sockinfo->m_sockfd = sockfd;
result = getsockname(sockfd, &sockinfo->m_addr, &sockinfo->m_addrLen);
if (result != 0) {
delete sockinfo;
DS_PASSERT(0);
}
return reinterpret_cast<SocketHandle>(sockinfo);
}
void DS::ListenSock(const DS::SocketHandle sock, int backlog)
{
DS_DASSERT(sock);
int result = listen(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd, backlog);
DS_PASSERT(result == 0);
}
DS::SocketHandle DS::AcceptSock(const DS::SocketHandle sock)
{
DS_DASSERT(sock);
SocketHandle_Private* sockp = reinterpret_cast<SocketHandle_Private*>(sock);
SocketHandle_Private* client = new SocketHandle_Private();
client->m_sockfd = accept(sockp->m_sockfd, &client->m_addr, &client->m_addrLen);
if (client->m_sockfd < 0) {
delete client;
if (errno == EINVAL) {
throw DS::SockHup();
} else if (errno == ECONNABORTED) {
return 0;
} else {
fprintf(stderr, "Socket closed: %s\n", strerror(errno));
DS_DASSERT(0);
}
}
timeval tv;
tv.tv_sec = NET_TIMEOUT;
tv.tv_usec = 0;
setsockopt(client->m_sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
// Allow 50ms on blocking sends to account for net suckiness
tv.tv_sec = 0;
tv.tv_usec = (50 * 1000);
setsockopt(client->m_sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
// eap-tastic protocols require Nagle's algo be disabled
setsockopt(client->m_sockfd, IPPROTO_TCP, TCP_NODELAY, &SOCK_YES, sizeof(SOCK_YES));
return reinterpret_cast<SocketHandle>(client);
}
void DS::CloseSock(DS::SocketHandle sock)
{
DS_DASSERT(sock);
shutdown(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd, SHUT_RDWR);
close(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd);
}
void DS::FreeSock(DS::SocketHandle sock)
{
CloseSock(sock);
delete reinterpret_cast<SocketHandle_Private*>(sock);
}
DS::String DS::SockIpAddress(const DS::SocketHandle sock)
{
char addrbuf[256];
SocketHandle_Private* sockp = reinterpret_cast<SocketHandle_Private*>(sock);
inet_ntop(sockp->m_addr.sa_family, get_in_addr(sockp), addrbuf, 256);
return String::Format("%s/%u", addrbuf, get_in_port(sockp));
}
uint32_t DS::GetAddress4(const char* lookup)
{
addrinfo info;
memset(&info, 0, sizeof(info));
info.ai_family = AF_INET;
info.ai_socktype = SOCK_STREAM;
info.ai_flags = 0;
addrinfo* addrList;
int result = getaddrinfo(lookup, 0, &info, &addrList);
DS_PASSERT(result == 0);
DS_PASSERT(addrList != 0);
uint32_t addr = reinterpret_cast<sockaddr_in*>(addrList->ai_addr)->sin_addr.s_addr;
freeaddrinfo(addrList);
return ntohl(addr);
}
int DS::SockFd(const DS::SocketHandle sock)
{
return reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd;
}
void DS::SendBuffer(const DS::SocketHandle sock, const void* buffer, size_t size)
{
do {
ssize_t bytes = send(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd,
buffer, size, 0);
if (bytes < 0) {
if (errno == EPIPE || errno == ECONNRESET)
throw DS::SockHup();
} else if (bytes == 0) {
throw DS::SockHup();
}
DS_PASSERT(bytes > 0);
size -= bytes;
buffer = reinterpret_cast<const void*>(reinterpret_cast<const uint8_t*>(buffer) + bytes);
} while (size > 0);
if (size > 0) {
CloseSock(sock);
throw DS::SockHup();
}
}
void DS::SendFile(const DS::SocketHandle sock, const void* buffer, size_t bufsz,
int fd, off_t* offset, size_t fdsz)
{
SocketHandle_Private* imp = reinterpret_cast<SocketHandle_Private*>(sock);
// Send the prepended buffer
setsockopt(imp->m_sockfd, IPPROTO_TCP, TCP_CORK, &SOCK_YES, sizeof(SOCK_YES));
while (bufsz > 0) {
ssize_t bytes = send(imp->m_sockfd, buffer, bufsz, 0);
if (bytes < 0 && (errno == EPIPE || errno == ECONNRESET))
throw DS::SockHup();
else if (bytes == 0)
throw DS::SockHup();
DS_PASSERT(bytes > 0);
bufsz -= bytes;
buffer = reinterpret_cast<const void*>(reinterpret_cast<const uint8_t*>(buffer) + bytes);
}
// Now send the file data via a system call
while (fdsz > 0) {
ssize_t bytes = sendfile(imp->m_sockfd, fd, offset, fdsz);
if (bytes < 0 && (errno == EAGAIN))
continue;
else if (bytes < 0 && (errno == EPIPE || errno == ECONNRESET))
throw DS::SockHup();
else if (bytes == 0)
throw DS::SockHup();
DS_PASSERT(bytes > 0);
fdsz -= bytes;
}
setsockopt(imp->m_sockfd, IPPROTO_TCP, TCP_CORK, &SOCK_NO, sizeof(SOCK_NO));
}
void DS::RecvBuffer(const DS::SocketHandle sock, void* buffer, size_t size)
{
while (size > 0) {
ssize_t bytes = recv(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd,
buffer, size, 0);
if (bytes < 0 && (errno == ECONNRESET || errno == EAGAIN || errno == EWOULDBLOCK || errno == EPIPE))
throw DS::SockHup();
if (bytes < 0 && errno == EINTR)
continue;
else if (bytes == 0)
throw DS::SockHup();
DS_PASSERT(bytes > 0);
size -= bytes;
buffer = reinterpret_cast<void*>(reinterpret_cast<uint8_t*>(buffer) + bytes);
}
}
size_t DS::PeekSize(const SocketHandle sock)
{
uint8_t buffer[256];
ssize_t bytes = recv(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd,
buffer, 256, MSG_PEEK | MSG_TRUNC);
if (bytes < 0 && (errno == ECONNRESET || errno == EAGAIN || errno == EWOULDBLOCK))
throw DS::SockHup();
else if (bytes == 0)
throw DS::SockHup();
DS_PASSERT(bytes > 0);
return static_cast<size_t>(bytes);
}
|
/******************************************************************************
* This file is part of dirtsand. *
* *
* dirtsand is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* dirtsand is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with dirtsand. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************/
#include "SockIO.h"
#include "errors.h"
#include "settings.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/sendfile.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <mutex>
static const int SOCK_NO = 0;
static const int SOCK_YES = 1;
struct SocketHandle_Private
{
int m_sockfd;
union {
sockaddr m_addr;
sockaddr_in m_in4addr;
sockaddr_in6 m_in6addr;
sockaddr_storage m_addrMax;
};
socklen_t m_addrLen;
SocketHandle_Private() : m_addrLen(sizeof(m_addrMax)) { }
};
static void* get_in_addr(SocketHandle_Private* sock)
{
if (sock->m_addr.sa_family == AF_INET)
return &sock->m_in4addr.sin_addr;
return &sock->m_in6addr.sin6_addr;
}
static uint16_t get_in_port(SocketHandle_Private* sock)
{
if (sock->m_addr.sa_family == AF_INET)
return ntohs(sock->m_in4addr.sin_port);
return ntohs(sock->m_in6addr.sin6_port);
}
DS::SocketHandle DS::BindSocket(const char* address, const char* port)
{
int result;
int sockfd;
addrinfo info;
memset(&info, 0, sizeof(info));
info.ai_family = AF_UNSPEC;
info.ai_socktype = SOCK_STREAM;
info.ai_flags = AI_PASSIVE;
addrinfo* addrList;
result = getaddrinfo(address, port, &info, &addrList);
DS_PASSERT(result == 0);
addrinfo* addr_iter;
for (addr_iter = addrList; addr_iter != 0; addr_iter = addr_iter->ai_next) {
sockfd = socket(addr_iter->ai_family, addr_iter->ai_socktype,
addr_iter->ai_protocol);
if (sockfd == -1)
continue;
// Avoid annoying "Address already in use" messages when restarting
// the server.
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &SOCK_YES, sizeof(SOCK_YES));
if (bind(sockfd, addr_iter->ai_addr, addr_iter->ai_addrlen) == 0)
break;
fprintf(stderr, "[Bind] %s\n", strerror(errno));
// Couldn't bind, try the next one
close(sockfd);
}
freeaddrinfo(addrList);
// Die if we didn't get a successful socket
DS_PASSERT(addr_iter);
SocketHandle_Private* sockinfo = new SocketHandle_Private();
sockinfo->m_sockfd = sockfd;
result = getsockname(sockfd, &sockinfo->m_addr, &sockinfo->m_addrLen);
if (result != 0) {
delete sockinfo;
DS_PASSERT(0);
}
return reinterpret_cast<SocketHandle>(sockinfo);
}
void DS::ListenSock(const DS::SocketHandle sock, int backlog)
{
DS_DASSERT(sock);
int result = listen(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd, backlog);
DS_PASSERT(result == 0);
}
DS::SocketHandle DS::AcceptSock(const DS::SocketHandle sock)
{
DS_DASSERT(sock);
SocketHandle_Private* sockp = reinterpret_cast<SocketHandle_Private*>(sock);
SocketHandle_Private* client = new SocketHandle_Private();
client->m_sockfd = accept(sockp->m_sockfd, &client->m_addr, &client->m_addrLen);
if (client->m_sockfd < 0) {
delete client;
if (errno == EINVAL) {
throw DS::SockHup();
} else if (errno == ECONNABORTED) {
return 0;
} else {
fprintf(stderr, "Socket closed: %s\n", strerror(errno));
DS_DASSERT(0);
}
}
timeval tv;
tv.tv_sec = NET_TIMEOUT;
tv.tv_usec = 0;
setsockopt(client->m_sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
// eap-tastic protocols require Nagle's algo be disabled
setsockopt(client->m_sockfd, IPPROTO_TCP, TCP_NODELAY, &SOCK_YES, sizeof(SOCK_YES));
return reinterpret_cast<SocketHandle>(client);
}
void DS::CloseSock(DS::SocketHandle sock)
{
DS_DASSERT(sock);
shutdown(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd, SHUT_RDWR);
close(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd);
}
void DS::FreeSock(DS::SocketHandle sock)
{
CloseSock(sock);
delete reinterpret_cast<SocketHandle_Private*>(sock);
}
DS::String DS::SockIpAddress(const DS::SocketHandle sock)
{
char addrbuf[256];
SocketHandle_Private* sockp = reinterpret_cast<SocketHandle_Private*>(sock);
inet_ntop(sockp->m_addr.sa_family, get_in_addr(sockp), addrbuf, 256);
return String::Format("%s/%u", addrbuf, get_in_port(sockp));
}
uint32_t DS::GetAddress4(const char* lookup)
{
addrinfo info;
memset(&info, 0, sizeof(info));
info.ai_family = AF_INET;
info.ai_socktype = SOCK_STREAM;
info.ai_flags = 0;
addrinfo* addrList;
int result = getaddrinfo(lookup, 0, &info, &addrList);
DS_PASSERT(result == 0);
DS_PASSERT(addrList != 0);
uint32_t addr = reinterpret_cast<sockaddr_in*>(addrList->ai_addr)->sin_addr.s_addr;
freeaddrinfo(addrList);
return ntohl(addr);
}
int DS::SockFd(const DS::SocketHandle sock)
{
return reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd;
}
void DS::SendBuffer(const DS::SocketHandle sock, const void* buffer, size_t size)
{
do {
ssize_t bytes = send(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd,
buffer, size, 0);
if (bytes < 0) {
if (errno == EPIPE || errno == ECONNRESET)
throw DS::SockHup();
} else if (bytes == 0) {
throw DS::SockHup();
}
DS_PASSERT(bytes > 0);
size -= bytes;
buffer = reinterpret_cast<const void*>(reinterpret_cast<const uint8_t*>(buffer) + bytes);
} while (size > 0);
if (size > 0) {
CloseSock(sock);
throw DS::SockHup();
}
}
void DS::SendFile(const DS::SocketHandle sock, const void* buffer, size_t bufsz,
int fd, off_t* offset, size_t fdsz)
{
SocketHandle_Private* imp = reinterpret_cast<SocketHandle_Private*>(sock);
// Send the prepended buffer
setsockopt(imp->m_sockfd, IPPROTO_TCP, TCP_CORK, &SOCK_YES, sizeof(SOCK_YES));
while (bufsz > 0) {
ssize_t bytes = send(imp->m_sockfd, buffer, bufsz, 0);
if (bytes < 0 && (errno == EPIPE || errno == ECONNRESET))
throw DS::SockHup();
else if (bytes == 0)
throw DS::SockHup();
DS_PASSERT(bytes > 0);
bufsz -= bytes;
buffer = reinterpret_cast<const void*>(reinterpret_cast<const uint8_t*>(buffer) + bytes);
}
// Now send the file data via a system call
while (fdsz > 0) {
ssize_t bytes = sendfile(imp->m_sockfd, fd, offset, fdsz);
if (bytes < 0 && (errno == EAGAIN))
continue;
else if (bytes < 0 && (errno == EPIPE || errno == ECONNRESET))
throw DS::SockHup();
else if (bytes == 0)
throw DS::SockHup();
DS_PASSERT(bytes > 0);
fdsz -= bytes;
}
setsockopt(imp->m_sockfd, IPPROTO_TCP, TCP_CORK, &SOCK_NO, sizeof(SOCK_NO));
}
void DS::RecvBuffer(const DS::SocketHandle sock, void* buffer, size_t size)
{
while (size > 0) {
ssize_t bytes = recv(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd,
buffer, size, 0);
if (bytes < 0 && (errno == ECONNRESET || errno == EAGAIN || errno == EWOULDBLOCK || errno == EPIPE))
throw DS::SockHup();
if (bytes < 0 && errno == EINTR)
continue;
else if (bytes == 0)
throw DS::SockHup();
DS_PASSERT(bytes > 0);
size -= bytes;
buffer = reinterpret_cast<void*>(reinterpret_cast<uint8_t*>(buffer) + bytes);
}
}
size_t DS::PeekSize(const SocketHandle sock)
{
uint8_t buffer[256];
ssize_t bytes = recv(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd,
buffer, 256, MSG_PEEK | MSG_TRUNC);
if (bytes < 0 && (errno == ECONNRESET || errno == EAGAIN || errno == EWOULDBLOCK))
throw DS::SockHup();
else if (bytes == 0)
throw DS::SockHup();
DS_PASSERT(bytes > 0);
return static_cast<size_t>(bytes);
}
|
Remove a sneaky timeout
|
Remove a sneaky timeout
We removed the handling for timeouts, so BOOM
|
C++
|
agpl-3.0
|
GehnShard/dirtsand,H-uru/dirtsand,H-uru/dirtsand,GehnShard/dirtsand
|
f23dfa3153f3b1f2aac1aa3c148f0ea2686fb8b1
|
chrome/browser/safe_browsing/filter_false_positive_perftest.cc
|
chrome/browser/safe_browsing/filter_false_positive_perftest.cc
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This test performs a series false positive checks using a list of URLs
// against a known set of SafeBrowsing data.
//
// It uses a normal SafeBrowsing database to create a bloom filter where it
// looks up all the URLs in the url file. A URL that has a prefix found in the
// bloom filter and found in the database is considered a hit: a valid lookup
// that will result in a gethash request. A URL that has a prefix found in the
// bloom filter but not in the database is a miss: a false positive lookup that
// will result in an unnecessary gethash request.
//
// By varying the size of the bloom filter and using a constant set of
// SafeBrowsing data, we can check a known set of URLs against the filter and
// determine the false positive rate.
//
// False positive calculation usage:
// $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.FalsePositives
// --filter-start=<integer>
// --filter-steps=<integer>
// --filter-verbose
//
// --filter-start: The filter multiplier to begin with. This represents the
// number of bits per prefix of memory to use in the filter.
// The default value is identical to the current SafeBrowsing
// database value.
// --filter-steps: The number of iterations to run, with each iteration
// increasing the filter multiplier by 1. The default value
// is 1.
// --filter-verbose: Used to print out the hit / miss results per URL.
// --filter-csv: The URL file contains information about the number of
// unique views (the popularity) of each URL. See the format
// description below.
//
//
// Hash compute time usage:
// $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.HashTime
// --filter-num-checks=<integer>
//
// --filter-num-checks: The number of hash look ups to perform on the bloom
// filter. The default is 10 million.
//
// Data files:
// chrome/test/data/safe_browsing/filter/database
// chrome/test/data/safe_browsing/filter/urls
//
// database: A normal SafeBrowsing database.
// urls: A text file containing a list of URLs, one per line. If the option
// --filter-csv is specified, the format of each line in the file is
// <url>,<weight> where weight is an integer indicating the number of
// unique views for the URL.
#include <fstream>
#include <vector>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/rand_util.h"
#include "base/scoped_ptr.h"
#include "base/sha2.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/time.h"
#include "chrome/browser/safe_browsing/bloom_filter.h"
#include "chrome/browser/safe_browsing/safe_browsing_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/sqlite_compiled_statement.h"
#include "chrome/common/sqlite_utils.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
namespace {
// Ensures the SafeBrowsing database is closed properly.
class ScopedPerfDatabase {
public:
explicit ScopedPerfDatabase(sqlite3* db) : db_(db) {}
~ScopedPerfDatabase() {
sqlite3_close(db_);
}
private:
sqlite3* db_;
DISALLOW_COPY_AND_ASSIGN(ScopedPerfDatabase);
};
// Command line flags.
const wchar_t kFilterVerbose[] = L"filter-verbose";
const wchar_t kFilterStart[] = L"filter-start";
const wchar_t kFilterSteps[] = L"filter-steps";
const wchar_t kFilterCsv[] = L"filter-csv";
const wchar_t kFilterNumChecks[] = L"filter-num-checks";
// Number of hash checks to make during performance testing.
static const int kNumHashChecks = 10000000;
// Returns the path to the data used in this test, relative to the top of the
// source directory.
FilePath GetFullDataPath() {
FilePath full_path;
CHECK(PathService::Get(chrome::DIR_TEST_DATA, &full_path));
full_path = full_path.Append(FILE_PATH_LITERAL("safe_browsing"));
full_path = full_path.Append(FILE_PATH_LITERAL("filter"));
CHECK(file_util::PathExists(full_path));
return full_path;
}
// Constructs a bloom filter of the appropriate size from the provided prefixes.
void BuildBloomFilter(int size_multiplier,
const std::vector<SBPrefix>& prefixes,
BloomFilter** bloom_filter) {
// Create a BloomFilter with the specified size.
const int key_count = std::max(static_cast<int>(prefixes.size()),
BloomFilter::kBloomFilterMinSize);
const int filter_size = key_count * size_multiplier;
*bloom_filter = new BloomFilter(filter_size);
// Add the prefixes to it.
for (size_t i = 0; i < prefixes.size(); ++i)
(*bloom_filter)->Insert(prefixes[i]);
std::cout << "Bloom filter with prefixes: " << prefixes.size()
<< ", multiplier: " << size_multiplier
<< ", size (bytes): " << (*bloom_filter)->size()
<< std::endl;
}
// Reads the set of add prefixes contained in a SafeBrowsing database into a
// sorted array suitable for fast searching. This takes significantly less time
// to look up a given prefix than performing SQL queries.
bool ReadDatabase(const FilePath& path, std::vector<SBPrefix>* prefixes) {
FilePath database_file = path.Append(FILE_PATH_LITERAL("database"));
sqlite3* db = NULL;
if (sqlite_utils::OpenSqliteDb(database_file, &db) != SQLITE_OK) {
sqlite3_close(db);
return false;
}
ScopedPerfDatabase database(db);
scoped_ptr<SqliteStatementCache> sql_cache(new SqliteStatementCache(db));
// Get the number of items in the add_prefix table.
std::string sql = "SELECT COUNT(*) FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(count_statement, *sql_cache, sql.c_str());
if (!count_statement.is_valid())
return false;
if (count_statement->step() != SQLITE_ROW)
return false;
const int count = count_statement->column_int(0);
// Load them into a prefix vector and sort
prefixes->reserve(count);
sql = "SELECT prefix FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(prefix_statement, *sql_cache, sql.c_str());
if (!prefix_statement.is_valid())
return false;
while (prefix_statement->step() == SQLITE_ROW)
prefixes->push_back(prefix_statement->column_int(0));
DCHECK(static_cast<int>(prefixes->size()) == count);
sort(prefixes->begin(), prefixes->end());
return true;
}
// Generates all legal SafeBrowsing prefixes for the specified URL, and returns
// the set of Prefixes that exist in the bloom filter. The function returns the
// number of host + path combinations checked.
int GeneratePrefixHits(const std::string url,
BloomFilter* bloom_filter,
std::vector<SBPrefix>* prefixes) {
GURL url_check(url);
std::vector<std::string> hosts;
if (url_check.HostIsIPAddress()) {
hosts.push_back(url_check.host());
} else {
safe_browsing_util::GenerateHostsToCheck(url_check, &hosts);
}
std::vector<std::string> paths;
safe_browsing_util::GeneratePathsToCheck(url_check, &paths);
for (size_t i = 0; i < hosts.size(); ++i) {
for (size_t j = 0; j < paths.size(); ++j) {
SBPrefix prefix;
base::SHA256HashString(hosts[i] + paths[j], &prefix, sizeof(prefix));
if (bloom_filter->Exists(prefix))
prefixes->push_back(prefix);
}
}
return hosts.size() * paths.size();
}
// Binary search of sorted prefixes.
bool IsPrefixInDatabase(SBPrefix prefix,
const std::vector<SBPrefix>& prefixes) {
if (prefixes.empty())
return false;
int low = 0;
int high = prefixes.size() - 1;
while (low <= high) {
int mid = ((unsigned int)low + (unsigned int)high) >> 1;
SBPrefix prefix_mid = prefixes[mid];
if (prefix_mid == prefix)
return true;
if (prefix_mid < prefix)
low = mid + 1;
else
high = mid - 1;
}
return false;
}
// Construct a bloom filter with the given prefixes and multiplier, and test the
// false positive rate (misses) against a URL list.
void CalculateBloomFilterFalsePositives(
int size_multiplier,
const FilePath& data_dir,
const std::vector<SBPrefix>& prefix_list) {
BloomFilter* bloom_filter = NULL;
BuildBloomFilter(size_multiplier, prefix_list, &bloom_filter);
scoped_refptr<BloomFilter> scoped_filter(bloom_filter);
// Read in data file line at a time.
FilePath url_file = data_dir.Append(FILE_PATH_LITERAL("urls"));
std::ifstream url_stream(WideToASCII(url_file.ToWStringHack()).c_str());
// Keep track of stats
int hits = 0;
int misses = 0;
int weighted_hits = 0;
int weighted_misses = 0;
int url_count = 0;
int prefix_count = 0;
// Print out volumes of data (per URL hit and miss information).
bool verbose = CommandLine::ForCurrentProcess()->HasSwitch(kFilterVerbose);
bool use_weights = CommandLine::ForCurrentProcess()->HasSwitch(kFilterCsv);
std::string url;
while (std::getline(url_stream, url)) {
++url_count;
// Handle a format that contains URLs weighted by unique views.
int weight = 1;
if (use_weights) {
std::string::size_type pos = url.find_last_of(",");
if (pos != std::string::npos) {
base::StringToInt(std::string(url, pos + 1), &weight);
url = url.substr(0, pos);
}
}
// See if the URL is in the bloom filter.
std::vector<SBPrefix> prefixes;
prefix_count += GeneratePrefixHits(url, bloom_filter, &prefixes);
// See if the prefix is actually in the database (in-memory prefix list).
for (size_t i = 0; i < prefixes.size(); ++i) {
if (IsPrefixInDatabase(prefixes[i], prefix_list)) {
++hits;
weighted_hits += weight;
if (verbose) {
std::cout << "Hit for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
} else {
++misses;
weighted_misses += weight;
if (verbose) {
std::cout << "Miss for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
}
}
}
// Print out the results for this test.
std::cout << "URLs checked: " << url_count
<< ", prefix compares: " << prefix_count
<< ", hits: " << hits
<< ", misses: " << misses;
if (use_weights) {
std::cout << ", weighted hits: " << weighted_hits
<< ", weighted misses: " << weighted_misses;
}
std::cout << std::endl;
}
} // namespace
// This test can take several minutes to perform its calculations, so it should
// be disabled until you need to run it.
TEST(SafeBrowsingBloomFilter, FalsePositives) {
std::vector<SBPrefix> prefix_list;
FilePath data_dir = GetFullDataPath();
ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));
const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
int start = BloomFilter::kBloomFilterSizeRatio;
if (cmd_line.HasSwitch(kFilterStart)) {
ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValueASCII(kFilterStart),
&start));
}
int steps = 1;
if (cmd_line.HasSwitch(kFilterSteps)) {
ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValueASCII(kFilterSteps),
&steps));
}
int stop = start + steps;
for (int multiplier = start; multiplier < stop; ++multiplier)
CalculateBloomFilterFalsePositives(multiplier, data_dir, prefix_list);
}
// Computes the time required for performing a number of look ups in a bloom
// filter. This is useful for measuring the performance of new hash functions.
TEST(SafeBrowsingBloomFilter, HashTime) {
// Read the data from the database.
std::vector<SBPrefix> prefix_list;
FilePath data_dir = GetFullDataPath();
ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));
const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
int num_checks = kNumHashChecks;
if (cmd_line.HasSwitch(kFilterNumChecks)) {
ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValue(kFilterNumChecks),
&num_checks));
}
// Populate the bloom filter and measure the time.
BloomFilter* bloom_filter = NULL;
Time populate_before = Time::Now();
BuildBloomFilter(BloomFilter::kBloomFilterSizeRatio,
prefix_list, &bloom_filter);
TimeDelta populate = Time::Now() - populate_before;
// Check a large number of random prefixes against the filter.
int hits = 0;
Time check_before = Time::Now();
for (int i = 0; i < num_checks; ++i) {
uint32 prefix = static_cast<uint32>(base::RandUint64());
if (bloom_filter->Exists(prefix))
++hits;
}
TimeDelta check = Time::Now() - check_before;
int64 time_per_insert = populate.InMicroseconds() /
static_cast<int>(prefix_list.size());
int64 time_per_check = check.InMicroseconds() / num_checks;
std::cout << "Time results for checks: " << num_checks
<< ", prefixes: " << prefix_list.size()
<< ", populate time (ms): " << populate.InMilliseconds()
<< ", check time (ms): " << check.InMilliseconds()
<< ", hits: " << hits
<< ", per-populate (us): " << time_per_insert
<< ", per-check (us): " << time_per_check
<< std::endl;
}
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This test performs a series false positive checks using a list of URLs
// against a known set of SafeBrowsing data.
//
// It uses a normal SafeBrowsing database to create a bloom filter where it
// looks up all the URLs in the url file. A URL that has a prefix found in the
// bloom filter and found in the database is considered a hit: a valid lookup
// that will result in a gethash request. A URL that has a prefix found in the
// bloom filter but not in the database is a miss: a false positive lookup that
// will result in an unnecessary gethash request.
//
// By varying the size of the bloom filter and using a constant set of
// SafeBrowsing data, we can check a known set of URLs against the filter and
// determine the false positive rate.
//
// False positive calculation usage:
// $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.FalsePositives
// --filter-start=<integer>
// --filter-steps=<integer>
// --filter-verbose
//
// --filter-start: The filter multiplier to begin with. This represents the
// number of bits per prefix of memory to use in the filter.
// The default value is identical to the current SafeBrowsing
// database value.
// --filter-steps: The number of iterations to run, with each iteration
// increasing the filter multiplier by 1. The default value
// is 1.
// --filter-verbose: Used to print out the hit / miss results per URL.
// --filter-csv: The URL file contains information about the number of
// unique views (the popularity) of each URL. See the format
// description below.
//
//
// Hash compute time usage:
// $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.HashTime
// --filter-num-checks=<integer>
//
// --filter-num-checks: The number of hash look ups to perform on the bloom
// filter. The default is 10 million.
//
// Data files:
// chrome/test/data/safe_browsing/filter/database
// chrome/test/data/safe_browsing/filter/urls
//
// database: A normal SafeBrowsing database.
// urls: A text file containing a list of URLs, one per line. If the option
// --filter-csv is specified, the format of each line in the file is
// <url>,<weight> where weight is an integer indicating the number of
// unique views for the URL.
#include <fstream>
#include <vector>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/rand_util.h"
#include "base/scoped_ptr.h"
#include "base/sha2.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/time.h"
#include "chrome/browser/safe_browsing/bloom_filter.h"
#include "chrome/browser/safe_browsing/safe_browsing_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/sqlite_compiled_statement.h"
#include "chrome/common/sqlite_utils.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
namespace {
// Ensures the SafeBrowsing database is closed properly.
class ScopedPerfDatabase {
public:
explicit ScopedPerfDatabase(sqlite3* db) : db_(db) {}
~ScopedPerfDatabase() {
sqlite3_close(db_);
}
private:
sqlite3* db_;
DISALLOW_COPY_AND_ASSIGN(ScopedPerfDatabase);
};
// Command line flags.
const char kFilterVerbose[] = "filter-verbose";
const char kFilterStart[] = "filter-start";
const char kFilterSteps[] = "filter-steps";
const char kFilterCsv[] = "filter-csv";
const char kFilterNumChecks[] = "filter-num-checks";
// Number of hash checks to make during performance testing.
static const int kNumHashChecks = 10000000;
// Returns the path to the data used in this test, relative to the top of the
// source directory.
FilePath GetFullDataPath() {
FilePath full_path;
CHECK(PathService::Get(chrome::DIR_TEST_DATA, &full_path));
full_path = full_path.Append(FILE_PATH_LITERAL("safe_browsing"));
full_path = full_path.Append(FILE_PATH_LITERAL("filter"));
CHECK(file_util::PathExists(full_path));
return full_path;
}
// Constructs a bloom filter of the appropriate size from the provided prefixes.
void BuildBloomFilter(int size_multiplier,
const std::vector<SBPrefix>& prefixes,
BloomFilter** bloom_filter) {
// Create a BloomFilter with the specified size.
const int key_count = std::max(static_cast<int>(prefixes.size()),
BloomFilter::kBloomFilterMinSize);
const int filter_size = key_count * size_multiplier;
*bloom_filter = new BloomFilter(filter_size);
// Add the prefixes to it.
for (size_t i = 0; i < prefixes.size(); ++i)
(*bloom_filter)->Insert(prefixes[i]);
std::cout << "Bloom filter with prefixes: " << prefixes.size()
<< ", multiplier: " << size_multiplier
<< ", size (bytes): " << (*bloom_filter)->size()
<< std::endl;
}
// Reads the set of add prefixes contained in a SafeBrowsing database into a
// sorted array suitable for fast searching. This takes significantly less time
// to look up a given prefix than performing SQL queries.
bool ReadDatabase(const FilePath& path, std::vector<SBPrefix>* prefixes) {
FilePath database_file = path.Append(FILE_PATH_LITERAL("database"));
sqlite3* db = NULL;
if (sqlite_utils::OpenSqliteDb(database_file, &db) != SQLITE_OK) {
sqlite3_close(db);
return false;
}
ScopedPerfDatabase database(db);
scoped_ptr<SqliteStatementCache> sql_cache(new SqliteStatementCache(db));
// Get the number of items in the add_prefix table.
std::string sql = "SELECT COUNT(*) FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(count_statement, *sql_cache, sql.c_str());
if (!count_statement.is_valid())
return false;
if (count_statement->step() != SQLITE_ROW)
return false;
const int count = count_statement->column_int(0);
// Load them into a prefix vector and sort
prefixes->reserve(count);
sql = "SELECT prefix FROM add_prefix";
SQLITE_UNIQUE_STATEMENT(prefix_statement, *sql_cache, sql.c_str());
if (!prefix_statement.is_valid())
return false;
while (prefix_statement->step() == SQLITE_ROW)
prefixes->push_back(prefix_statement->column_int(0));
DCHECK(static_cast<int>(prefixes->size()) == count);
sort(prefixes->begin(), prefixes->end());
return true;
}
// Generates all legal SafeBrowsing prefixes for the specified URL, and returns
// the set of Prefixes that exist in the bloom filter. The function returns the
// number of host + path combinations checked.
int GeneratePrefixHits(const std::string url,
BloomFilter* bloom_filter,
std::vector<SBPrefix>* prefixes) {
GURL url_check(url);
std::vector<std::string> hosts;
if (url_check.HostIsIPAddress()) {
hosts.push_back(url_check.host());
} else {
safe_browsing_util::GenerateHostsToCheck(url_check, &hosts);
}
std::vector<std::string> paths;
safe_browsing_util::GeneratePathsToCheck(url_check, &paths);
for (size_t i = 0; i < hosts.size(); ++i) {
for (size_t j = 0; j < paths.size(); ++j) {
SBPrefix prefix;
base::SHA256HashString(hosts[i] + paths[j], &prefix, sizeof(prefix));
if (bloom_filter->Exists(prefix))
prefixes->push_back(prefix);
}
}
return hosts.size() * paths.size();
}
// Binary search of sorted prefixes.
bool IsPrefixInDatabase(SBPrefix prefix,
const std::vector<SBPrefix>& prefixes) {
if (prefixes.empty())
return false;
int low = 0;
int high = prefixes.size() - 1;
while (low <= high) {
int mid = ((unsigned int)low + (unsigned int)high) >> 1;
SBPrefix prefix_mid = prefixes[mid];
if (prefix_mid == prefix)
return true;
if (prefix_mid < prefix)
low = mid + 1;
else
high = mid - 1;
}
return false;
}
// Construct a bloom filter with the given prefixes and multiplier, and test the
// false positive rate (misses) against a URL list.
void CalculateBloomFilterFalsePositives(
int size_multiplier,
const FilePath& data_dir,
const std::vector<SBPrefix>& prefix_list) {
BloomFilter* bloom_filter = NULL;
BuildBloomFilter(size_multiplier, prefix_list, &bloom_filter);
scoped_refptr<BloomFilter> scoped_filter(bloom_filter);
// Read in data file line at a time.
FilePath url_file = data_dir.Append(FILE_PATH_LITERAL("urls"));
std::ifstream url_stream(WideToASCII(url_file.ToWStringHack()).c_str());
// Keep track of stats
int hits = 0;
int misses = 0;
int weighted_hits = 0;
int weighted_misses = 0;
int url_count = 0;
int prefix_count = 0;
// Print out volumes of data (per URL hit and miss information).
bool verbose = CommandLine::ForCurrentProcess()->HasSwitch(kFilterVerbose);
bool use_weights = CommandLine::ForCurrentProcess()->HasSwitch(kFilterCsv);
std::string url;
while (std::getline(url_stream, url)) {
++url_count;
// Handle a format that contains URLs weighted by unique views.
int weight = 1;
if (use_weights) {
std::string::size_type pos = url.find_last_of(",");
if (pos != std::string::npos) {
base::StringToInt(std::string(url, pos + 1), &weight);
url = url.substr(0, pos);
}
}
// See if the URL is in the bloom filter.
std::vector<SBPrefix> prefixes;
prefix_count += GeneratePrefixHits(url, bloom_filter, &prefixes);
// See if the prefix is actually in the database (in-memory prefix list).
for (size_t i = 0; i < prefixes.size(); ++i) {
if (IsPrefixInDatabase(prefixes[i], prefix_list)) {
++hits;
weighted_hits += weight;
if (verbose) {
std::cout << "Hit for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
} else {
++misses;
weighted_misses += weight;
if (verbose) {
std::cout << "Miss for URL: " << url
<< " (prefix = " << prefixes[i] << ")"
<< std::endl;
}
}
}
}
// Print out the results for this test.
std::cout << "URLs checked: " << url_count
<< ", prefix compares: " << prefix_count
<< ", hits: " << hits
<< ", misses: " << misses;
if (use_weights) {
std::cout << ", weighted hits: " << weighted_hits
<< ", weighted misses: " << weighted_misses;
}
std::cout << std::endl;
}
} // namespace
// This test can take several minutes to perform its calculations, so it should
// be disabled until you need to run it.
TEST(SafeBrowsingBloomFilter, FalsePositives) {
std::vector<SBPrefix> prefix_list;
FilePath data_dir = GetFullDataPath();
ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));
const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
int start = BloomFilter::kBloomFilterSizeRatio;
if (cmd_line.HasSwitch(kFilterStart)) {
ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValueASCII(kFilterStart),
&start));
}
int steps = 1;
if (cmd_line.HasSwitch(kFilterSteps)) {
ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValueASCII(kFilterSteps),
&steps));
}
int stop = start + steps;
for (int multiplier = start; multiplier < stop; ++multiplier)
CalculateBloomFilterFalsePositives(multiplier, data_dir, prefix_list);
}
// Computes the time required for performing a number of look ups in a bloom
// filter. This is useful for measuring the performance of new hash functions.
TEST(SafeBrowsingBloomFilter, HashTime) {
// Read the data from the database.
std::vector<SBPrefix> prefix_list;
FilePath data_dir = GetFullDataPath();
ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));
const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
int num_checks = kNumHashChecks;
if (cmd_line.HasSwitch(kFilterNumChecks)) {
ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValue(kFilterNumChecks),
&num_checks));
}
// Populate the bloom filter and measure the time.
BloomFilter* bloom_filter = NULL;
Time populate_before = Time::Now();
BuildBloomFilter(BloomFilter::kBloomFilterSizeRatio,
prefix_list, &bloom_filter);
TimeDelta populate = Time::Now() - populate_before;
// Check a large number of random prefixes against the filter.
int hits = 0;
Time check_before = Time::Now();
for (int i = 0; i < num_checks; ++i) {
uint32 prefix = static_cast<uint32>(base::RandUint64());
if (bloom_filter->Exists(prefix))
++hits;
}
TimeDelta check = Time::Now() - check_before;
int64 time_per_insert = populate.InMicroseconds() /
static_cast<int>(prefix_list.size());
int64 time_per_check = check.InMicroseconds() / num_checks;
std::cout << "Time results for checks: " << num_checks
<< ", prefixes: " << prefix_list.size()
<< ", populate time (ms): " << populate.InMilliseconds()
<< ", check time (ms): " << check.InMilliseconds()
<< ", hits: " << hits
<< ", per-populate (us): " << time_per_insert
<< ", per-check (us): " << time_per_check
<< std::endl;
}
|
Build fix.
|
Build fix.
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@54863 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
markYoungH/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,Chilledheart/chromium,bright-sparks/chromium-spacewalk,Chilledheart/chromium,keishi/chromium,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,patrickm/chromium.src,zcbenz/cefode-chromium,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,rogerwang/chromium,M4sse/chromium.src,dednal/chromium.src,ChromiumWebApps/chromium,markYoungH/chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,ltilve/chromium,robclark/chromium,robclark/chromium,jaruba/chromium.src,ltilve/chromium,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,ondra-novak/chromium.src,robclark/chromium,jaruba/chromium.src,markYoungH/chromium.src,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,keishi/chromium,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,robclark/chromium,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,ondra-novak/chromium.src,littlstar/chromium.src,zcbenz/cefode-chromium,robclark/chromium,ChromiumWebApps/chromium,Just-D/chromium-1,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,chuan9/chromium-crosswalk,dushu1203/chromium.src,nacl-webkit/chrome_deps,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,keishi/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,dednal/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,patrickm/chromium.src,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,timopulkkinen/BubbleFish,rogerwang/chromium,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,jaruba/chromium.src,robclark/chromium,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,patrickm/chromium.src,rogerwang/chromium,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,Just-D/chromium-1,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,Just-D/chromium-1,keishi/chromium,timopulkkinen/BubbleFish,hujiajie/pa-chromium,keishi/chromium,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,rogerwang/chromium,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,robclark/chromium,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,ltilve/chromium,littlstar/chromium.src,M4sse/chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,Just-D/chromium-1,markYoungH/chromium.src,nacl-webkit/chrome_deps,Fireblend/chromium-crosswalk,Just-D/chromium-1,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,dednal/chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,keishi/chromium,dednal/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,littlstar/chromium.src,robclark/chromium,ltilve/chromium,M4sse/chromium.src,nacl-webkit/chrome_deps,dednal/chromium.src,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,patrickm/chromium.src,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,Jonekee/chromium.src,hujiajie/pa-chromium,nacl-webkit/chrome_deps,anirudhSK/chromium,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,rogerwang/chromium,fujunwei/chromium-crosswalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,littlstar/chromium.src,zcbenz/cefode-chromium,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,rogerwang/chromium,anirudhSK/chromium,M4sse/chromium.src,rogerwang/chromium,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,keishi/chromium,hujiajie/pa-chromium,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,rogerwang/chromium,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,timopulkkinen/BubbleFish,dushu1203/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,anirudhSK/chromium,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,robclark/chromium,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,ltilve/chromium,rogerwang/chromium,anirudhSK/chromium,keishi/chromium,M4sse/chromium.src,markYoungH/chromium.src,zcbenz/cefode-chromium,littlstar/chromium.src,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,jaruba/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,keishi/chromium,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,Fireblend/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,dednal/chromium.src,M4sse/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,rogerwang/chromium,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,patrickm/chromium.src,littlstar/chromium.src,keishi/chromium,keishi/chromium
|
c852f6c24d2a87ef4d4f3077c11a1656ceb7d4da
|
src/game/game.cpp
|
src/game/game.cpp
|
#include <iostream>
#include <functional>
#include "game.hpp"
GameManager::GameManager()
{
m_window = new MgCore::Window();
m_context = new MgCore::Context(3, 2, 0);
m_events = new MgCore::Events();
m_clock = new MgCore::FpsTimer();
m_running = true;
m_window->make_current(m_context);
if(ogl_LoadFunctions() == ogl_LOAD_FAILED)
{
std::cout << "Error: glLoadGen failed to load.";
}
m_lis.handler = std::bind(&GameManager::event_handler, this, std::placeholders::_1);
m_lis.mask = MgCore::EventType::Quit | MgCore::EventType::WindowSized;
m_events->add_listener(m_lis);
m_fpsTime = 0.0;
m_ss = std::cout.precision();
glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
MgCore::ShaderInfo vertInfo {GL_VERTEX_SHADER, "../data/shaders/main.vs"};
MgCore::ShaderInfo fragInfo {GL_FRAGMENT_SHADER, "../data/shaders/main.fs"};
MgCore::Shader vertShader(vertInfo);
MgCore::Shader fragShader(fragInfo);
m_program = new MgCore::ShaderProgram(&vertShader, &fragShader);
m_program->use();
m_mesh = new MgCore::Mesh2D(m_program);
glClearColor(0.5, 0.5, 0.5, 1.0);
}
GameManager::~GameManager()
{
glDeleteVertexArrays(1, &m_vao);
m_window->make_current(nullptr);
delete m_window;
delete m_context;
delete m_events;
delete m_clock;
delete m_program;
delete m_mesh;
}
void GameManager::start()
{
while (m_running)
{
m_fpsTime += m_clock->tick();
m_events->process();
update();
render();
m_window->flip();
if (m_fpsTime >= 2.0) {
std::cout.precision (5);
std::cout << "FPS: " << m_clock->get_fps() << std::endl;
std::cout.precision (m_ss);
m_fpsTime = 0;
}
}
}
bool GameManager::event_handler(MgCore::Event &event)
{
MgCore::EventType type = event.type;
switch(type) {
case MgCore::EventType::Quit:
m_running = false;
break;
case MgCore::EventType::WindowSized:
std::cout << event.event.windowSized.width << " "
<< event.event.windowSized.height << " "
<< event.event.windowSized.id << std::endl;
break;
}
return true;
}
void GameManager::update()
{
m_mesh->update();
}
void GameManager::render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_program->use();
m_mesh->render();
}
|
#include <iostream>
#include <functional>
#include "game.hpp"
GameManager::GameManager()
{
m_window = new MgCore::Window();
m_context = new MgCore::Context(3, 2, 0);
m_events = new MgCore::Events();
m_clock = new MgCore::FpsTimer();
m_running = true;
m_window->make_current(m_context);
if(ogl_LoadFunctions() == ogl_LOAD_FAILED)
{
std::cout << "Error: glLoadGen failed to load.";
}
m_lis.handler = std::bind(&GameManager::event_handler, this, std::placeholders::_1);
m_lis.mask = MgCore::EventType::Quit | MgCore::EventType::WindowSized;
m_events->add_listener(m_lis);
m_fpsTime = 0.0;
m_ss = std::cout.precision();
glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
MgCore::ShaderInfo vertInfo {GL_VERTEX_SHADER, "../data/shaders/main.vs"};
MgCore::ShaderInfo fragInfo {GL_FRAGMENT_SHADER, "../data/shaders/main.fs"};
MgCore::Shader vertShader(vertInfo);
MgCore::Shader fragShader(fragInfo);
m_program = new MgCore::ShaderProgram(&vertShader, &fragShader);
m_program->use();
m_mesh = new MgCore::Mesh2D(m_program);
glClearColor(0.5, 0.5, 0.5, 1.0);
}
GameManager::~GameManager()
{
glDeleteVertexArrays(1, &m_vao);
m_window->make_current(nullptr);
delete m_mesh;
delete m_window;
delete m_context;
delete m_events;
delete m_clock;
delete m_program;
}
void GameManager::start()
{
while (m_running)
{
m_fpsTime += m_clock->tick();
m_events->process();
update();
render();
m_window->flip();
if (m_fpsTime >= 2.0) {
std::cout.precision (5);
std::cout << "FPS: " << m_clock->get_fps() << std::endl;
std::cout.precision (m_ss);
m_fpsTime = 0;
}
}
}
bool GameManager::event_handler(MgCore::Event &event)
{
MgCore::EventType type = event.type;
switch(type) {
case MgCore::EventType::Quit:
m_running = false;
break;
case MgCore::EventType::WindowSized:
std::cout << event.event.windowSized.width << " "
<< event.event.windowSized.height << " "
<< event.event.windowSized.id << std::endl;
break;
}
return true;
}
void GameManager::update()
{
m_mesh->update();
}
void GameManager::render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_program->use();
m_mesh->render();
}
|
Fix a potential issue.
|
Fix a potential issue.
|
C++
|
unknown
|
OpenRhythm/OpenRhythm,OpenRhythm/OpenRhythm,mdsitton/musicgame,OpenRhythm/OpenRhythm,mdsitton/musicgame
|
9048a20d8b8191f9d081146700d445c09b605f4b
|
src/get_search.cc
|
src/get_search.cc
|
/**
* \file get_search.cc
*
*
*
* \author Ethan Burns
* \date 2008-11-13
*/
#include <string.h>
#include <stdlib.h>
#include <limits>
#include <vector>
#include <iostream>
// this has to come first because other includes may include the C++
// STL map.
#include "lpastar.h"
#include "astar.h"
#include "arastar.h"
#include "awastar.h"
#include "multi_a_star.h"
#include "breadth_first_search.h"
#include "cost_bound_dfs.h"
#include "ida_star.h"
#include "kbfs.h"
#include "psdd_search.h"
#include "arpbnf_search.h"
#include "opbnf_search.h"
#include "bfpsdd_search.h"
#include "wbfpsdd_search.h"
#include "idpsdd_search.h"
#include "dynamic_bounded_psdd.h"
#include "pbnf_search.h"
#include "wpbnf_search.h"
#include "pastar.h"
#include "prastar.h"
#include "wprastar.h"
#include "optimistic.h"
#include "get_search.h"
#include <limits.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#if !defined(LINE_MAX)
#define LINE_MAX 255
#endif
using namespace std;
unsigned int threads = 1;
fp_type cost_bound = fp_infinity;
unsigned int nblocks = 1;
double weight = 1.0;
/**
* Parse a weight schedule string.
*/
vector<double> *parse_weights(char *str)
{
unsigned int i, j;
bool decimal_seen = false;
char buf[LINE_MAX];
vector<double> *weights = new vector<double>();
j = 0;
for (i = 0; i < strlen(str); i += 1) {
char c = str[i];
if (isdigit(c) || (c == '.' && !decimal_seen)) {
if (c == '.')
decimal_seen = true;
assert(j < LINE_MAX); // just bomb out if we overflow :(
buf[j] = c;
j += 1;
} else if (c == ',') {
double d;
assert(j < LINE_MAX); // just bomb out if we overflow :(
buf[j] = '\0';
j = 0;
decimal_seen = false;
sscanf(buf, "%lf", &d);
weights->push_back(d);
} else {
cerr << "Invalid weight list [" << str
<< "] at char: " << i << endl;
exit(1);
}
}
if (j > 0) {
double d;
buf[j] = '\0';
j = 0;
sscanf(buf, "%lf", &d);
weights->push_back(d);
}
return weights;
}
Search *get_search(int argc, char *argv[])
{
unsigned int min_expansions = 0;
unsigned int multiplier;
double bound;
if (argc > 1 && strcmp(argv[1], "astar") == 0) {
return new AStar();
} else if (argc > 1 && sscanf(argv[1], "wastar-%lf", &weight) == 1) {
return new AStar(false);
} else if (argc > 1 && sscanf(argv[1], "optimistic-%lf", &bound) == 1) {
weight = ((bound - 1) * 2) + 1;
return new Optimistic(bound);
} else if (argc > 1 && sscanf(argv[1], "wastardd-%lf", &weight) == 1) {
return new AStar(true);
} else if (argc > 1 && sscanf(argv[1], "awastar-%lf", &weight) == 1) {
return new AwAStar();
} else if (argc > 2 && strcmp(argv[1], "arastar") == 0) {
vector<double> *weights = parse_weights(argv[2]);
weight = weights->at(0);
return new ARAStar(weights);
} else if (argc > 1 && strcmp(argv[1], "idastar") == 0) {
return new IDAStar();
} else if (argc > 1 && strcmp(argv[1], "bfs") == 0) {
return new BreadthFirstSearch();
/*
} else if (argc > 1
&& sscanf(argv[1], "costbounddfs-%lf", &cost_bound) == 1) {
return new CostBoundDFS(cost_bound);
*/
} else if (argc > 1 && sscanf(argv[1], "kbfs-%u", &threads) == 1) {
return new KBFS(threads);
} else if (argc > 1 && sscanf(argv[1], "pastar-%u", &threads) == 1) {
return new PAStar(threads);
} else if (argc > 1 && sscanf(argv[1], "lpastar-%lf-%u", &weight, &threads) == 2) {
return new LPAStar(threads);
} else if (argc > 1 && sscanf(argv[1], "prastar-%u", &threads) == 1) {
return new PRAStar(threads, false, false);
} else if (argc > 1 && sscanf(argv[1], "aprastar-%u-%u", &threads, &nblocks) == 2) {
return new PRAStar(threads, true, false);
} else if (argc > 1 && sscanf(argv[1], "hdastar-%u", &threads) == 1) {
return new PRAStar(threads, false, true);
} else if (argc > 1 && sscanf(argv[1], "ahdastar-%u-%u", &threads, &nblocks) == 2) {
return new PRAStar(threads, true, true);
} else if (argc > 1 && sscanf(argv[1], "waprastar-%lf-%u-%u", &weight, &threads, &nblocks) == 3) {
return new wPRAStar(threads, false, true);
} else if (argc > 1 && sscanf(argv[1], "waprastardd-%lf-%u-%u", &weight, &threads, &nblocks) == 3) {
return new wPRAStar(threads, true, true);
} else if (argc > 1 && sscanf(argv[1], "wprastar-%lf-%u", &weight, &threads) == 2) {
return new wPRAStar(threads, false, false);
} else if (argc > 1 && sscanf(argv[1], "wprastardd-%lf-%u", &weight, &threads) == 2) {
return new wPRAStar(threads, true, false);
} else if (argc > 1
&& sscanf(argv[1], "psdd-%u-%u", &threads, &nblocks) == 2) {
return new PSDDSearch(threads);
} else if (argc > 1
&& sscanf(argv[1], "bfpsdd-%u-%u-%u-%u", &multiplier,
&min_expansions, &threads, &nblocks) == 4) {
return new BFPSDDSearch(threads, multiplier, min_expansions);
} else if (argc > 1
&& sscanf(argv[1], "wbfpsdd-%lf-%u-%u-%u-%u", &weight,
&multiplier, &min_expansions,
&threads, &nblocks) == 5) {
return new WBFPSDDSearch(threads, multiplier, min_expansions, false);
} else if (argc > 1
&& sscanf(argv[1], "wbfpsdddd-%lf-%u-%u-%u-%u", &weight,
&multiplier, &min_expansions,
&threads, &nblocks) == 5) {
return new WBFPSDDSearch(threads, multiplier, min_expansions, true);
} else if (argc > 1
&& sscanf(argv[1], "idpsdd-%u-%u", &threads, &nblocks) == 2) {
return new IDPSDDSearch(threads);
} else if (argc > 1
&& sscanf(argv[1], "dynpsdd-%lf-%u-%u",
&weight, &threads, &nblocks) == 3) {
return new DynamicBoundedPSDD(threads, weight);
} else if (argc > 1
&& sscanf(argv[1], "pbnf-%lf-%u-%u-%u",
&weight, &min_expansions, &threads, &nblocks) == 4) {
return new PBNF::PBNFSearch(threads, min_expansions, false);
} else if (argc > 1
&& sscanf(argv[1], "safepbnf-%lf-%u-%u-%u", &weight, &min_expansions, &threads, &nblocks) == 4) {
return new PBNF::PBNFSearch(threads, min_expansions, true);
} else if (argc > 2
&& sscanf(argv[1], "arpbnf-%u-%u-%u", &min_expansions, &threads, &nblocks) == 3) {
vector<double> *weights = parse_weights(argv[2]);
weight = weights->at(0);
return new ARPBNF::ARPBNFSearch(threads, min_expansions, weights);
} else if (argc > 1
&& sscanf(argv[1], "wpbnf-%lf-%u-%u-%u", &weight, &min_expansions, &threads, &nblocks) == 4) {
return new WPBNF::WPBNFSearch(threads, min_expansions, false);
} else if (argc > 1
&& sscanf(argv[1], "wpbnfdd-%lf-%u-%u-%u", &weight, &min_expansions, &threads, &nblocks) == 4) {
return new WPBNF::WPBNFSearch(threads, min_expansions, true);
} else if (argc > 1
&& sscanf(argv[1], "opbnf-%lf-%u-%u-%u", &weight, &min_expansions, &threads, &nblocks) == 4) {
return new OPBNF::OPBNFSearch(threads, min_expansions);
} else if (argc > 1 && sscanf(argv[1], "multiastar-%u", &threads) == 1) {
return new MultiAStar(threads);
} else if (argc > 1 && sscanf(argv[1], "multiwastar-%lf-%u", &weight, &threads) == 2) {
return new MultiAStar(threads);
} else {
cout << "Must supply a search algorithm:" << endl;
cout << "\tastar" << endl
<< "\twastar-<weight>" << endl
<< "\tidastar" << endl
<< "\tbfs" << endl
<< "\tcostbounddfs-<cost>" << endl
<< "\tkbfs-<threads>" << endl
<< "\tawastar-<weight>" << endl
<< "\tarastar <weight-list>" << endl
<< "\tpastar-<threads>" << endl
<< "\tlpastar-<weight>-<threads>" << endl
<< "\tprastar-<threads>" << endl
<< "\taprastar-<threads>-<nblocks>" << endl
<< "\thdastar-<threads>" << endl
<< "\tahdastar-<threads>-<nblocks>" << endl
<< "\twaprastar-<weight>-<threads>-<nblocks>" << endl
<< "\twaprastardd-<weight>-<threads>-<nblocks>" << endl
<< "\twprastar-<weight>-<threads>" << endl
<< "\twprastardd-<weight>-<threads>" << endl
<< "\tpsdd-<threads>-<nblocks>" << endl
<< "\tdynpsdd-<weight>-<threads>-<nblocks>" << endl
<< "\tbfpsdd-<multiplier>-<min-expansions>-<threads>-<nblocks>" << endl
<< "\twbfpsdd-<weight>-<multiplier>-<min-expansions>-<threads>-<nblocks>" << endl
<< "\twbfpsdddd-<weight>-<multiplier>-<min-expansions>-<threads>-<nblocks>" << endl
<< "\tidpsdd-<threads>-<nblocks>" << endl
<< "\tpbnf-<weight>-<min_expansions>-<threads>-<nblocks>" << endl
<< "\twpbnf-<weight>-<min_expansions>-<threads>-<nblocks>" << endl
<< "\twpbnfdd-<weight>-<min_expansions>-<threads>-<nblocks>" << endl
<< "\tsafepbnf-<min-expansions>-<threads>-<nblocks>" << endl
<< "\tsafepbnf-<weight>-<min-expansions>-<threads>-<nblocks>" << endl
<< "\tarpbnf-<min-expansions>-<threads>-<nblocks> <weight-list>" << endl
<< "\topbnf-<bound>-<min-expansions>-<threads>-<nblocks>" << endl
<< "\tmultiastar-<threads>" << endl
<< "\tmultiwastar-<weight>-<threads>" << endl
<< endl;
exit(EXIT_FAILURE);
}
}
|
/**
* \file get_search.cc
*
*
*
* \author Ethan Burns
* \date 2008-11-13
*/
#include <string.h>
#include <stdlib.h>
#include <limits>
#include <vector>
#include <iostream>
// this has to come first because other includes may include the C++
// STL map.
#include "lpastar.h"
#include "astar.h"
#include "arastar.h"
#include "awastar.h"
#include "multi_a_star.h"
#include "breadth_first_search.h"
#include "cost_bound_dfs.h"
#include "ida_star.h"
#include "kbfs.h"
#include "psdd_search.h"
#include "arpbnf_search.h"
#include "opbnf_search.h"
#include "bfpsdd_search.h"
#include "wbfpsdd_search.h"
#include "idpsdd_search.h"
#include "dynamic_bounded_psdd.h"
#include "pbnf_search.h"
#include "wpbnf_search.h"
#include "pastar.h"
#include "prastar.h"
#include "wprastar.h"
#include "optimistic.h"
#include "get_search.h"
#include <limits.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#if !defined(LINE_MAX)
#define LINE_MAX 255
#endif
using namespace std;
unsigned int threads = 1;
fp_type cost_bound = fp_infinity;
unsigned int nblocks = 1;
double weight = 1.0;
/**
* Parse a weight schedule string.
*/
vector<double> *parse_weights(char *str)
{
unsigned int i, j;
bool decimal_seen = false;
char buf[LINE_MAX];
vector<double> *weights = new vector<double>();
j = 0;
for (i = 0; i < strlen(str); i += 1) {
char c = str[i];
if (isdigit(c) || (c == '.' && !decimal_seen)) {
if (c == '.')
decimal_seen = true;
assert(j < LINE_MAX); // just bomb out if we overflow :(
buf[j] = c;
j += 1;
} else if (c == ',') {
double d;
assert(j < LINE_MAX); // just bomb out if we overflow :(
buf[j] = '\0';
j = 0;
decimal_seen = false;
sscanf(buf, "%lf", &d);
weights->push_back(d);
} else {
cerr << "Invalid weight list [" << str
<< "] at char: " << i << endl;
exit(1);
}
}
if (j > 0) {
double d;
buf[j] = '\0';
j = 0;
sscanf(buf, "%lf", &d);
weights->push_back(d);
}
return weights;
}
Search *get_search(int argc, char *argv[])
{
unsigned int min_expansions = 0;
unsigned int multiplier;
double bound;
if (argc > 1 && strcmp(argv[1], "astar") == 0) {
return new AStar();
} else if (argc > 1 && sscanf(argv[1], "wastar-%lf", &weight) == 1) {
return new AStar(false);
} else if (argc > 1 && sscanf(argv[1], "optimistic-%lf", &bound) == 1) {
weight = ((bound - 1) * 2) + 1;
return new Optimistic(bound);
} else if (argc > 1 && sscanf(argv[1], "wastardd-%lf", &weight) == 1) {
return new AStar(true);
} else if (argc > 1 && sscanf(argv[1], "awastar-%lf", &weight) == 1) {
return new AwAStar();
} else if (argc > 2 && strcmp(argv[1], "arastar") == 0) {
vector<double> *weights = parse_weights(argv[2]);
weight = weights->at(0);
return new ARAStar(weights);
} else if (argc > 1 && strcmp(argv[1], "idastar") == 0) {
return new IDAStar();
} else if (argc > 1 && strcmp(argv[1], "bfs") == 0) {
return new BreadthFirstSearch();
/*
} else if (argc > 1
&& sscanf(argv[1], "costbounddfs-%lf", &cost_bound) == 1) {
return new CostBoundDFS(cost_bound);
*/
} else if (argc > 1 && sscanf(argv[1], "kbfs-%u", &threads) == 1) {
return new KBFS(threads);
} else if (argc > 1 && sscanf(argv[1], "pastar-%u", &threads) == 1) {
return new PAStar(threads);
} else if (argc > 1 && sscanf(argv[1], "lpastar-%lf-%u", &weight, &threads) == 2) {
return new LPAStar(threads);
} else if (argc > 1 && sscanf(argv[1], "prastar-%u", &threads) == 1) {
return new PRAStar(threads, false, false);
} else if (argc > 1 && sscanf(argv[1], "aprastar-%u-%u", &threads, &nblocks) == 2) {
return new PRAStar(threads, true, false);
} else if (argc > 1 && sscanf(argv[1], "hdastar-%u", &threads) == 1) {
return new PRAStar(threads, false, true);
} else if (argc > 1 && sscanf(argv[1], "ahdastar-%u-%u", &threads, &nblocks) == 2) {
return new PRAStar(threads, true, true);
} else if (argc > 1 && sscanf(argv[1], "wahdastar-%lf-%u-%u", &weight, &threads, &nblocks) == 3) {
return new wPRAStar(threads, false, true);
} else if (argc > 1 && sscanf(argv[1], "wahdastardd-%lf-%u-%u", &weight, &threads, &nblocks) == 3) {
return new wPRAStar(threads, true, true);
} else if (argc > 1 && sscanf(argv[1], "whdastar-%lf-%u", &weight, &threads) == 2) {
return new wPRAStar(threads, false, false);
} else if (argc > 1 && sscanf(argv[1], "whdastardd-%lf-%u", &weight, &threads) == 2) {
return new wPRAStar(threads, true, false);
} else if (argc > 1
&& sscanf(argv[1], "psdd-%u-%u", &threads, &nblocks) == 2) {
return new PSDDSearch(threads);
} else if (argc > 1
&& sscanf(argv[1], "bfpsdd-%u-%u-%u-%u", &multiplier,
&min_expansions, &threads, &nblocks) == 4) {
return new BFPSDDSearch(threads, multiplier, min_expansions);
} else if (argc > 1
&& sscanf(argv[1], "wbfpsdd-%lf-%u-%u-%u-%u", &weight,
&multiplier, &min_expansions,
&threads, &nblocks) == 5) {
return new WBFPSDDSearch(threads, multiplier, min_expansions, false);
} else if (argc > 1
&& sscanf(argv[1], "wbfpsdddd-%lf-%u-%u-%u-%u", &weight,
&multiplier, &min_expansions,
&threads, &nblocks) == 5) {
return new WBFPSDDSearch(threads, multiplier, min_expansions, true);
} else if (argc > 1
&& sscanf(argv[1], "idpsdd-%u-%u", &threads, &nblocks) == 2) {
return new IDPSDDSearch(threads);
} else if (argc > 1
&& sscanf(argv[1], "dynpsdd-%lf-%u-%u",
&weight, &threads, &nblocks) == 3) {
return new DynamicBoundedPSDD(threads, weight);
} else if (argc > 1
&& sscanf(argv[1], "pbnf-%lf-%u-%u-%u",
&weight, &min_expansions, &threads, &nblocks) == 4) {
return new PBNF::PBNFSearch(threads, min_expansions, false);
} else if (argc > 1
&& sscanf(argv[1], "safepbnf-%lf-%u-%u-%u", &weight, &min_expansions, &threads, &nblocks) == 4) {
return new PBNF::PBNFSearch(threads, min_expansions, true);
} else if (argc > 2
&& sscanf(argv[1], "arpbnf-%u-%u-%u", &min_expansions, &threads, &nblocks) == 3) {
vector<double> *weights = parse_weights(argv[2]);
weight = weights->at(0);
return new ARPBNF::ARPBNFSearch(threads, min_expansions, weights);
} else if (argc > 1
&& sscanf(argv[1], "wpbnf-%lf-%u-%u-%u", &weight, &min_expansions, &threads, &nblocks) == 4) {
return new WPBNF::WPBNFSearch(threads, min_expansions, false);
} else if (argc > 1
&& sscanf(argv[1], "wpbnfdd-%lf-%u-%u-%u", &weight, &min_expansions, &threads, &nblocks) == 4) {
return new WPBNF::WPBNFSearch(threads, min_expansions, true);
} else if (argc > 1
&& sscanf(argv[1], "opbnf-%lf-%u-%u-%u", &weight, &min_expansions, &threads, &nblocks) == 4) {
return new OPBNF::OPBNFSearch(threads, min_expansions);
} else if (argc > 1 && sscanf(argv[1], "multiastar-%u", &threads) == 1) {
return new MultiAStar(threads);
} else if (argc > 1 && sscanf(argv[1], "multiwastar-%lf-%u", &weight, &threads) == 2) {
return new MultiAStar(threads);
} else {
cout << "Must supply a search algorithm:" << endl;
cout << "\tastar" << endl
<< "\twastar-<weight>" << endl
<< "\tidastar" << endl
<< "\tbfs" << endl
<< "\tcostbounddfs-<cost>" << endl
<< "\tkbfs-<threads>" << endl
<< "\tawastar-<weight>" << endl
<< "\tarastar <weight-list>" << endl
<< "\tpastar-<threads>" << endl
<< "\tlpastar-<weight>-<threads>" << endl
<< "\tprastar-<threads>" << endl
<< "\taprastar-<threads>-<nblocks>" << endl
<< "\thdastar-<threads>" << endl
<< "\tahdastar-<threads>-<nblocks>" << endl
<< "\twahdastar-<weight>-<threads>-<nblocks>" << endl
<< "\twahdastardd-<weight>-<threads>-<nblocks>" << endl
<< "\twhdastar-<weight>-<threads>" << endl
<< "\twhdastardd-<weight>-<threads>" << endl
<< "\tpsdd-<threads>-<nblocks>" << endl
<< "\tdynpsdd-<weight>-<threads>-<nblocks>" << endl
<< "\tbfpsdd-<multiplier>-<min-expansions>-<threads>-<nblocks>" << endl
<< "\twbfpsdd-<weight>-<multiplier>-<min-expansions>-<threads>-<nblocks>" << endl
<< "\twbfpsdddd-<weight>-<multiplier>-<min-expansions>-<threads>-<nblocks>" << endl
<< "\tidpsdd-<threads>-<nblocks>" << endl
<< "\tpbnf-<weight>-<min_expansions>-<threads>-<nblocks>" << endl
<< "\twpbnf-<weight>-<min_expansions>-<threads>-<nblocks>" << endl
<< "\twpbnfdd-<weight>-<min_expansions>-<threads>-<nblocks>" << endl
<< "\tsafepbnf-<min-expansions>-<threads>-<nblocks>" << endl
<< "\tsafepbnf-<weight>-<min-expansions>-<threads>-<nblocks>" << endl
<< "\tarpbnf-<min-expansions>-<threads>-<nblocks> <weight-list>" << endl
<< "\topbnf-<bound>-<min-expansions>-<threads>-<nblocks>" << endl
<< "\tmultiastar-<threads>" << endl
<< "\tmultiwastar-<weight>-<threads>" << endl
<< endl;
exit(EXIT_FAILURE);
}
}
|
Change wprastar to whdastar since that is really what it is.
|
Change wprastar to whdastar since that is really what it is.
|
C++
|
mit
|
eaburns/pbnf,eaburns/pbnf,eaburns/pbnf,eaburns/pbnf
|
98126ffdf1072f691e473651e5847716fdecffd8
|
test/Emitter.cc
|
test/Emitter.cc
|
/*-
* Copyright (c) 2015 Masayoshi Mizutani <[email protected]>
* 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.
*
* 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 FOUNDATION 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 <regex>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include "./gtest.h"
#include "./FluentTest.hpp"
#include "../src/fluent/emitter.hpp"
#include "../src/debug.h"
TEST_F(FluentTest, InetEmitter) {
fluent::InetEmitter *e = new fluent::InetEmitter("localhost", 24224);
const std::string tag = "test.inet";
fluent::Message *msg = new fluent::Message(tag);
msg->set("url", "https://github.com");
msg->set("port", 443);
// msg should be deleted by Emitter after sending
e->emit(msg);
std::string res_tag, res_ts, res_rec;
EXPECT_TRUE(get_line(&res_tag, &res_ts, &res_rec));
EXPECT_EQ(res_tag, tag);
EXPECT_EQ(res_rec, "{\"port\":443,\"url\":\"https://github.com\"}");
delete e;
}
TEST_F(FluentTest, InetEmitter_QueueLimit) {
fluent::InetEmitter *e = new fluent::InetEmitter("localhost", 24224);
std::string res_tag, res_ts, res_rec;
e->set_queue_limit(1);
const std::string tag = "test.inet";
fluent::Message *msg = new fluent::Message(tag);
msg->set("num", 0);
// msg should be deleted by Emitter after sending
e->emit(msg);
ASSERT_TRUE(get_line(&res_tag, &res_ts, &res_rec));
EXPECT_EQ(res_tag, tag);
EXPECT_EQ(res_rec, "{\"num\":0}");
this->stop_fluent();
// First emit after stopping fluentd should be succeess
// because of sending message.
msg = new fluent::Message(tag);
msg->set("num", 1);
EXPECT_TRUE(e->emit(msg));
ASSERT_FALSE(get_line(&res_tag, &res_ts, &res_rec, 3));
// Second emit should be succeess because of storing message in buffer.
msg = new fluent::Message(tag);
msg->set("num", 2);
EXPECT_TRUE(e->emit(msg));
ASSERT_FALSE(get_line(&res_tag, &res_ts, &res_rec, 3));
// Third emit should be fail because buffer is full.
msg = new fluent::Message(tag);
msg->set("num", 3);
EXPECT_FALSE(e->emit(msg));
ASSERT_FALSE(get_line(&res_tag, &res_ts, &res_rec, 3));
delete e;
}
TEST(FileEmitter, basic) {
struct stat st;
const std::string fname = "fileemitter_test_output.msg";
const std::string tag = "test.file";
if (0 == ::stat(fname.c_str(), &st)) {
ASSERT_TRUE(0 == unlink(fname.c_str()));
}
fluent::FileEmitter *e = new fluent::FileEmitter(fname);
fluent::Message *msg = new fluent::Message(tag);
msgpack::sbuffer sbuf;
msgpack::packer<msgpack::sbuffer> pkr(&sbuf);
msg->set("num", 1);
msg->set_ts(100000);
msg->to_msgpack(&pkr);
EXPECT_TRUE(e->emit(msg));
delete e;
ASSERT_EQ (0, ::stat(fname.c_str(), &st));
uint8_t buf[BUFSIZ];
int fd = ::open(fname.c_str(), O_RDONLY);
ASSERT_TRUE(fd > 0);
int readsize = ::read(fd, buf, sizeof(buf));
ASSERT_TRUE(readsize > 0);
EXPECT_EQ(sbuf.size(), readsize);
EXPECT_TRUE(0 == memcmp(sbuf.data(), buf, sbuf.size()));
}
|
/*-
* Copyright (c) 2015 Masayoshi Mizutani <[email protected]>
* 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.
*
* 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 FOUNDATION 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 <regex>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include "./gtest.h"
#include "./FluentTest.hpp"
#include "../src/fluent/emitter.hpp"
#include "../src/debug.h"
TEST_F(FluentTest, InetEmitter) {
fluent::InetEmitter *e = new fluent::InetEmitter("localhost", 24224);
const std::string tag = "test.inet";
fluent::Message *msg = new fluent::Message(tag);
msg->set("url", "https://github.com");
msg->set("port", 443);
// msg should be deleted by Emitter after sending
e->emit(msg);
std::string res_tag, res_ts, res_rec;
EXPECT_TRUE(get_line(&res_tag, &res_ts, &res_rec));
EXPECT_EQ(res_tag, tag);
EXPECT_EQ(res_rec, "{\"port\":443,\"url\":\"https://github.com\"}");
delete e;
}
TEST_F(FluentTest, InetEmitter_QueueLimit) {
fluent::InetEmitter *e = new fluent::InetEmitter("localhost", 24224);
std::string res_tag, res_ts, res_rec;
e->set_queue_limit(1);
const std::string tag = "test.inet";
fluent::Message *msg = new fluent::Message(tag);
msg->set("num", 0);
// msg should be deleted by Emitter after sending
e->emit(msg);
ASSERT_TRUE(get_line(&res_tag, &res_ts, &res_rec));
EXPECT_EQ(res_tag, tag);
EXPECT_EQ(res_rec, "{\"num\":0}");
this->stop_fluent();
// First emit after stopping fluentd should be succeess
// because of sending message.
msg = new fluent::Message(tag);
msg->set("num", 1);
EXPECT_TRUE(e->emit(msg));
ASSERT_FALSE(get_line(&res_tag, &res_ts, &res_rec, 3));
// Second emit should be succeess because of storing message in buffer.
msg = new fluent::Message(tag);
msg->set("num", 2);
EXPECT_TRUE(e->emit(msg));
ASSERT_FALSE(get_line(&res_tag, &res_ts, &res_rec, 3));
// Third emit should be fail because buffer is full.
msg = new fluent::Message(tag);
msg->set("num", 3);
EXPECT_FALSE(e->emit(msg));
ASSERT_FALSE(get_line(&res_tag, &res_ts, &res_rec, 3));
delete e;
}
TEST(FileEmitter, basic) {
struct stat st;
const std::string fname = "fileemitter_test_output.msg";
const std::string tag = "test.file";
if (0 == ::stat(fname.c_str(), &st)) {
ASSERT_TRUE(0 == unlink(fname.c_str()));
}
fluent::FileEmitter *e = new fluent::FileEmitter(fname);
fluent::Message *msg = new fluent::Message(tag);
msgpack::sbuffer sbuf;
msgpack::packer<msgpack::sbuffer> pkr(&sbuf);
msg->set("num", 1);
msg->set_ts(100000);
msg->to_msgpack(&pkr);
EXPECT_TRUE(e->emit(msg));
delete e;
ASSERT_EQ (0, ::stat(fname.c_str(), &st));
uint8_t buf[BUFSIZ];
int fd = ::open(fname.c_str(), O_RDONLY);
ASSERT_TRUE(fd > 0);
int readsize = ::read(fd, buf, sizeof(buf));
ASSERT_TRUE(readsize > 0);
EXPECT_EQ(sbuf.size(), readsize);
EXPECT_TRUE(0 == memcmp(sbuf.data(), buf, sbuf.size()));
EXPECT_TRUE(0 == unlink(fname.c_str()));
}
|
remove the file created by FileEmitter test
|
remove the file created by FileEmitter test
|
C++
|
bsd-2-clause
|
m-mizutani/libfluent,m-mizutani/libfluent,m-mizutani/libfluent
|
f6a1fb6b11b83c1055c40374bf4308f21e052fdd
|
OrbitQt/main.cpp
|
OrbitQt/main.cpp
|
//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------
#include <QApplication>
#include <QFontDatabase>
#include <QStyleFactory>
#include "../OrbitGl/App.h"
#include "orbitmainwindow.h"
int main(int argc, char* argv[]) {
QApplication a(argc, argv);
a.setStyle(QStyleFactory::create("Fusion"));
QPalette darkPalette;
darkPalette.setColor(QPalette::Window, QColor(53, 53, 53));
darkPalette.setColor(QPalette::WindowText, Qt::white);
darkPalette.setColor(QPalette::Base, QColor(25, 25, 25));
darkPalette.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
darkPalette.setColor(QPalette::ToolTipBase, Qt::white);
darkPalette.setColor(QPalette::ToolTipText, Qt::white);
darkPalette.setColor(QPalette::Text, Qt::white);
darkPalette.setColor(QPalette::Button, QColor(53, 53, 53));
darkPalette.setColor(QPalette::ButtonText, Qt::white);
darkPalette.setColor(QPalette::BrightText, Qt::red);
darkPalette.setColor(QPalette::Link, QColor(42, 130, 218));
darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218));
darkPalette.setColor(QPalette::HighlightedText, Qt::black);
a.setPalette(darkPalette);
a.setStyleSheet(
"QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid "
"white; }");
OrbitMainWindow w(&a);
if (!w.IsHeadless()) {
w.showMaximized();
} else {
w.show();
w.hide();
}
w.PostInit();
int errorCode = a.exec();
OrbitApp::OnExit();
return errorCode;
}
|
//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------
#include <QApplication>
#include <QFontDatabase>
#include <QStyleFactory>
#include "../OrbitGl/App.h"
#include "orbitmainwindow.h"
int main(int argc, char* argv[]) {
#if __linux__
QCoreApplication::setAttribute(Qt::AA_DontUseNativeDialogs);
#endif
QApplication a(argc, argv);
a.setStyle(QStyleFactory::create("Fusion"));
QPalette darkPalette;
darkPalette.setColor(QPalette::Window, QColor(53, 53, 53));
darkPalette.setColor(QPalette::WindowText, Qt::white);
darkPalette.setColor(QPalette::Base, QColor(25, 25, 25));
darkPalette.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
darkPalette.setColor(QPalette::ToolTipBase, Qt::white);
darkPalette.setColor(QPalette::ToolTipText, Qt::white);
darkPalette.setColor(QPalette::Text, Qt::white);
darkPalette.setColor(QPalette::Button, QColor(53, 53, 53));
darkPalette.setColor(QPalette::ButtonText, Qt::white);
darkPalette.setColor(QPalette::BrightText, Qt::red);
darkPalette.setColor(QPalette::Link, QColor(42, 130, 218));
darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218));
darkPalette.setColor(QPalette::HighlightedText, Qt::black);
a.setPalette(darkPalette);
a.setStyleSheet(
"QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid "
"white; }");
OrbitMainWindow w(&a);
if (!w.IsHeadless()) {
w.showMaximized();
} else {
w.show();
w.hide();
}
w.PostInit();
int errorCode = a.exec();
OrbitApp::OnExit();
return errorCode;
}
|
Fix crash when opening dialog on Linux (b/150301022).
|
Fix crash when opening dialog on Linux (b/150301022).
|
C++
|
bsd-2-clause
|
google/orbit,pierricgimmig/orbitprofiler,google/orbit,google/orbit,google/orbit,pierricgimmig/orbitprofiler,pierricgimmig/orbitprofiler,pierricgimmig/orbitprofiler
|
e7f5da903228d32de47a9c6021e4d59cda0101ef
|
avatar.cpp
|
avatar.cpp
|
/******************************************************************************
* Copyright (C) 2017 Kitsune Ral <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "avatar.h"
#include "jobs/mediathumbnailjob.h"
#include "events/eventcontent.h"
#include "connection.h"
#include <QtGui/QPainter>
#include <QtCore/QPointer>
using namespace QMatrixClient;
class Avatar::Private
{
public:
explicit Private(QIcon di, QUrl url = {})
: _defaultIcon(di), _url(url)
{ }
QImage get(Connection* connection, QSize size,
get_callback_t callback) const;
bool upload(UploadContentJob* job, upload_callback_t callback);
const QIcon _defaultIcon;
QUrl _url;
// The below are related to image caching, hence mutable
mutable QImage _originalImage;
mutable std::vector<QPair<QSize, QImage>> _scaledImages;
mutable QSize _requestedSize;
mutable bool _valid = false;
mutable QPointer<MediaThumbnailJob> _thumbnailRequest = nullptr;
mutable QPointer<BaseJob> _uploadRequest = nullptr;
mutable std::vector<get_callback_t> callbacks;
mutable get_callback_t uploadCallback;
};
Avatar::Avatar(QIcon defaultIcon)
: d(std::make_unique<Private>(std::move(defaultIcon)))
{ }
Avatar::Avatar(QUrl url, QIcon defaultIcon)
: d(std::make_unique<Private>(std::move(defaultIcon), std::move(url)))
{ }
Avatar::Avatar(Avatar&&) = default;
Avatar::~Avatar() = default;
Avatar& Avatar::operator=(Avatar&&) = default;
QImage Avatar::get(Connection* connection, int dimension,
get_callback_t callback) const
{
return d->get(connection, {dimension, dimension}, callback);
}
QImage Avatar::get(Connection* connection, int width, int height,
get_callback_t callback) const
{
return d->get(connection, {width, height}, callback);
}
bool Avatar::upload(Connection* connection, const QString& fileName,
upload_callback_t callback) const
{
if (isJobRunning(d->_uploadRequest))
return false;
return d->upload(connection->uploadFile(fileName), callback);
}
bool Avatar::upload(Connection* connection, QIODevice* source,
upload_callback_t callback) const
{
if (isJobRunning(d->_uploadRequest) || !source->isReadable())
return false;
return d->upload(connection->uploadContent(source), callback);
}
QString Avatar::mediaId() const
{
return d->_url.authority() + d->_url.path();
}
QImage Avatar::Private::get(Connection* connection, QSize size,
get_callback_t callback) const
{
// FIXME: Alternating between longer-width and longer-height requests
// is a sure way to trick the below code into constantly getting another
// image from the server because the existing one is alleged unsatisfactory.
// This is plain abuse by the client, though; so not critical for now.
if( ( !(_valid || _thumbnailRequest)
|| size.width() > _requestedSize.width()
|| size.height() > _requestedSize.height() ) && _url.isValid() )
{
qCDebug(MAIN) << "Getting avatar from" << _url.toString();
_requestedSize = size;
if (isJobRunning(_thumbnailRequest))
_thumbnailRequest->abandon();
callbacks.emplace_back(std::move(callback));
_thumbnailRequest = connection->getThumbnail(_url, size);
QObject::connect( _thumbnailRequest, &MediaThumbnailJob::success, [this]
{
_valid = true;
_originalImage = _thumbnailRequest->scaledThumbnail(_requestedSize);
_scaledImages.clear();
for (auto n: callbacks)
n();
});
}
if( _originalImage.isNull() )
{
if (_defaultIcon.isNull())
return _originalImage;
QPainter p { &_originalImage };
_defaultIcon.paint(&p, { QPoint(), _defaultIcon.actualSize(size) });
}
for (auto p: _scaledImages)
if (p.first == size)
return p.second;
auto result = _originalImage.scaled(size,
Qt::KeepAspectRatio, Qt::SmoothTransformation);
_scaledImages.emplace_back(size, result);
return result;
}
bool Avatar::Private::upload(UploadContentJob* job, upload_callback_t callback)
{
_uploadRequest = job;
if (!isJobRunning(_uploadRequest))
return false;
_uploadRequest->connect(_uploadRequest, &BaseJob::success,
[job,callback] { callback(job->contentUri()); });
return true;
}
QUrl Avatar::url() const { return d->_url; }
bool Avatar::updateUrl(const QUrl& newUrl)
{
if (newUrl == d->_url)
return false;
// FIXME: Make it a library-wide constant and maybe even make the URL checker
// a Connection(?) method.
if (newUrl.scheme() != "mxc" || newUrl.path().count('/') != 1)
{
qCWarning(MAIN) << "Malformed avatar URL:" << newUrl.toDisplayString();
return false;
}
d->_url = newUrl;
d->_valid = false;
if (isJobRunning(d->_thumbnailRequest))
d->_thumbnailRequest->abandon();
return true;
}
|
/******************************************************************************
* Copyright (C) 2017 Kitsune Ral <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "avatar.h"
#include "jobs/mediathumbnailjob.h"
#include "events/eventcontent.h"
#include "connection.h"
#include <QtGui/QPainter>
#include <QtCore/QPointer>
using namespace QMatrixClient;
class Avatar::Private
{
public:
explicit Private(QIcon di, QUrl url = {})
: _defaultIcon(di), _url(url)
{ }
QImage get(Connection* connection, QSize size,
get_callback_t callback) const;
bool upload(UploadContentJob* job, upload_callback_t callback);
bool checkUrl(QUrl url) const;
const QIcon _defaultIcon;
QUrl _url;
// The below are related to image caching, hence mutable
mutable QImage _originalImage;
mutable std::vector<QPair<QSize, QImage>> _scaledImages;
mutable QSize _requestedSize;
mutable bool _bannedUrl = false;
mutable bool _fetched = false;
mutable QPointer<MediaThumbnailJob> _thumbnailRequest = nullptr;
mutable QPointer<BaseJob> _uploadRequest = nullptr;
mutable std::vector<get_callback_t> callbacks;
mutable get_callback_t uploadCallback;
};
Avatar::Avatar(QIcon defaultIcon)
: d(std::make_unique<Private>(std::move(defaultIcon)))
{ }
Avatar::Avatar(QUrl url, QIcon defaultIcon)
: d(std::make_unique<Private>(std::move(defaultIcon), std::move(url)))
{ }
Avatar::Avatar(Avatar&&) = default;
Avatar::~Avatar() = default;
Avatar& Avatar::operator=(Avatar&&) = default;
QImage Avatar::get(Connection* connection, int dimension,
get_callback_t callback) const
{
return d->get(connection, {dimension, dimension}, callback);
}
QImage Avatar::get(Connection* connection, int width, int height,
get_callback_t callback) const
{
return d->get(connection, {width, height}, callback);
}
bool Avatar::upload(Connection* connection, const QString& fileName,
upload_callback_t callback) const
{
if (isJobRunning(d->_uploadRequest))
return false;
return d->upload(connection->uploadFile(fileName), callback);
}
bool Avatar::upload(Connection* connection, QIODevice* source,
upload_callback_t callback) const
{
if (isJobRunning(d->_uploadRequest) || !source->isReadable())
return false;
return d->upload(connection->uploadContent(source), callback);
}
QString Avatar::mediaId() const
{
return d->_url.authority() + d->_url.path();
}
QImage Avatar::Private::get(Connection* connection, QSize size,
get_callback_t callback) const
{
// FIXME: Alternating between longer-width and longer-height requests
// is a sure way to trick the below code into constantly getting another
// image from the server because the existing one is alleged unsatisfactory.
// This is plain abuse by the client, though; so not critical for now.
if( ( !(_fetched || _thumbnailRequest)
|| size.width() > _requestedSize.width()
|| size.height() > _requestedSize.height() ) && checkUrl(_url) )
{
qCDebug(MAIN) << "Getting avatar from" << _url.toString();
_requestedSize = size;
if (isJobRunning(_thumbnailRequest))
_thumbnailRequest->abandon();
callbacks.emplace_back(std::move(callback));
_thumbnailRequest = connection->getThumbnail(_url, size);
QObject::connect( _thumbnailRequest, &MediaThumbnailJob::success, [this]
{
_fetched = true;
_originalImage = _thumbnailRequest->scaledThumbnail(_requestedSize);
_scaledImages.clear();
for (auto n: callbacks)
n();
});
}
if( _originalImage.isNull() )
{
if (_defaultIcon.isNull())
return _originalImage;
QPainter p { &_originalImage };
_defaultIcon.paint(&p, { QPoint(), _defaultIcon.actualSize(size) });
}
for (auto p: _scaledImages)
if (p.first == size)
return p.second;
auto result = _originalImage.scaled(size,
Qt::KeepAspectRatio, Qt::SmoothTransformation);
_scaledImages.emplace_back(size, result);
return result;
}
bool Avatar::Private::upload(UploadContentJob* job, upload_callback_t callback)
{
_uploadRequest = job;
if (!isJobRunning(_uploadRequest))
return false;
_uploadRequest->connect(_uploadRequest, &BaseJob::success,
[job,callback] { callback(job->contentUri()); });
return true;
}
bool Avatar::Private::checkUrl(QUrl url) const
{
if (_bannedUrl || url.isEmpty())
return false;
// FIXME: Make "mxc" a library-wide constant and maybe even make
// the URL checker a Connection(?) method.
_bannedUrl = !(url.isValid() &&
url.scheme() == "mxc" && url.path().count('/') == 1);
if (_bannedUrl)
qCWarning(MAIN) << "Avatar URL is invalid or not mxc-based:"
<< url.toDisplayString();
return !_bannedUrl;
}
QUrl Avatar::url() const { return d->_url; }
bool Avatar::updateUrl(const QUrl& newUrl)
{
if (newUrl == d->_url)
return false;
d->_url = newUrl;
d->_fetched = false;
if (isJobRunning(d->_thumbnailRequest))
d->_thumbnailRequest->abandon();
return true;
}
|
check URLs before fetching, not on updating the URL
|
Avatar: check URLs before fetching, not on updating the URL
Closes #187.
|
C++
|
lgpl-2.1
|
Fxrh/libqmatrixclient,QMatrixClient/libqmatrixclient,QMatrixClient/libqmatrixclient
|
0c29147f087a2a25b0c2c6512913c6c81a1e2989
|
aeron-common/src/test/cpp/concurrent/TermReaderTest.cpp
|
aeron-common/src/test/cpp/concurrent/TermReaderTest.cpp
|
/*
* Copyright 2014 - 2015 Real Logic Ltd.
*
* 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 <array>
#include <gtest/gtest.h>
#include <thread>
#include "MockAtomicBuffer.h"
#include <concurrent/logbuffer/TermReader.h>
using namespace aeron::common::concurrent::logbuffer;
using namespace aeron::common::concurrent::mock;
using namespace aeron::common::concurrent;
using namespace aeron::common;
#define TERM_BUFFER_CAPACITY (LogBufferDescriptor::TERM_MIN_LENGTH)
#define META_DATA_BUFFER_CAPACITY (LogBufferDescriptor::TERM_META_DATA_LENGTH)
#define HDR_LENGTH (DataHeader::LENGTH)
#define TERM_BUFFER_UNALIGNED_CAPACITY (LogBufferDescriptor::TERM_MIN_LENGTH + FrameDescriptor::FRAME_ALIGNMENT - 1)
#define INITIAL_TERM_ID 7
typedef std::array<std::uint8_t, TERM_BUFFER_CAPACITY> log_buffer_t;
typedef std::array<std::uint8_t, META_DATA_BUFFER_CAPACITY> state_buffer_t;
typedef std::array<std::uint8_t, HDR_LENGTH> hdr_t;
typedef std::array<std::uint8_t, TERM_BUFFER_UNALIGNED_CAPACITY> log_buffer_unaligned_t;
class TermReaderTest : public testing::Test
{
public:
TermReaderTest() :
m_log(&m_logBuffer[0], m_logBuffer.size()),
m_logReader(INITIAL_TERM_ID, m_log)
{
m_logBuffer.fill(0);
}
virtual void SetUp()
{
m_logBuffer.fill(0);
}
protected:
AERON_DECL_ALIGNED(log_buffer_t m_logBuffer, 16);
MockAtomicBuffer m_log;
TermReader m_logReader;
};
class MockDataHandler
{
public:
MOCK_CONST_METHOD4(onData, void(AtomicBuffer&, util::index_t, util::index_t, Header&));
};
TEST_F(TermReaderTest, shouldThrowExceptionWhenCapacityNotMultipleOfAlignment)
{
AERON_DECL_ALIGNED(log_buffer_unaligned_t logBuffer, 16);
MockAtomicBuffer mockLog(&logBuffer[0], logBuffer.size());
ASSERT_THROW(
{
TermReader logReader(INITIAL_TERM_ID, mockLog);
}, util::IllegalStateException);
}
TEST_F(TermReaderTest, shouldReadFirstMessage)
{
MockDataHandler handler;
const util::index_t msgLength = 1;
const util::index_t frameLength = DataHeader::LENGTH + msgLength;
const util::index_t alignedFrameLength = util::BitUtil::align(frameLength, FrameDescriptor::FRAME_ALIGNMENT);
const std::int32_t termOffset = 0;
testing::Sequence sequence;
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(0)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(frameLength));
EXPECT_CALL(m_log, getUInt16(FrameDescriptor::typeOffset(0)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0x01));
EXPECT_CALL(handler, onData(testing::Ref(m_log), DataHeader::LENGTH, msgLength, testing::_))
.Times(1)
.InSequence(sequence);
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(alignedFrameLength)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0));
const int framesRead = m_logReader.read(
termOffset, [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header)
{
handler.onData(buffer, offset, length, header);
}, INT_MAX);
EXPECT_EQ(framesRead, 1);
}
TEST_F(TermReaderTest, shouldNotReadWhenLimitIsZero)
{
MockDataHandler handler;
const util::index_t msgLength = 1;
const util::index_t frameLength = DataHeader::LENGTH + msgLength;
const std::int32_t termOffset = 0;
testing::Sequence sequence;
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(0)))
.Times(1)
.WillOnce(testing::Return(frameLength));
EXPECT_CALL(handler, onData(testing::Ref(m_log), DataHeader::LENGTH, msgLength, testing::_))
.Times(0);
const int framesRead = m_logReader.read(
termOffset, [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header)
{
handler.onData(buffer, offset, length, header);
}, 0);
EXPECT_EQ(framesRead, 0);
}
TEST_F(TermReaderTest, shouldNotReadPastTail)
{
MockDataHandler handler;
const util::index_t msgLength = 1;
const std::int32_t termOffset = 0;
testing::Sequence sequence;
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(0)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0));
EXPECT_CALL(m_log, getUInt16(FrameDescriptor::typeOffset(0)))
.Times(0);
EXPECT_CALL(handler, onData(testing::Ref(m_log), DataHeader::LENGTH, msgLength, testing::_))
.Times(0);
const int framesRead = m_logReader.read(
termOffset, [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header)
{
handler.onData(buffer, offset, length, header);
}, INT_MAX);
EXPECT_EQ(framesRead, 0);
}
TEST_F(TermReaderTest, shouldReadOneLimitedMessage)
{
MockDataHandler handler;
const util::index_t msgLength = 1;
const util::index_t frameLength = DataHeader::LENGTH + msgLength;
const std::int32_t termOffset = 0;
testing::Sequence sequence;
EXPECT_CALL(m_log, getInt32Volatile(testing::_))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(frameLength));
EXPECT_CALL(m_log, getUInt16(testing::_))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0x01));
EXPECT_CALL(handler, onData(testing::Ref(m_log), DataHeader::LENGTH, msgLength, testing::_))
.Times(1)
.InSequence(sequence);
const int framesRead = m_logReader.read(
termOffset, [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header)
{
handler.onData(buffer, offset, length, header);
}, 1);
EXPECT_EQ(framesRead, 1);
}
TEST_F(TermReaderTest, shouldReadMultipleMessages)
{
MockDataHandler handler;
const util::index_t msgLength = 1;
const util::index_t frameLength = DataHeader::LENGTH + msgLength;
const util::index_t alignedFrameLength = util::BitUtil::align(frameLength, FrameDescriptor::FRAME_ALIGNMENT);
const std::int32_t termOffset = 0;
testing::Sequence sequence;
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(0)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(frameLength));
EXPECT_CALL(m_log, getUInt16(FrameDescriptor::typeOffset(0)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0x01));
EXPECT_CALL(handler, onData(testing::Ref(m_log), DataHeader::LENGTH, msgLength, testing::_))
.Times(1)
.InSequence(sequence);
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(alignedFrameLength)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(frameLength));
EXPECT_CALL(m_log, getUInt16(FrameDescriptor::typeOffset(alignedFrameLength)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0x01));
EXPECT_CALL(handler, onData(testing::Ref(m_log), alignedFrameLength + DataHeader::LENGTH, msgLength, testing::_))
.Times(1)
.InSequence(sequence);
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(alignedFrameLength * 2)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0));
const int framesRead = m_logReader.read(
termOffset, [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header)
{
handler.onData(buffer, offset, length, header);
}, INT_MAX);
EXPECT_EQ(framesRead, 2);
}
TEST_F(TermReaderTest, shouldReadLastMessage)
{
MockDataHandler handler;
const util::index_t msgLength = 1;
const util::index_t frameLength = DataHeader::LENGTH + msgLength;
const util::index_t alignedFrameLength = util::BitUtil::align(frameLength, FrameDescriptor::FRAME_ALIGNMENT);
const std::int32_t startOfMessage = TERM_BUFFER_CAPACITY - alignedFrameLength;
testing::Sequence sequence;
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(startOfMessage)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(frameLength));
EXPECT_CALL(m_log, getUInt16(FrameDescriptor::typeOffset(startOfMessage)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0x01));
EXPECT_CALL(handler, onData(testing::Ref(m_log), startOfMessage + DataHeader::LENGTH, msgLength, testing::_))
.Times(1)
.InSequence(sequence);
const int framesRead = m_logReader.read(
startOfMessage, [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header)
{
handler.onData(buffer, offset, length, header);
}, INT_MAX);
EXPECT_EQ(framesRead, 1);
}
TEST_F(TermReaderTest, shouldNotReadLastMessageWhenPadding)
{
MockDataHandler handler;
const util::index_t msgLength = 1;
const util::index_t frameLength = DataHeader::LENGTH + msgLength;
const util::index_t alignedFrameLength = util::BitUtil::align(frameLength, FrameDescriptor::FRAME_ALIGNMENT);
const util::index_t startOfMessage = TERM_BUFFER_CAPACITY - alignedFrameLength;
testing::Sequence sequence;
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(startOfMessage)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(frameLength));
EXPECT_CALL(m_log, getUInt16(FrameDescriptor::typeOffset(startOfMessage)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(FrameDescriptor::PADDING_FRAME_TYPE));
EXPECT_CALL(handler, onData(testing::Ref(m_log), startOfMessage + DataHeader::LENGTH, msgLength, testing::_))
.Times(0);
const int framesRead = m_logReader.read(
startOfMessage, [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header)
{
handler.onData(buffer, offset, length, header);
}, INT_MAX);
EXPECT_EQ(framesRead, 0);
}
|
/*
* Copyright 2014 - 2015 Real Logic Ltd.
*
* 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 <array>
#include <gtest/gtest.h>
#include <thread>
#include "MockAtomicBuffer.h"
#include <concurrent/logbuffer/TermReader.h>
using namespace aeron::common::concurrent::logbuffer;
using namespace aeron::common::concurrent::mock;
using namespace aeron::common::concurrent;
using namespace aeron::common;
#define TERM_BUFFER_CAPACITY (LogBufferDescriptor::TERM_MIN_LENGTH)
#define META_DATA_BUFFER_CAPACITY (LogBufferDescriptor::TERM_META_DATA_LENGTH)
#define HDR_LENGTH (DataHeader::LENGTH)
#define TERM_BUFFER_UNALIGNED_CAPACITY (LogBufferDescriptor::TERM_MIN_LENGTH + FrameDescriptor::FRAME_ALIGNMENT - 1)
#define INITIAL_TERM_ID 7
typedef std::array<std::uint8_t, TERM_BUFFER_CAPACITY> log_buffer_t;
typedef std::array<std::uint8_t, META_DATA_BUFFER_CAPACITY> state_buffer_t;
typedef std::array<std::uint8_t, HDR_LENGTH> hdr_t;
typedef std::array<std::uint8_t, TERM_BUFFER_UNALIGNED_CAPACITY> log_buffer_unaligned_t;
class TermReaderTest : public testing::Test
{
public:
TermReaderTest() :
m_log(&m_logBuffer[0], m_logBuffer.size()),
m_logReader(INITIAL_TERM_ID, m_log)
{
m_logBuffer.fill(0);
}
virtual void SetUp()
{
m_logBuffer.fill(0);
}
protected:
AERON_DECL_ALIGNED(log_buffer_t m_logBuffer, 16);
MockAtomicBuffer m_log;
TermReader m_logReader;
};
class MockDataHandler
{
public:
MOCK_CONST_METHOD4(onData, void(AtomicBuffer&, util::index_t, util::index_t, Header&));
};
TEST_F(TermReaderTest, shouldThrowExceptionWhenCapacityNotMultipleOfAlignment)
{
AERON_DECL_ALIGNED(log_buffer_unaligned_t logBuffer, 16);
MockAtomicBuffer mockLog(&logBuffer[0], logBuffer.size());
ASSERT_THROW(
{
TermReader logReader(INITIAL_TERM_ID, mockLog);
}, util::IllegalStateException);
}
TEST_F(TermReaderTest, shouldReadFirstMessage)
{
MockDataHandler handler;
const util::index_t msgLength = 1;
const util::index_t frameLength = DataHeader::LENGTH + msgLength;
const util::index_t alignedFrameLength = util::BitUtil::align(frameLength, FrameDescriptor::FRAME_ALIGNMENT);
const std::int32_t termOffset = 0;
testing::Sequence sequence;
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(0)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(frameLength));
EXPECT_CALL(m_log, getUInt16(FrameDescriptor::typeOffset(0)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0x01));
EXPECT_CALL(handler, onData(testing::Ref(m_log), DataHeader::LENGTH, msgLength, testing::_))
.Times(1)
.InSequence(sequence);
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(alignedFrameLength)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0));
const int framesRead = m_logReader.read(
termOffset, [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header)
{
handler.onData(buffer, offset, length, header);
}, INT_MAX);
EXPECT_EQ(framesRead, 1);
}
TEST_F(TermReaderTest, shouldNotReadPastTail)
{
MockDataHandler handler;
const util::index_t msgLength = 1;
const std::int32_t termOffset = 0;
testing::Sequence sequence;
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(0)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0));
EXPECT_CALL(m_log, getUInt16(FrameDescriptor::typeOffset(0)))
.Times(0);
EXPECT_CALL(handler, onData(testing::Ref(m_log), DataHeader::LENGTH, msgLength, testing::_))
.Times(0);
const int framesRead = m_logReader.read(
termOffset, [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header)
{
handler.onData(buffer, offset, length, header);
}, INT_MAX);
EXPECT_EQ(framesRead, 0);
}
TEST_F(TermReaderTest, shouldReadOneLimitedMessage)
{
MockDataHandler handler;
const util::index_t msgLength = 1;
const util::index_t frameLength = DataHeader::LENGTH + msgLength;
const std::int32_t termOffset = 0;
testing::Sequence sequence;
EXPECT_CALL(m_log, getInt32Volatile(testing::_))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(frameLength));
EXPECT_CALL(m_log, getUInt16(testing::_))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0x01));
EXPECT_CALL(handler, onData(testing::Ref(m_log), DataHeader::LENGTH, msgLength, testing::_))
.Times(1)
.InSequence(sequence);
const int framesRead = m_logReader.read(
termOffset, [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header)
{
handler.onData(buffer, offset, length, header);
}, 1);
EXPECT_EQ(framesRead, 1);
}
TEST_F(TermReaderTest, shouldReadMultipleMessages)
{
MockDataHandler handler;
const util::index_t msgLength = 1;
const util::index_t frameLength = DataHeader::LENGTH + msgLength;
const util::index_t alignedFrameLength = util::BitUtil::align(frameLength, FrameDescriptor::FRAME_ALIGNMENT);
const std::int32_t termOffset = 0;
testing::Sequence sequence;
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(0)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(frameLength));
EXPECT_CALL(m_log, getUInt16(FrameDescriptor::typeOffset(0)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0x01));
EXPECT_CALL(handler, onData(testing::Ref(m_log), DataHeader::LENGTH, msgLength, testing::_))
.Times(1)
.InSequence(sequence);
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(alignedFrameLength)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(frameLength));
EXPECT_CALL(m_log, getUInt16(FrameDescriptor::typeOffset(alignedFrameLength)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0x01));
EXPECT_CALL(handler, onData(testing::Ref(m_log), alignedFrameLength + DataHeader::LENGTH, msgLength, testing::_))
.Times(1)
.InSequence(sequence);
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(alignedFrameLength * 2)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0));
const int framesRead = m_logReader.read(
termOffset, [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header)
{
handler.onData(buffer, offset, length, header);
}, INT_MAX);
EXPECT_EQ(framesRead, 2);
}
TEST_F(TermReaderTest, shouldReadLastMessage)
{
MockDataHandler handler;
const util::index_t msgLength = 1;
const util::index_t frameLength = DataHeader::LENGTH + msgLength;
const util::index_t alignedFrameLength = util::BitUtil::align(frameLength, FrameDescriptor::FRAME_ALIGNMENT);
const std::int32_t startOfMessage = TERM_BUFFER_CAPACITY - alignedFrameLength;
testing::Sequence sequence;
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(startOfMessage)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(frameLength));
EXPECT_CALL(m_log, getUInt16(FrameDescriptor::typeOffset(startOfMessage)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(0x01));
EXPECT_CALL(handler, onData(testing::Ref(m_log), startOfMessage + DataHeader::LENGTH, msgLength, testing::_))
.Times(1)
.InSequence(sequence);
const int framesRead = m_logReader.read(
startOfMessage, [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header)
{
handler.onData(buffer, offset, length, header);
}, INT_MAX);
EXPECT_EQ(framesRead, 1);
}
TEST_F(TermReaderTest, shouldNotReadLastMessageWhenPadding)
{
MockDataHandler handler;
const util::index_t msgLength = 1;
const util::index_t frameLength = DataHeader::LENGTH + msgLength;
const util::index_t alignedFrameLength = util::BitUtil::align(frameLength, FrameDescriptor::FRAME_ALIGNMENT);
const util::index_t startOfMessage = TERM_BUFFER_CAPACITY - alignedFrameLength;
testing::Sequence sequence;
EXPECT_CALL(m_log, getInt32Volatile(FrameDescriptor::lengthOffset(startOfMessage)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(frameLength));
EXPECT_CALL(m_log, getUInt16(FrameDescriptor::typeOffset(startOfMessage)))
.Times(1)
.InSequence(sequence)
.WillOnce(testing::Return(FrameDescriptor::PADDING_FRAME_TYPE));
EXPECT_CALL(handler, onData(testing::Ref(m_log), startOfMessage + DataHeader::LENGTH, msgLength, testing::_))
.Times(0);
const int framesRead = m_logReader.read(
startOfMessage, [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header)
{
handler.onData(buffer, offset, length, header);
}, INT_MAX);
EXPECT_EQ(framesRead, 0);
}
|
remove unnecessary test
|
[C++]: remove unnecessary test
|
C++
|
apache-2.0
|
EvilMcJerkface/Aeron,mikeb01/Aeron,oleksiyp/Aeron,oleksiyp/Aeron,buybackoff/Aeron,real-logic/Aeron,galderz/Aeron,rlankenau/Aeron,jerrinot/Aeron,gkamal/Aeron,mikeb01/Aeron,lennartj/Aeron,tbrooks8/Aeron,UIKit0/Aeron,UIKit0/Aeron,RussellWilby/Aeron,buybackoff/Aeron,strangelydim/Aeron,jerrinot/Aeron,mikeb01/Aeron,UIKit0/Aeron,strangelydim/Aeron,galderz/Aeron,lennartj/Aeron,EvilMcJerkface/Aeron,lennartj/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,real-logic/Aeron,tbrooks8/Aeron,gkamal/Aeron,rlankenau/Aeron,gkamal/Aeron,oleksiyp/Aeron,real-logic/Aeron,strangelydim/Aeron,mikeb01/Aeron,rlankenau/Aeron,galderz/Aeron,RussellWilby/Aeron,jerrinot/Aeron,RussellWilby/Aeron,EvilMcJerkface/Aeron,tbrooks8/Aeron,galderz/Aeron,buybackoff/Aeron
|
2cc54aa3856855bfd95d641b544167ee7a7dab4a
|
src/Band/band.hpp
|
src/Band/band.hpp
|
// Copyright (c) 2013-2017 Anton Kozhevnikov, Thomas Schulthess
// 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.
//
// 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.
/** \file band.hpp
*
* \brief Contains declaration and partial implementation of sirius::Band class.
*/
#ifndef __BAND_HPP__
#define __BAND_HPP__
#include "periodic_function.hpp"
#include "K_point/k_point_set.hpp"
#include "Hamiltonian/hamiltonian.hpp"
namespace sirius {
/// Setup and solve the eigen value problem.
class Band // TODO: Band class is lightweight and in principle can be converted to a namespace
{
private:
/// Simulation context.
Simulation_context& ctx_;
/// Alias for the unit cell.
Unit_cell& unit_cell_;
/// BLACS grid for distributed linear algebra operations.
BLACS_grid const& blacs_grid_;
inline void solve_full_potential(K_point& kp__, Hamiltonian& hamiltonian__) const;
/// Solve the first-variational (non-magnetic) problem with exact diagonalization.
/** This is only used by the LAPW method. */
inline void diag_full_potential_first_variation_exact(K_point& kp__, Hamiltonian& hamiltonian__) const;
/// Solve the first-variational (non-magnetic) problem with iterative Davidson diagonalization.
inline void diag_full_potential_first_variation_davidson(K_point& kp__, Hamiltonian& hamiltonian__) const;
/// Solve second-variational problem.
inline void diag_full_potential_second_variation(K_point& kp, Hamiltonian& hamiltonian__) const;
/// Get singular components of the LAPW overlap matrix.
/** Singular components are the eigen-vectors with a very small eigen-value. */
inline void get_singular_components(K_point& kp__, Hamiltonian& H__) const;
template <typename T>
inline int solve_pseudo_potential(K_point& kp__, Hamiltonian& hamiltonian__) const;
/// Diagonalize a pseudo-potential Hamiltonian.
template <typename T>
int diag_pseudo_potential(K_point* kp__, Hamiltonian& H__) const;
/// Exact (not iterative) diagonalization of the Hamiltonian.
template <typename T>
inline void diag_pseudo_potential_exact(K_point* kp__, int ispn__, Hamiltonian& H__) const;
/// Iterative Davidson diagonalization.
template <typename T>
inline int diag_pseudo_potential_davidson(K_point* kp__, Hamiltonian& H__) const;
template <typename T>
inline std::vector<double> diag_S_davidson(K_point& kp__, Hamiltonian& H__) const;
/// RMM-DIIS diagonalization.
template <typename T>
inline void diag_pseudo_potential_rmm_diis(K_point* kp__, int ispn__, Hamiltonian& H__) const;
template <typename T>
inline void
diag_pseudo_potential_chebyshev(K_point* kp__, int ispn__, Hamiltonian& H__, P_operator<T>& p_op__) const;
/// Auxiliary function used internally by residuals() function.
inline mdarray<double, 1> residuals_aux(K_point* kp__,
int ispn__,
int num_bands__,
std::vector<double>& eval__,
Wave_functions& hpsi__,
Wave_functions& opsi__,
Wave_functions& res__,
mdarray<double, 2>& h_diag__,
mdarray<double, 1>& o_diag__) const;
/// Compute preconditioned residuals
template <typename T>
inline int residuals(K_point* kp__,
int ispn__,
int N__,
int num_bands__,
std::vector<double>& eval__,
std::vector<double>& eval_old__,
dmatrix<T>& evec__,
Wave_functions& hphi__,
Wave_functions& ophi__,
Wave_functions& hpsi__,
Wave_functions& opsi__,
Wave_functions& res__,
mdarray<double, 2>& h_diag__,
mdarray<double, 1>& o_diag__,
double eval_tolerance__,
double norm_tolerance__) const; //TODO: more documentation here
template <typename T>
void check_residuals(K_point& kp__, Hamiltonian& H__) const;
/// Check wave-functions for orthonormalization.
template <typename T>
void check_wave_functions(K_point& kp__, Hamiltonian& H__) const
{
if (kp__.comm().rank() == 0) {
printf("checking wave-functions\n");
}
if (!ctx_.full_potential()) {
dmatrix<T> ovlp(ctx_.num_bands(), ctx_.num_bands(), ctx_.blacs_grid(), ctx_.cyclic_block_size(), ctx_.cyclic_block_size());
const bool nc_mag = (ctx_.num_mag_dims() == 3);
const int num_sc = nc_mag ? 2 : 1;
auto& psi = kp__.spinor_wave_functions();
Wave_functions spsi(kp__.gkvec_partition(), ctx_.num_bands(), ctx_.preferred_memory_t(), num_sc);
if (is_device_memory(ctx_.preferred_memory_t())) {
auto& mpd = ctx_.mem_pool(memory_t::device);
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
psi.pw_coeffs(ispn).allocate(mpd);
psi.pw_coeffs(ispn).copy_to(memory_t::device, 0, ctx_.num_bands());
}
for (int i = 0; i < num_sc; i++) {
spsi.pw_coeffs(i).allocate(mpd);
}
ovlp.allocate(memory_t::device);
}
kp__.beta_projectors().prepare();
/* compute residuals */
for (int ispin_step = 0; ispin_step < ctx_.num_spin_dims(); ispin_step++) {
/* apply Hamiltonian and S operators to the wave-functions */
H__.apply_h_s<T>(&kp__, nc_mag ? 2 : ispin_step, 0, ctx_.num_bands(), psi, nullptr, &spsi);
inner(ctx_.preferred_memory_t(), ctx_.blas_linalg_t(), nc_mag ? 2 : ispin_step, psi, 0, ctx_.num_bands(),
spsi, 0, ctx_.num_bands(), ovlp, 0, 0);
double diff = check_identity(ovlp, ctx_.num_bands());
if (kp__.comm().rank() == 0) {
if (diff > 1e-12) {
printf("overlap matrix is not identity, maximum error : %20.12f\n", diff);
} else {
printf("OK! Wave functions are orthonormal.\n");
}
}
}
if (is_device_memory(ctx_.preferred_memory_t())) {
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
psi.pw_coeffs(ispn).deallocate(memory_t::device);
}
}
kp__.beta_projectors().dismiss();
}
}
/** Compute \f$ O_{ii'} = \langle \phi_i | \hat O | \phi_{i'} \rangle \f$ operator matrix
* for the subspace spanned by the wave-functions \f$ \phi_i \f$. The matrix is always returned
* in the CPU pointer because most of the standard math libraries start from the CPU. */
template <typename T>
inline void set_subspace_mtrx(int N__,
int n__,
Wave_functions& phi__,
Wave_functions& op_phi__,
dmatrix<T>& mtrx__,
dmatrix<T>* mtrx_old__ = nullptr) const;
public:
/// Constructor
Band(Simulation_context& ctx__)
: ctx_(ctx__)
, unit_cell_(ctx__.unit_cell())
, blacs_grid_(ctx__.blacs_grid())
{
if (!ctx_.initialized()) {
TERMINATE("Simulation_context is not initialized");
}
}
/// Solve \f$ \hat H \psi = E \psi \f$ and find eigen-states of the Hamiltonian.
inline void solve(K_point_set& kset__, Hamiltonian& hamiltonian__, bool precompute__) const;
/// Initialize the subspace for the entire k-point set.
inline void initialize_subspace(K_point_set& kset__, Hamiltonian& hamiltonian__) const;
/// Initialize the wave-functions subspace.
template <typename T>
inline void initialize_subspace(K_point* kp__, Hamiltonian& hamiltonian__, int num_ao__) const;
static double& evp_work_count() // TODO: move counters to sim.ctx
{
static double evp_work_count_{0};
return evp_work_count_;
}
};
#include "residuals.hpp"
#include "diag_full_potential.hpp"
#include "diag_pseudo_potential.hpp"
#include "initialize_subspace.hpp"
#include "solve.hpp"
#include "set_subspace_mtrx.hpp"
}
#endif // __BAND_HPP__
|
// Copyright (c) 2013-2017 Anton Kozhevnikov, Thomas Schulthess
// 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.
//
// 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.
/** \file band.hpp
*
* \brief Contains declaration and partial implementation of sirius::Band class.
*/
#ifndef __BAND_HPP__
#define __BAND_HPP__
#include "periodic_function.hpp"
#include "K_point/k_point_set.hpp"
#include "Hamiltonian/hamiltonian.hpp"
namespace sirius {
/// Setup and solve the eigen value problem.
class Band // TODO: Band class is lightweight and in principle can be converted to a namespace
{
private:
/// Simulation context.
Simulation_context& ctx_;
/// Alias for the unit cell.
Unit_cell& unit_cell_;
/// BLACS grid for distributed linear algebra operations.
BLACS_grid const& blacs_grid_;
inline void solve_full_potential(K_point& kp__, Hamiltonian& hamiltonian__) const;
/// Solve the first-variational (non-magnetic) problem with exact diagonalization.
/** This is only used by the LAPW method. */
inline void diag_full_potential_first_variation_exact(K_point& kp__, Hamiltonian& hamiltonian__) const;
/// Solve the first-variational (non-magnetic) problem with iterative Davidson diagonalization.
inline void diag_full_potential_first_variation_davidson(K_point& kp__, Hamiltonian& hamiltonian__) const;
/// Solve second-variational problem.
inline void diag_full_potential_second_variation(K_point& kp, Hamiltonian& hamiltonian__) const;
/// Get singular components of the LAPW overlap matrix.
/** Singular components are the eigen-vectors with a very small eigen-value. */
inline void get_singular_components(K_point& kp__, Hamiltonian& H__) const;
template <typename T>
inline int solve_pseudo_potential(K_point& kp__, Hamiltonian& hamiltonian__) const;
/// Diagonalize a pseudo-potential Hamiltonian.
template <typename T>
int diag_pseudo_potential(K_point* kp__, Hamiltonian& H__) const;
/// Exact (not iterative) diagonalization of the Hamiltonian.
template <typename T>
inline void diag_pseudo_potential_exact(K_point* kp__, int ispn__, Hamiltonian& H__) const;
/// Iterative Davidson diagonalization.
template <typename T>
inline int diag_pseudo_potential_davidson(K_point* kp__, Hamiltonian& H__) const;
template <typename T>
inline std::vector<double> diag_S_davidson(K_point& kp__, Hamiltonian& H__) const;
/// RMM-DIIS diagonalization.
template <typename T>
inline void diag_pseudo_potential_rmm_diis(K_point* kp__, int ispn__, Hamiltonian& H__) const;
//template <typename T>
//inline void
//diag_pseudo_potential_chebyshev(K_point* kp__, int ispn__, Hamiltonian& H__, P_operator<T>& p_op__) const;
/// Auxiliary function used internally by residuals() function.
inline mdarray<double, 1> residuals_aux(K_point* kp__,
int ispn__,
int num_bands__,
std::vector<double>& eval__,
Wave_functions& hpsi__,
Wave_functions& opsi__,
Wave_functions& res__,
mdarray<double, 2>& h_diag__,
mdarray<double, 1>& o_diag__) const;
/// Compute preconditioned residuals
template <typename T>
inline int residuals(K_point* kp__,
int ispn__,
int N__,
int num_bands__,
std::vector<double>& eval__,
std::vector<double>& eval_old__,
dmatrix<T>& evec__,
Wave_functions& hphi__,
Wave_functions& ophi__,
Wave_functions& hpsi__,
Wave_functions& opsi__,
Wave_functions& res__,
mdarray<double, 2>& h_diag__,
mdarray<double, 1>& o_diag__,
double eval_tolerance__,
double norm_tolerance__) const; //TODO: more documentation here
template <typename T>
void check_residuals(K_point& kp__, Hamiltonian& H__) const;
/// Check wave-functions for orthonormalization.
template <typename T>
void check_wave_functions(K_point& kp__, Hamiltonian& H__) const
{
if (kp__.comm().rank() == 0) {
printf("checking wave-functions\n");
}
if (!ctx_.full_potential()) {
dmatrix<T> ovlp(ctx_.num_bands(), ctx_.num_bands(), ctx_.blacs_grid(), ctx_.cyclic_block_size(), ctx_.cyclic_block_size());
const bool nc_mag = (ctx_.num_mag_dims() == 3);
const int num_sc = nc_mag ? 2 : 1;
auto& psi = kp__.spinor_wave_functions();
Wave_functions spsi(kp__.gkvec_partition(), ctx_.num_bands(), ctx_.preferred_memory_t(), num_sc);
if (is_device_memory(ctx_.preferred_memory_t())) {
auto& mpd = ctx_.mem_pool(memory_t::device);
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
psi.pw_coeffs(ispn).allocate(mpd);
psi.pw_coeffs(ispn).copy_to(memory_t::device, 0, ctx_.num_bands());
}
for (int i = 0; i < num_sc; i++) {
spsi.pw_coeffs(i).allocate(mpd);
}
ovlp.allocate(memory_t::device);
}
kp__.beta_projectors().prepare();
/* compute residuals */
for (int ispin_step = 0; ispin_step < ctx_.num_spin_dims(); ispin_step++) {
/* apply Hamiltonian and S operators to the wave-functions */
H__.apply_h_s<T>(&kp__, nc_mag ? 2 : ispin_step, 0, ctx_.num_bands(), psi, nullptr, &spsi);
inner(ctx_.preferred_memory_t(), ctx_.blas_linalg_t(), nc_mag ? 2 : ispin_step, psi, 0, ctx_.num_bands(),
spsi, 0, ctx_.num_bands(), ovlp, 0, 0);
double diff = check_identity(ovlp, ctx_.num_bands());
if (kp__.comm().rank() == 0) {
if (diff > 1e-12) {
printf("overlap matrix is not identity, maximum error : %20.12f\n", diff);
} else {
printf("OK! Wave functions are orthonormal.\n");
}
}
}
if (is_device_memory(ctx_.preferred_memory_t())) {
for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) {
psi.pw_coeffs(ispn).deallocate(memory_t::device);
}
}
kp__.beta_projectors().dismiss();
}
}
/** Compute \f$ O_{ii'} = \langle \phi_i | \hat O | \phi_{i'} \rangle \f$ operator matrix
* for the subspace spanned by the wave-functions \f$ \phi_i \f$. The matrix is always returned
* in the CPU pointer because most of the standard math libraries start from the CPU. */
template <typename T>
inline void set_subspace_mtrx(int N__,
int n__,
Wave_functions& phi__,
Wave_functions& op_phi__,
dmatrix<T>& mtrx__,
dmatrix<T>* mtrx_old__ = nullptr) const;
public:
/// Constructor
Band(Simulation_context& ctx__)
: ctx_(ctx__)
, unit_cell_(ctx__.unit_cell())
, blacs_grid_(ctx__.blacs_grid())
{
if (!ctx_.initialized()) {
TERMINATE("Simulation_context is not initialized");
}
}
/// Solve \f$ \hat H \psi = E \psi \f$ and find eigen-states of the Hamiltonian.
inline void solve(K_point_set& kset__, Hamiltonian& hamiltonian__, bool precompute__) const;
/// Initialize the subspace for the entire k-point set.
inline void initialize_subspace(K_point_set& kset__, Hamiltonian& hamiltonian__) const;
/// Initialize the wave-functions subspace.
template <typename T>
inline void initialize_subspace(K_point* kp__, Hamiltonian& hamiltonian__, int num_ao__) const;
static double& evp_work_count() // TODO: move counters to sim.ctx
{
static double evp_work_count_{0};
return evp_work_count_;
}
};
#include "residuals.hpp"
#include "diag_full_potential.hpp"
#include "diag_pseudo_potential.hpp"
#include "initialize_subspace.hpp"
#include "solve.hpp"
#include "set_subspace_mtrx.hpp"
}
#endif // __BAND_HPP__
|
comment old code
|
comment old code
|
C++
|
bsd-2-clause
|
toxa81/sirius,electronic-structure/sirius,toxa81/sirius,electronic-structure/sirius,toxa81/sirius,electronic-structure/sirius,electronic-structure/sirius,toxa81/sirius,electronic-structure/sirius,toxa81/sirius,electronic-structure/sirius,electronic-structure/sirius,toxa81/sirius
|
10e611ec519350020646575978f3b1c703be111e
|
Queens_Class.cpp
|
Queens_Class.cpp
|
//EJ Eppinger
//06.06.16
//Program to teach me how to use C++
using namespace std;
int main(){
//intializes Queens class
class Queens{
//public methods
public:
int n = 30;
int valids = 0;
bool board[n][n];
//Constructor
Queens(int n){
for(int col = 0; col < n; col++){
for(int row = 0; row < n; row++){
board[col][row] = false;
}
}
}
//N getter method
static int getN(){ return n;}
//unfinished board printer method
/*void printBoard(){
cout << "Board: " << isValid() << endl;
for(int col = 0; col < n; ++col){
for(int row = 0; row < n; ++row){
if(board[row][col])
}
}
}
*/
//placePiece method
void placePiece(int col, int row){
board[col][row] = !board[col][row];
}
//testing diagonals in the up-right direction
bool right(int row, int col){
int count = 0;
for(int i = 0; i < n; ++i){
if( row- i < 0 || col + i > n + 1){
return true;
}
else if(board[row - 1][col + 1]) {
++count;
if(count > 1){
return false;
}
}
}
return true;
}
//testing diagonals in the up-left direction
bool left(int row, int col){
int count = 0;
for(int i = 0; i < n; ++i){
if (row - i < 0 || col - i < 0){
return true;
}
if(board[row - i][col - i]){
++count;
if(count > 1){
return false;
}
}
}
return true;
}
//tests a board's validity
bool isValid(){
++valids;
for(int row = 0; row < n; ++row){
int count = 0;
for (int col = 0; col < n; ++col){
if(board[row][col]){
++count;
if(count > 1){
return false;
}
}
}
}
for(int row = 0; row < n; ++row){
int count = 0;
for (int col = 0; col < n; ++col){
if(board[col][row]){
++count;
if(count > 1){
return false;
}
}
}
}
for(int i = 0; i < n; ++i){
if(!(right(n - 1, i) && right(i, 0) && left(n - 1, i) && left(i, n - 1))){
return false;
}
}
return true;
}
};
}
|
//EJ Eppinger
//06.06.16
//Program to teach me how to use C++
using namespace std;
int main(){
//intializes Queens class
class Queens{
//public methods
public:
int n;
int valids = 0;
//Constructor
Queens(int n){
this.n = n;
board = bool[n][n]
for(int col = 0; col < n; col++){
for(int row = 0; row < n; row++){
board[col][row] = false;
}
}
}
//N getter method
static int getN(){ return n;}
//unfinished board printer method
/*void printBoard(){
cout << "Board: " << isValid() << endl;
for(int col = 0; col < n; ++col){
for(int row = 0; row < n; ++row){
if(board[row][col])
}
}
}
*/
//placePiece method
void placePiece(int col, int row){
board[col][row] = !board[col][row];
}
//testing diagonals in the up-right direction
bool right(int row, int col){
int count = 0;
for(int i = 0; i < n; ++i){
if( row- i < 0 || col + i > n + 1){
return true;
}
else if(board[row - 1][col + 1]) {
++count;
if(count > 1){
return false;
}
}
}
return true;
}
//testing diagonals in the up-left direction
bool left(int row, int col){
int count = 0;
for(int i = 0; i < n; ++i){
if (row - i < 0 || col - i < 0){
return true;
}
if(board[row - i][col - i]){
++count;
if(count > 1){
return false;
}
}
}
return true;
}
//tests a board's validity
bool isValid(){
++valids;
for(int row = 0; row < n; ++row){
int count = 0;
for (int col = 0; col < n; ++col){
if(board[row][col]){
++count;
if(count > 1){
return false;
}
}
}
}
for(int row = 0; row < n; ++row){
int count = 0;
for (int col = 0; col < n; ++col){
if(board[col][row]){
++count;
if(count > 1){
return false;
}
}
}
}
for(int i = 0; i < n; ++i){
if(!(right(n - 1, i) && right(i, 0) && left(n - 1, i) && left(i, n - 1))){
return false;
}
}
return true;
}
};
}
|
Update Some Stuff
|
Update Some Stuff
|
C++
|
mit
|
eppingere/Learning-Cplusplus,eppingere/Learning-Cplusplus
|
0e9e63931517d96765b84917df94b2a1f999bb07
|
src/CSVLoader.cpp
|
src/CSVLoader.cpp
|
#include "CSVLoader.h"
#include <cassert>
#include <iostream>
#include <fstream>
#include <glm/glm.hpp>
#include "PointCloud.h"
#include "../system/StringUtils.h"
using namespace std;
using namespace table;
CSVLoader::CSVLoader() : FileTypeHandler("Comma separated values", false) {
addExtension("csv");
}
std::shared_ptr<Graph>
CSVLoader::openGraph(const char * filename) {
auto graph = std::make_shared<PointCloud>();
ifstream in(filename, ios::in);
if (!in) {
cerr << "Cannot open " << filename << endl;
return 0;
}
char delimiter = '\t';
vector<string> header;
cerr << "reading CSV\n";
try {
while (!in.eof() && !in.fail()) {
string s;
getline(in, s);
StringUtils::trim(s);
if (s.empty()) continue;
vector<string> row = StringUtils::split(s, delimiter);
assert(!row.empty());
if (header.empty()) {
header = row;
for (vector<string>::const_iterator it = header.begin(); it != header.end(); it++) {
string n = StringUtils::toLower(*it);
if (n == "likes" || n == "count") {
graph->getNodeData().addIntColumn(it->c_str());
} else if (n != "x" && n != "y" && n != "z" && n != "lat" && n != "lon" &&
n != "long" && n != "lng" && n != "latitude" && n != "longitude") {
graph->getNodeData().addTextColumn(it->c_str());
}
}
} else {
int node_id = graph->getNodeArray().addNode();
double x = 0, y = 0;
for (unsigned int i = 0; i < row.size(); i++) {
if (row[i].empty()) continue;
if (header[i] == "X") {
x = stof(row[i]);
} else if (header[i] == "Y") {
y = stof(row[i]);
} else {
graph->getNodeData()[header[i]].setValue(node_id, row[i]);
}
}
graph->getNodeArray().setPosition(node_id, glm::vec3(x, y, 0));
}
}
} catch (exception & e) {
cerr << "exception: " << e.what() << endl;
assert(0);
}
cerr << "reading CSV done\n";
return graph;
}
|
#include "CSVLoader.h"
#include <cassert>
#include <iostream>
#include <fstream>
#include <glm/glm.hpp>
#include "PointCloud.h"
#include "../system/StringUtils.h"
using namespace std;
using namespace table;
CSVLoader::CSVLoader() : FileTypeHandler("Comma separated values", false) {
addExtension("csv");
}
std::shared_ptr<Graph>
CSVLoader::openGraph(const char * filename) {
auto graph = std::make_shared<PointCloud>();
graph->setNodeArray(std::make_shared<NodeArray>());
ifstream in(filename, ios::in);
if (!in) {
cerr << "Cannot open " << filename << endl;
return 0;
}
char delimiter = '\t';
vector<string> header;
cerr << "reading CSV\n";
try {
while (!in.eof() && !in.fail()) {
string s;
getline(in, s);
StringUtils::trim(s);
if (s.empty()) continue;
vector<string> row = StringUtils::split(s, delimiter);
assert(!row.empty());
if (header.empty()) {
header = row;
for (vector<string>::const_iterator it = header.begin(); it != header.end(); it++) {
string n = StringUtils::toLower(*it);
if (n == "likes" || n == "count") {
graph->getNodeData().addIntColumn(it->c_str());
} else if (n != "x" && n != "y" && n != "z" && n != "lat" && n != "lon" &&
n != "long" && n != "lng" && n != "latitude" && n != "longitude") {
graph->getNodeData().addTextColumn(it->c_str());
}
}
} else {
int node_id = graph->getNodeArray().addNode();
double x = 0, y = 0;
for (unsigned int i = 0; i < row.size(); i++) {
if (row[i].empty()) continue;
if (header[i] == "X") {
x = stof(row[i]);
} else if (header[i] == "Y") {
y = stof(row[i]);
} else {
graph->getNodeData()[header[i]].setValue(node_id, row[i]);
}
}
graph->getNodeArray().setPosition(node_id, glm::vec3(x, y, 0));
}
}
} catch (exception & e) {
cerr << "exception: " << e.what() << endl;
assert(0);
}
cerr << "reading CSV done\n";
return graph;
}
|
create NodeArray for PointCloud
|
create NodeArray for PointCloud
|
C++
|
mit
|
Sometrik/graphlib,Sometrik/graphlib
|
94d59ff15212209b2d646e0b0735e7b11d9a650b
|
test_flights.cc
|
test_flights.cc
|
// Copyright 2016 Arizona Board of Regents. See README.md and LICENSE for more.
#include <iostream>
#include <algorithm>
#include <iterator>
#include <ctime>
#include <boost/random.hpp>
#include <boost/generator_iterator.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/algorithm/string.hpp>
#include "nanocube.h"
#include "nanocube_traversals.h"
#include "debug.h"
int atoi(const std::string &s) { return atoi(s.c_str()); }
double atof(const std::string &s) { return atof(s.c_str()); }
static const unsigned short MortonTable256[256] =
{
0x0000, 0x0001, 0x0004, 0x0005, 0x0010, 0x0011, 0x0014, 0x0015,
0x0040, 0x0041, 0x0044, 0x0045, 0x0050, 0x0051, 0x0054, 0x0055,
0x0100, 0x0101, 0x0104, 0x0105, 0x0110, 0x0111, 0x0114, 0x0115,
0x0140, 0x0141, 0x0144, 0x0145, 0x0150, 0x0151, 0x0154, 0x0155,
0x0400, 0x0401, 0x0404, 0x0405, 0x0410, 0x0411, 0x0414, 0x0415,
0x0440, 0x0441, 0x0444, 0x0445, 0x0450, 0x0451, 0x0454, 0x0455,
0x0500, 0x0501, 0x0504, 0x0505, 0x0510, 0x0511, 0x0514, 0x0515,
0x0540, 0x0541, 0x0544, 0x0545, 0x0550, 0x0551, 0x0554, 0x0555,
0x1000, 0x1001, 0x1004, 0x1005, 0x1010, 0x1011, 0x1014, 0x1015,
0x1040, 0x1041, 0x1044, 0x1045, 0x1050, 0x1051, 0x1054, 0x1055,
0x1100, 0x1101, 0x1104, 0x1105, 0x1110, 0x1111, 0x1114, 0x1115,
0x1140, 0x1141, 0x1144, 0x1145, 0x1150, 0x1151, 0x1154, 0x1155,
0x1400, 0x1401, 0x1404, 0x1405, 0x1410, 0x1411, 0x1414, 0x1415,
0x1440, 0x1441, 0x1444, 0x1445, 0x1450, 0x1451, 0x1454, 0x1455,
0x1500, 0x1501, 0x1504, 0x1505, 0x1510, 0x1511, 0x1514, 0x1515,
0x1540, 0x1541, 0x1544, 0x1545, 0x1550, 0x1551, 0x1554, 0x1555,
0x4000, 0x4001, 0x4004, 0x4005, 0x4010, 0x4011, 0x4014, 0x4015,
0x4040, 0x4041, 0x4044, 0x4045, 0x4050, 0x4051, 0x4054, 0x4055,
0x4100, 0x4101, 0x4104, 0x4105, 0x4110, 0x4111, 0x4114, 0x4115,
0x4140, 0x4141, 0x4144, 0x4145, 0x4150, 0x4151, 0x4154, 0x4155,
0x4400, 0x4401, 0x4404, 0x4405, 0x4410, 0x4411, 0x4414, 0x4415,
0x4440, 0x4441, 0x4444, 0x4445, 0x4450, 0x4451, 0x4454, 0x4455,
0x4500, 0x4501, 0x4504, 0x4505, 0x4510, 0x4511, 0x4514, 0x4515,
0x4540, 0x4541, 0x4544, 0x4545, 0x4550, 0x4551, 0x4554, 0x4555,
0x5000, 0x5001, 0x5004, 0x5005, 0x5010, 0x5011, 0x5014, 0x5015,
0x5040, 0x5041, 0x5044, 0x5045, 0x5050, 0x5051, 0x5054, 0x5055,
0x5100, 0x5101, 0x5104, 0x5105, 0x5110, 0x5111, 0x5114, 0x5115,
0x5140, 0x5141, 0x5144, 0x5145, 0x5150, 0x5151, 0x5154, 0x5155,
0x5400, 0x5401, 0x5404, 0x5405, 0x5410, 0x5411, 0x5414, 0x5415,
0x5440, 0x5441, 0x5444, 0x5445, 0x5450, 0x5451, 0x5454, 0x5455,
0x5500, 0x5501, 0x5504, 0x5505, 0x5510, 0x5511, 0x5514, 0x5515,
0x5540, 0x5541, 0x5544, 0x5545, 0x5550, 0x5551, 0x5554, 0x5555
};
float uniform_variate()
{
typedef boost::mt19937 RNGType;
static RNGType rng;
static boost::uniform_01<> d;
static boost::variate_generator< RNGType, boost::uniform_01<> > gen(rng, d);
return gen();
}
vector<int> random_point(const vector<int> &schema)
{
vector<int> result;
for (int i=0; i<schema.size(); ++i) {
float u = uniform_variate();
int r = (1 << schema.at(i));
int ui = std::max(0, std::min(r - 1, int(u * r)));
result.push_back(ui);
}
return result;
}
vector<pair<int, int> > random_region(const vector<int> &schema)
{
vector<int> p1 = random_point(schema), p2 = random_point(schema);
vector<pair<int, int> > result;
for (int i=0; i<p1.size(); ++i) {
result.push_back(make_pair(min(p1[i], p2[i]+1), max(p1[i], p2[i]+1)));
}
return result;
}
// convert lat,lon to quad tree address
int loc2addr(double lat, double lon, int qtreeLevel)
{
double xd = (lon + M_PI) / (2.0 * M_PI);
double yd = (log(tan(M_PI / 4.0 + lat / 2.0)) + M_PI) / (2.0 * M_PI);
//cout << lat << " " << lon << " " << endl;
unsigned short x = xd * (1 << qtreeLevel), y = yd * (1 << qtreeLevel);
// turn (x,y) into an address of the quadtree
// Interleave bits
// TODO use int64_t
int z = MortonTable256[y >> 8] << 17 |
MortonTable256[x >> 8] << 16 |
MortonTable256[y & 0xFF] << 1 |
MortonTable256[x & 0xFF];
return z;
}
void test(Nanocube<int> &nc, vector<pair<int,int> > &dataarray, vector<int> &schema)
{
/**************************************************/
// Test
/**************************************************/
int n_regions = 10;
for (int l=0; l<n_regions; ++l) {
vector<pair<int, int> > region = random_region(schema);
//vector<pair<int, int> > region;
//region.push_back({500,3200});
//region.push_back({300,19000});
int rq = ortho_range_query(nc, region);
int count = 0;
for(int dlength = 0; dlength < dataarray.size(); dlength++) {
if( (dataarray[dlength].first > region[0].first &&
dataarray[dlength].first < region[0].second) &&
(dataarray[dlength].second > region[1].first &&
dataarray[dlength].second < region[1].second) ) {
count ++;
}
}
cout << "Query from Nanocubea: "<< rq << " | Linear scan: " << count << endl;
}
}
int main(int argc, char **argv)
{
using namespace boost::gregorian;
using namespace boost::posix_time;
ifstream is(argv[1]);
std::cout << "Data file: " << argv[1] << std::endl;
string s;
int qtreeLevel = 15;
vector<int> schema = {qtreeLevel*2, qtreeLevel*2};
// use a quadtree
Nanocube<int> nc(schema);
vector<pair<int,int> > dataarray;
int i = 0;
clock_t begin = clock();
while (std::getline(is, s)) {
vector<string> output;
boost::split(output,s,boost::is_any_of("\t"));
if (output.size() != 4) {
cerr << "Bad line:" << s << endl;
continue;
}
double ori_lat = atof(output[0]) * M_PI / 180.0;
double ori_lon = atof(output[1]) * M_PI / 180.0;
double des_lat = atof(output[2]) * M_PI / 180.0;
double des_lon = atof(output[3]) * M_PI / 180.0;
if (ori_lat > 85.0511 || ori_lat < -85.0511 ||
des_lat > 85.0511 || des_lat < -85.0511 ){
cerr << "Invalid latitude: " << ori_lat << ", " << des_lat;
cerr << " (should be in [-85.0511, 85.0511])" << endl;
continue;
}
int d1 = loc2addr(ori_lat, ori_lon, qtreeLevel);
int d2 = loc2addr(des_lat, des_lon, qtreeLevel);
nc.insert(1, {d1, d2});
dataarray.push_back({d1,d2});
if (++i % 10000 == 0) {
//nc.report_size();
cout << i << endl;
}
}
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "Running time: " << elapsed_secs << endl;
test(nc, dataarray, schema);
}
|
// Copyright 2016 Arizona Board of Regents. See README.md and LICENSE for more.
#include <iostream>
#include <algorithm>
#include <iterator>
#include <ctime>
#include <boost/random.hpp>
#include <boost/generator_iterator.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/algorithm/string.hpp>
#include "nanocube.h"
#include "nanocube_traversals.h"
#include "debug.h"
int atoi(const std::string &s) { return atoi(s.c_str()); }
double atof(const std::string &s) { return atof(s.c_str()); }
static const unsigned short MortonTable256[256] =
{
0x0000, 0x0001, 0x0004, 0x0005, 0x0010, 0x0011, 0x0014, 0x0015,
0x0040, 0x0041, 0x0044, 0x0045, 0x0050, 0x0051, 0x0054, 0x0055,
0x0100, 0x0101, 0x0104, 0x0105, 0x0110, 0x0111, 0x0114, 0x0115,
0x0140, 0x0141, 0x0144, 0x0145, 0x0150, 0x0151, 0x0154, 0x0155,
0x0400, 0x0401, 0x0404, 0x0405, 0x0410, 0x0411, 0x0414, 0x0415,
0x0440, 0x0441, 0x0444, 0x0445, 0x0450, 0x0451, 0x0454, 0x0455,
0x0500, 0x0501, 0x0504, 0x0505, 0x0510, 0x0511, 0x0514, 0x0515,
0x0540, 0x0541, 0x0544, 0x0545, 0x0550, 0x0551, 0x0554, 0x0555,
0x1000, 0x1001, 0x1004, 0x1005, 0x1010, 0x1011, 0x1014, 0x1015,
0x1040, 0x1041, 0x1044, 0x1045, 0x1050, 0x1051, 0x1054, 0x1055,
0x1100, 0x1101, 0x1104, 0x1105, 0x1110, 0x1111, 0x1114, 0x1115,
0x1140, 0x1141, 0x1144, 0x1145, 0x1150, 0x1151, 0x1154, 0x1155,
0x1400, 0x1401, 0x1404, 0x1405, 0x1410, 0x1411, 0x1414, 0x1415,
0x1440, 0x1441, 0x1444, 0x1445, 0x1450, 0x1451, 0x1454, 0x1455,
0x1500, 0x1501, 0x1504, 0x1505, 0x1510, 0x1511, 0x1514, 0x1515,
0x1540, 0x1541, 0x1544, 0x1545, 0x1550, 0x1551, 0x1554, 0x1555,
0x4000, 0x4001, 0x4004, 0x4005, 0x4010, 0x4011, 0x4014, 0x4015,
0x4040, 0x4041, 0x4044, 0x4045, 0x4050, 0x4051, 0x4054, 0x4055,
0x4100, 0x4101, 0x4104, 0x4105, 0x4110, 0x4111, 0x4114, 0x4115,
0x4140, 0x4141, 0x4144, 0x4145, 0x4150, 0x4151, 0x4154, 0x4155,
0x4400, 0x4401, 0x4404, 0x4405, 0x4410, 0x4411, 0x4414, 0x4415,
0x4440, 0x4441, 0x4444, 0x4445, 0x4450, 0x4451, 0x4454, 0x4455,
0x4500, 0x4501, 0x4504, 0x4505, 0x4510, 0x4511, 0x4514, 0x4515,
0x4540, 0x4541, 0x4544, 0x4545, 0x4550, 0x4551, 0x4554, 0x4555,
0x5000, 0x5001, 0x5004, 0x5005, 0x5010, 0x5011, 0x5014, 0x5015,
0x5040, 0x5041, 0x5044, 0x5045, 0x5050, 0x5051, 0x5054, 0x5055,
0x5100, 0x5101, 0x5104, 0x5105, 0x5110, 0x5111, 0x5114, 0x5115,
0x5140, 0x5141, 0x5144, 0x5145, 0x5150, 0x5151, 0x5154, 0x5155,
0x5400, 0x5401, 0x5404, 0x5405, 0x5410, 0x5411, 0x5414, 0x5415,
0x5440, 0x5441, 0x5444, 0x5445, 0x5450, 0x5451, 0x5454, 0x5455,
0x5500, 0x5501, 0x5504, 0x5505, 0x5510, 0x5511, 0x5514, 0x5515,
0x5540, 0x5541, 0x5544, 0x5545, 0x5550, 0x5551, 0x5554, 0x5555
};
float uniform_variate()
{
typedef boost::mt19937 RNGType;
static RNGType rng;
static boost::uniform_01<> d;
static boost::variate_generator< RNGType, boost::uniform_01<> > gen(rng, d);
return gen();
}
vector<int> random_point(const vector<int> &schema)
{
vector<int> result;
for (int i=0; i<schema.size(); ++i) {
float u = uniform_variate();
int r = (1 << schema.at(i));
int ui = std::max(0, std::min(r - 1, int(u * r)));
result.push_back(ui);
}
return result;
}
vector<pair<int, int> > random_region(const vector<int> &schema)
{
vector<int> p1 = random_point(schema), p2 = random_point(schema);
vector<pair<int, int> > result;
for (int i=0; i<p1.size(); ++i) {
result.push_back(make_pair(min(p1[i], p2[i]+1), max(p1[i], p2[i]+1)));
}
return result;
}
// convert lat,lon to quad tree address
int loc2addr(double lat, double lon, int qtreeLevel)
{
double xd = (lon + M_PI) / (2.0 * M_PI);
double yd = (log(tan(M_PI / 4.0 + lat / 2.0)) + M_PI) / (2.0 * M_PI);
//cout << lat << " " << lon << " " << endl;
unsigned short x = xd * (1 << qtreeLevel), y = yd * (1 << qtreeLevel);
// turn (x,y) into an address of the quadtree
// Interleave bits
// TODO use int64_t
int z = MortonTable256[y >> 8] << 17 |
MortonTable256[x >> 8] << 16 |
MortonTable256[y & 0xFF] << 1 |
MortonTable256[x & 0xFF];
return z;
}
void test(Nanocube<int> &nc, vector<pair<int,int> > &dataarray, vector<int> &schema)
{
/**************************************************/
// Test
/**************************************************/
int n_regions = 10;
for (int l=0; l<n_regions; ++l) {
vector<pair<int, int> > region = random_region(schema);
//vector<pair<int, int> > region;
//region.push_back({500,3200});
//region.push_back({300,19000});
int rq = ortho_range_query(nc, region);
int count = 0;
for(int dlength = 0; dlength < dataarray.size(); dlength++) {
if( (dataarray[dlength].first > region[0].first &&
dataarray[dlength].first < region[0].second) &&
(dataarray[dlength].second > region[1].first &&
dataarray[dlength].second < region[1].second) ) {
count ++;
}
}
cout << "Query from Nanocubea: "<< rq << " | Linear scan: " << count << endl;
}
}
int main(int argc, char **argv)
{
using namespace boost::gregorian;
using namespace boost::posix_time;
ifstream is(argv[1]);
std::cout << "Data file: " << argv[1] << std::endl;
string s;
int qtreeLevel = 15;
vector<int> schema = {qtreeLevel*2, qtreeLevel*2};
// use a quadtree
Nanocube<int> nc(schema);
vector<pair<int,int> > dataarray;
int i = 0;
clock_t begin = clock();
while (std::getline(is, s)) {
vector<string> output;
boost::split(output,s,boost::is_any_of("\t"));
if (output.size() != 4) {
cerr << "Bad line:" << s << endl;
continue;
}
double ori_lat = atof(output[0]) * M_PI / 180.0;
double ori_lon = atof(output[1]) * M_PI / 180.0;
double des_lat = atof(output[2]) * M_PI / 180.0;
double des_lon = atof(output[3]) * M_PI / 180.0;
if (ori_lat > 85.0511 || ori_lat < -85.0511 ||
des_lat > 85.0511 || des_lat < -85.0511 ){
cerr << "Invalid latitude: " << ori_lat << ", " << des_lat;
cerr << " (should be in [-85.0511, 85.0511])" << endl;
continue;
}
int d1 = loc2addr(ori_lat, ori_lon, qtreeLevel);
int d2 = loc2addr(des_lat, des_lon, qtreeLevel);
nc.insert(1, {d1, d2});
dataarray.push_back({d1,d2});
if (++i % 10000 == 0) {
//nc.report_size();
cout << i << endl;
}
}
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "Running time: " << elapsed_secs << endl;
{
//nc.content_compact();
ofstream os("flights.nc");
nc.write_to_binary_stream(os);
}
test(nc, dataarray, schema);
}
|
save nanocube in test_flights
|
save nanocube in test_flights
|
C++
|
mit
|
cscheid/nanocube2,cscheid/nanocube2,cscheid/nanocube2,cscheid/nanocube2
|
367912e9b3698452d537115acdc22435f6820384
|
test_merkle.cpp
|
test_merkle.cpp
|
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include <vector>
#include "snarkfront.hpp"
using namespace snarkfront;
using namespace std;
void printUsage(const char* exeName) {
cout << "usage: " << exeName
<< " -c BN128|Edwards"
" -b 256|512"
" -d tree_depth"
" -i leaf_number"
<< endl;
exit(EXIT_FAILURE);
}
template <typename PAIRING, typename EVAL, typename EVAL_PATH, typename ZK_PATH>
void runTest(const size_t treeDepth,
const size_t leafNumber)
{
EVAL currentTree(treeDepth);
vector<typename EVAL::DigType> oldLeafs;
vector<EVAL_PATH> oldPaths;
typename EVAL::HashType::WordType count = 0;
while (! currentTree.isFull()) {
const typename EVAL::DigType leaf{count};
currentTree.updatePath(leaf, oldPaths);
// save an old authentication path
oldLeafs.emplace_back(leaf);
oldPaths.emplace_back(currentTree.authPath());
currentTree.updateSiblings(leaf);
++count;
}
if (leafNumber >= oldLeafs.size()) {
cout << "leaf number " << leafNumber
<< " is larger than " << oldLeafs.size()
<< endl;
exit(EXIT_FAILURE);
}
const auto& leaf = oldLeafs[leafNumber];
const auto& authPath = oldPaths[leafNumber];
cout << "leaf " << leafNumber << " child bits ";
for (int i = authPath.childBits().size() - 1; i >= 0; --i) {
cout << authPath.childBits()[i];
}
cout << endl;
cout << "root path" << endl;
for (int i = authPath.rootPath().size() - 1; i >= 0; --i) {
cout << "[" << i << "] "
<< asciiHex(authPath.rootPath()[i], true) << endl;
}
cout << "siblings" << endl;
for (int i = authPath.siblings().size() - 1; i >= 0; --i) {
cout << "[" << i << "] "
<< asciiHex(authPath.siblings()[i], true) << endl;
}
typename ZK_PATH::DigType rt;
bless(rt, authPath.rootHash());
end_input<PAIRING>();
typename ZK_PATH::DigType zkLeaf;
bless(zkLeaf, leaf);
ZK_PATH zkAuthPath(authPath);
zkAuthPath.updatePath(zkLeaf);
assert_true(rt == zkAuthPath.rootHash());
cout << "variable count " << variable_count<PAIRING>() << endl;
}
template <typename PAIRING>
bool runTest(const string& shaBits,
const size_t treeDepth,
const size_t leafNumber)
{
typedef typename PAIRING::Fr FR;
if ("256" == shaBits) {
runTest<PAIRING,
eval::MerkleTree_SHA256,
eval::MerkleAuthPath_SHA256,
zk::MerkleAuthPath_SHA256<FR>>(
treeDepth,
leafNumber);
} else if ("512" == shaBits) {
runTest<PAIRING,
eval::MerkleTree_SHA512,
eval::MerkleAuthPath_SHA512,
zk::MerkleAuthPath_SHA512<FR>>(
treeDepth,
leafNumber);
}
GenericProgressBar progress1(cerr), progress2(cerr, 100);
cerr << "generate key pair";
const auto key = keypair<PAIRING>(progress2);
cerr << endl;
const auto in = input<PAIRING>();
cerr << "generate proof";
const auto p = proof(key, progress2);
cerr << endl;
cerr << "verify proof ";
const bool proofOK = verify(key, in, p, progress1);
cerr << endl;
return proofOK;
}
int main(int argc, char *argv[])
{
// command line switches
string ellipticCurve, shaBits;
size_t treeDepth = -1, leafNumber = -1;
int opt;
while (-1 != (opt = getopt(argc, argv, "c:b:d:i:"))) {
switch (opt) {
case ('c') :
ellipticCurve = optarg;
break;
case ('b') :
shaBits = optarg;
break;
case('d') :
{
stringstream ss(optarg);
ss >> treeDepth;
if (!ss) printUsage(argv[0]);
}
break;
case('i') :
{
stringstream ss(optarg);
ss >> leafNumber;
if (!ss) printUsage(argv[0]);
}
break;
}
}
if (shaBits.empty() || -1 == treeDepth || -1 == leafNumber) {
printUsage(argv[0]);
}
bool result;
if ("BN128" == ellipticCurve) {
// Barreto-Naehrig 128 bits
init_BN128();
result = runTest<BN128_PAIRING>(shaBits, treeDepth, leafNumber);
} else if ("Edwards" == ellipticCurve) {
// Edwards 80 bits
init_Edwards();
result = runTest<EDWARDS_PAIRING>(shaBits, treeDepth, leafNumber);
} else {
// no elliptic curve specified
printUsage(argv[0]);
}
cout << "proof verification " << (result ? "OK" : "FAIL") << endl;
exit(EXIT_SUCCESS);
}
|
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include <vector>
#include "snarkfront.hpp"
using namespace snarkfront;
using namespace std;
void printUsage(const char* exeName) {
cout << "usage: " << exeName
<< " -c BN128|Edwards"
" -b 256|512"
" -d tree_depth"
" -i leaf_number"
<< endl;
exit(EXIT_FAILURE);
}
template <typename PAIRING, typename BUNDLE, typename ZK_PATH>
void runTest(const size_t treeDepth,
const size_t leafNumber)
{
BUNDLE bundle(treeDepth);
while (! bundle.isFull()) {
const typename BUNDLE::DigType leaf{bundle.treeSize()};
bundle.addLeaf(
leaf,
leafNumber == bundle.treeSize());
}
if (leafNumber >= bundle.treeSize()) {
cout << "leaf number " << leafNumber
<< " is larger than " << bundle.treeSize()
<< endl;
exit(EXIT_FAILURE);
}
const auto& leaf = bundle.authLeaf().front();
const auto& authPath = bundle.authPath().front();
cout << "leaf " << leafNumber << " child bits ";
for (int i = authPath.childBits().size() - 1; i >= 0; --i) {
cout << authPath.childBits()[i];
}
cout << endl;
cout << "root path" << endl;
for (int i = authPath.rootPath().size() - 1; i >= 0; --i) {
cout << "[" << i << "] "
<< asciiHex(authPath.rootPath()[i], true) << endl;
}
cout << "siblings" << endl;
for (int i = authPath.siblings().size() - 1; i >= 0; --i) {
cout << "[" << i << "] "
<< asciiHex(authPath.siblings()[i], true) << endl;
}
typename ZK_PATH::DigType rt;
bless(rt, authPath.rootHash());
end_input<PAIRING>();
typename ZK_PATH::DigType zkLeaf;
bless(zkLeaf, leaf);
ZK_PATH zkAuthPath(authPath);
zkAuthPath.updatePath(zkLeaf);
assert_true(rt == zkAuthPath.rootHash());
cout << "variable count " << variable_count<PAIRING>() << endl;
}
template <typename PAIRING>
bool runTest(const string& shaBits,
const size_t treeDepth,
const size_t leafNumber)
{
typedef typename PAIRING::Fr FR;
if ("256" == shaBits) {
runTest<PAIRING,
MerkleBundle_SHA256<uint32_t>, // count could be size_t
zk::MerkleAuthPath_SHA256<FR>>(
treeDepth,
leafNumber);
} else if ("512" == shaBits) {
runTest<PAIRING,
MerkleBundle_SHA512<uint64_t>, // count could be size_t
zk::MerkleAuthPath_SHA512<FR>>(
treeDepth,
leafNumber);
}
GenericProgressBar progress1(cerr), progress2(cerr, 100);
cerr << "generate key pair";
const auto key = keypair<PAIRING>(progress2);
cerr << endl;
const auto in = input<PAIRING>();
cerr << "generate proof";
const auto p = proof(key, progress2);
cerr << endl;
cerr << "verify proof ";
const bool proofOK = verify(key, in, p, progress1);
cerr << endl;
return proofOK;
}
int main(int argc, char *argv[])
{
// command line switches
string ellipticCurve, shaBits;
size_t treeDepth = -1, leafNumber = -1;
int opt;
while (-1 != (opt = getopt(argc, argv, "c:b:d:i:"))) {
switch (opt) {
case ('c') :
ellipticCurve = optarg;
break;
case ('b') :
shaBits = optarg;
break;
case('d') :
{
stringstream ss(optarg);
ss >> treeDepth;
if (!ss) printUsage(argv[0]);
}
break;
case('i') :
{
stringstream ss(optarg);
ss >> leafNumber;
if (!ss) printUsage(argv[0]);
}
break;
}
}
if (shaBits.empty() || -1 == treeDepth || -1 == leafNumber) {
printUsage(argv[0]);
}
bool result;
if ("BN128" == ellipticCurve) {
// Barreto-Naehrig 128 bits
init_BN128();
result = runTest<BN128_PAIRING>(shaBits, treeDepth, leafNumber);
} else if ("Edwards" == ellipticCurve) {
// Edwards 80 bits
init_Edwards();
result = runTest<EDWARDS_PAIRING>(shaBits, treeDepth, leafNumber);
} else {
// no elliptic curve specified
printUsage(argv[0]);
}
cout << "proof verification " << (result ? "OK" : "FAIL") << endl;
exit(EXIT_SUCCESS);
}
|
use Merkle bundle
|
use Merkle bundle
|
C++
|
mit
|
jancarlsson/snarkfront,jancarlsson/snarkfront
|
8c2a519b5302505e15abeeeb0a31c117d44a95da
|
src/StreamBin.cpp
|
src/StreamBin.cpp
|
#include "StreamBin.h"
#include <iostream>
using std::cout;
using std::endl;
namespace sensekit {
StreamBin::StreamBin(StreamBinId id, size_t bufferLengthInBytes)
: m_id(id)
{
allocate_buffers(bufferLengthInBytes);
}
void StreamBin::allocate_buffers(size_t bufferLengthInBytes)
{
m_buffers.fill(nullptr);
for(auto& frame : m_buffers)
{
frame = new sensekit_frame_t;
frame->byteLength = bufferLengthInBytes;
frame->data = nullptr;
frame->data = new uint8_t[bufferLengthInBytes];
}
}
sensekit_frame_t* StreamBin::get_back_buffer()
{
return m_buffers[m_currentBackBufferIndex];
}
sensekit_frame_t* StreamBin::cycle_buffers()
{
if (!m_frontBufferLocked)
{
m_currentFrontBufferIndex = m_currentBackBufferIndex;
}
do
{
m_currentBackBufferIndex =
m_currentBackBufferIndex + 1 < BUFFER_COUNT ? m_currentBackBufferIndex + 1 : 0;
} while (m_currentBackBufferIndex == m_currentFrontBufferIndex);
return m_buffers[m_currentBackBufferIndex];
}
sensekit_frame_t* StreamBin::get_front_buffer()
{
return m_buffers[m_currentFrontBufferIndex];
}
StreamBin::~StreamBin()
{
for(auto& frame : m_buffers)
{
delete[] (uint8_t*)frame->data;
delete frame;
frame = nullptr;
}
}
}
|
#include "StreamBin.h"
#include <iostream>
using std::cout;
using std::endl;
namespace sensekit {
StreamBin::StreamBin(StreamBinId id, size_t bufferLengthInBytes)
: m_id(id)
{
allocate_buffers(bufferLengthInBytes);
}
void StreamBin::allocate_buffers(size_t bufferLengthInBytes)
{
for(auto& frame : m_buffers)
{
frame = new sensekit_frame_t;
frame->byteLength = bufferLengthInBytes;
frame->data = new uint8_t[bufferLengthInBytes];
}
}
sensekit_frame_t* StreamBin::get_back_buffer()
{
return m_buffers[m_currentBackBufferIndex];
}
sensekit_frame_t* StreamBin::cycle_buffers()
{
if (!m_frontBufferLocked)
{
m_currentFrontBufferIndex = m_currentBackBufferIndex;
}
do
{
m_currentBackBufferIndex =
m_currentBackBufferIndex + 1 < BUFFER_COUNT ? m_currentBackBufferIndex + 1 : 0;
} while (m_currentBackBufferIndex == m_currentFrontBufferIndex);
return m_buffers[m_currentBackBufferIndex];
}
sensekit_frame_t* StreamBin::get_front_buffer()
{
return m_buffers[m_currentFrontBufferIndex];
}
StreamBin::~StreamBin()
{
for(auto& frame : m_buffers)
{
delete[] (uint8_t*)frame->data;
delete frame;
frame = nullptr;
}
}
}
|
remove debugging statements in StreamBin
|
remove debugging statements in StreamBin
|
C++
|
apache-2.0
|
orbbec/astra,orbbec/astra,orbbec/astra,orbbec/astra,orbbec/astra
|
ecf68dfff4a23c785b523d096554d09dfa295cbd
|
src/base/types.hh
|
src/base/types.hh
|
/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* 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 copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Nathan Binkert
*/
/**
* @file
* Defines global host-dependent types:
* Counter, Tick, and (indirectly) {int,uint}{8,16,32,64}_t.
*/
#ifndef __BASE_TYPES_HH__
#define __BASE_TYPES_HH__
#include <inttypes.h>
#include <cassert>
#include <memory>
#include <ostream>
#include <stdexcept>
#include "base/refcnt.hh"
/** uint64_t constant */
#define ULL(N) ((uint64_t)N##ULL)
/** int64_t constant */
#define LL(N) ((int64_t)N##LL)
/** Statistics counter type. Not much excuse for not using a 64-bit
* integer here, but if you're desperate and only run short
* simulations you could make this 32 bits.
*/
typedef int64_t Counter;
/**
* Tick count type.
*/
typedef uint64_t Tick;
const Tick MaxTick = ULL(0xffffffffffffffff);
/**
* Cycles is a wrapper class for representing cycle counts, i.e. a
* relative difference between two points in time, expressed in a
* number of clock cycles.
*
* The Cycles wrapper class is a type-safe alternative to a
* typedef, aiming to avoid unintentional mixing of cycles and ticks
* in the code base.
*
* Note that there is no overloading of the bool operator as the
* compiler is allowed to turn booleans into integers and this causes
* a whole range of issues in a handful locations. The solution to
* this problem would be to use the safe bool idiom, but for now we
* make do without the test and use the more elaborate comparison >
* Cycles(0).
*/
class Cycles
{
private:
/** Member holding the actual value. */
uint64_t c;
public:
/** Explicit constructor assigning a value. */
explicit constexpr Cycles(uint64_t _c) : c(_c) { }
/** Default constructor for parameter classes. */
Cycles() : c(0) { }
/** Converting back to the value type. */
constexpr operator uint64_t() const { return c; }
/** Prefix increment operator. */
Cycles& operator++()
{ ++c; return *this; }
/** Prefix decrement operator. Is only temporarily used in the O3 CPU. */
Cycles& operator--()
{ assert(c != 0); --c; return *this; }
/** In-place addition of cycles. */
Cycles& operator+=(const Cycles& cc)
{ c += cc.c; return *this; }
/** Greater than comparison used for > Cycles(0). */
constexpr bool operator>(const Cycles& cc) const
{ return c > cc.c; }
constexpr Cycles operator +(const Cycles& b) const
{ return Cycles(c + b.c); }
constexpr Cycles operator -(const Cycles& b) const
{
return c >= b.c ? Cycles(c - b.c) :
throw std::invalid_argument("RHS cycle value larger than LHS");
}
constexpr Cycles operator <<(const int32_t shift) const
{ return Cycles(c << shift); }
constexpr Cycles operator >>(const int32_t shift) const
{ return Cycles(c >> shift); }
friend std::ostream& operator<<(std::ostream &out, const Cycles & cycles);
};
/**
* Address type
* This will probably be moved somewhere else in the near future.
* This should be at least as big as the biggest address width in use
* in the system, which will probably be 64 bits.
*/
typedef uint64_t Addr;
typedef uint16_t MicroPC;
static const MicroPC MicroPCRomBit = 1 << (sizeof(MicroPC) * 8 - 1);
static inline MicroPC
romMicroPC(MicroPC upc)
{
return upc | MicroPCRomBit;
}
static inline MicroPC
normalMicroPC(MicroPC upc)
{
return upc & ~MicroPCRomBit;
}
static inline bool
isRomMicroPC(MicroPC upc)
{
return MicroPCRomBit & upc;
}
const Addr MaxAddr = (Addr)-1;
typedef uint64_t RegVal;
typedef double FloatRegVal;
/**
* Thread index/ID type
*/
typedef int16_t ThreadID;
const ThreadID InvalidThreadID = (ThreadID)-1;
/** Globally unique thread context ID */
typedef int ContextID;
const ContextID InvalidContextID = (ContextID)-1;
/**
* Port index/ID type, and a symbolic name for an invalid port id.
*/
typedef int16_t PortID;
const PortID InvalidPortID = (PortID)-1;
class FaultBase;
typedef std::shared_ptr<FaultBase> Fault;
// Rather than creating a shared_ptr instance and assigning it nullptr,
// we just create an alias.
constexpr decltype(nullptr) NoFault = nullptr;
struct AtomicOpFunctor
{
virtual void operator()(uint8_t *p) = 0;
virtual AtomicOpFunctor* clone() = 0;
virtual ~AtomicOpFunctor() {}
};
template <class T>
struct TypedAtomicOpFunctor : public AtomicOpFunctor
{
void operator()(uint8_t *p) { execute((T *)p); }
virtual AtomicOpFunctor* clone() = 0;
virtual void execute(T * p) = 0;
};
enum ByteOrder {
BigEndianByteOrder,
LittleEndianByteOrder
};
#endif // __BASE_TYPES_HH__
|
/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* 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 copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Nathan Binkert
*/
/**
* @file
* Defines global host-dependent types:
* Counter, Tick, and (indirectly) {int,uint}{8,16,32,64}_t.
*/
#ifndef __BASE_TYPES_HH__
#define __BASE_TYPES_HH__
#include <inttypes.h>
#include <cassert>
#include <memory>
#include <ostream>
#include <stdexcept>
#include "base/refcnt.hh"
/** uint64_t constant */
#define ULL(N) ((uint64_t)N##ULL)
/** int64_t constant */
#define LL(N) ((int64_t)N##LL)
/** Statistics counter type. Not much excuse for not using a 64-bit
* integer here, but if you're desperate and only run short
* simulations you could make this 32 bits.
*/
typedef int64_t Counter;
/**
* Tick count type.
*/
typedef uint64_t Tick;
const Tick MaxTick = ULL(0xffffffffffffffff);
/**
* Cycles is a wrapper class for representing cycle counts, i.e. a
* relative difference between two points in time, expressed in a
* number of clock cycles.
*
* The Cycles wrapper class is a type-safe alternative to a
* typedef, aiming to avoid unintentional mixing of cycles and ticks
* in the code base.
*
* Note that there is no overloading of the bool operator as the
* compiler is allowed to turn booleans into integers and this causes
* a whole range of issues in a handful locations. The solution to
* this problem would be to use the safe bool idiom, but for now we
* make do without the test and use the more elaborate comparison >
* Cycles(0).
*/
class Cycles
{
private:
/** Member holding the actual value. */
uint64_t c;
public:
/** Explicit constructor assigning a value. */
explicit constexpr Cycles(uint64_t _c) : c(_c) { }
/** Default constructor for parameter classes. */
Cycles() : c(0) { }
/** Converting back to the value type. */
constexpr operator uint64_t() const { return c; }
/** Prefix increment operator. */
Cycles& operator++()
{ ++c; return *this; }
/** Prefix decrement operator. Is only temporarily used in the O3 CPU. */
Cycles& operator--()
{ assert(c != 0); --c; return *this; }
/** In-place addition of cycles. */
Cycles& operator+=(const Cycles& cc)
{ c += cc.c; return *this; }
/** Greater than comparison used for > Cycles(0). */
constexpr bool operator>(const Cycles& cc) const
{ return c > cc.c; }
constexpr Cycles operator +(const Cycles& b) const
{ return Cycles(c + b.c); }
constexpr Cycles operator -(const Cycles& b) const
{
return c >= b.c ? Cycles(c - b.c) :
throw std::invalid_argument("RHS cycle value larger than LHS");
}
constexpr Cycles operator <<(const int32_t shift) const
{ return Cycles(c << shift); }
constexpr Cycles operator >>(const int32_t shift) const
{ return Cycles(c >> shift); }
friend std::ostream& operator<<(std::ostream &out, const Cycles & cycles);
};
/**
* Address type
* This will probably be moved somewhere else in the near future.
* This should be at least as big as the biggest address width in use
* in the system, which will probably be 64 bits.
*/
typedef uint64_t Addr;
typedef uint16_t MicroPC;
static const MicroPC MicroPCRomBit = 1 << (sizeof(MicroPC) * 8 - 1);
static inline MicroPC
romMicroPC(MicroPC upc)
{
return upc | MicroPCRomBit;
}
static inline MicroPC
normalMicroPC(MicroPC upc)
{
return upc & ~MicroPCRomBit;
}
static inline bool
isRomMicroPC(MicroPC upc)
{
return MicroPCRomBit & upc;
}
const Addr MaxAddr = (Addr)-1;
typedef uint64_t RegVal;
typedef double FloatRegVal;
static inline uint32_t
floatToBits32(float val)
{
union
{
float f;
uint32_t i;
} u;
u.f = val;
return u.i;
}
static inline uint64_t
floatToBits64(double val)
{
union
{
double f;
uint64_t i;
} u;
u.f = val;
return u.i;
}
static inline uint64_t floatToBits(double val) { return floatToBits64(val); }
static inline uint32_t floatToBits(float val) { return floatToBits32(val); }
static inline float
bitsToFloat32(uint32_t val)
{
union
{
float f;
uint32_t i;
} u;
u.i = val;
return u.f;
}
static inline double
bitsToFloat64(uint64_t val)
{
union
{
double f;
uint64_t i;
} u;
u.i = val;
return u.f;
}
static inline double bitsToFloat(uint64_t val) { return bitsToFloat64(val); }
static inline float bitsToFloat(uint32_t val) { return bitsToFloat32(val); }
/**
* Thread index/ID type
*/
typedef int16_t ThreadID;
const ThreadID InvalidThreadID = (ThreadID)-1;
/** Globally unique thread context ID */
typedef int ContextID;
const ContextID InvalidContextID = (ContextID)-1;
/**
* Port index/ID type, and a symbolic name for an invalid port id.
*/
typedef int16_t PortID;
const PortID InvalidPortID = (PortID)-1;
class FaultBase;
typedef std::shared_ptr<FaultBase> Fault;
// Rather than creating a shared_ptr instance and assigning it nullptr,
// we just create an alias.
constexpr decltype(nullptr) NoFault = nullptr;
struct AtomicOpFunctor
{
virtual void operator()(uint8_t *p) = 0;
virtual AtomicOpFunctor* clone() = 0;
virtual ~AtomicOpFunctor() {}
};
template <class T>
struct TypedAtomicOpFunctor : public AtomicOpFunctor
{
void operator()(uint8_t *p) { execute((T *)p); }
virtual AtomicOpFunctor* clone() = 0;
virtual void execute(T * p) = 0;
};
enum ByteOrder {
BigEndianByteOrder,
LittleEndianByteOrder
};
#endif // __BASE_TYPES_HH__
|
Add some functions to convert floats to bits and vice versa.
|
base: Add some functions to convert floats to bits and vice versa.
These make it easier to extract the binary representation of floats and
doubles, and given a binary representation convert it back again.
The versions with a size prefix are safer to use since they make it
clear what size inputs/outputs are expected. The versions without are
to make writing generic code easier in case the same code snippet,
templated function, etc., needs to be applied in both circumstances.
Change-Id: Ib1f35a7e88e00806a7c639c211c5699b4af5a472
Reviewed-on: https://gem5-review.googlesource.com/c/14455
Reviewed-by: Giacomo Travaglini <[email protected]>
Maintainer: Gabe Black <[email protected]>
|
C++
|
bsd-3-clause
|
TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,gem5/gem5,TUD-OS/gem5-dtu,gem5/gem5,gem5/gem5,gem5/gem5,TUD-OS/gem5-dtu,gem5/gem5,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,gem5/gem5,TUD-OS/gem5-dtu,gem5/gem5
|
61cb8080448a8104a864641bd8267498512fb97c
|
tests/test_shell.cpp
|
tests/test_shell.cpp
|
#include <atomic>
#include "../shell.h"
#include "../coroutine.h"
#include <gtest/gtest.h>
class CoroTest : testing::Test { };
using namespace cu;
TEST(CoroTest, Test1)
{
std::vector<std::string> lines;
cmd(find("../.."), grep("test_"), out(lines));
for (auto& line : lines)
std::cout << line << std::endl;
}
TEST(CoroTest, Test2)
{
cmd(find("../.."),
grep(".*\\.cpp$|.*\\.h$"),
cat(),
grep("class|struct|typedef|using|void|int|double|float"),
grep_v("enable_if|;|\"|\'"),
split(" "),
trim(),
uniq(),
join(" "),
out());
}
TEST(CoroTest, Test3)
{
std::vector<cu::pull_type_ptr<void> > coros;
for(int i=1; i<10; ++i)
{
coros.emplace_back(cu::make_generator<void>(
[=](auto& yield)
{
std::cout << "create " << i << std::endl;
yield();
std::cout << "download " << i << std::endl;
yield();
std::cout << "patching " << i << std::endl;
yield();
std::cout << "compile " << i << std::endl;
yield();
std::cout << "tests " << i << std::endl;
yield();
std::cout << "packing " << i << std::endl;
yield();
std::cout << "destroy " << i << std::endl;
}
));
}
bool any_updated = true;
while(any_updated)
{
any_updated = false;
for(auto& c : coros)
{
if(*c)
{
(*c)();
any_updated = true;
}
}
}
}
|
#include <atomic>
#include "../shell.h"
#include "../coroutine.h"
#include <gtest/gtest.h>
class CoroTest : testing::Test { };
using namespace cu;
TEST(CoroTest, Test1)
{
std::vector<std::string> lines;
cmd(find("../.."), grep("test_"), out(lines));
for (auto& line : lines)
std::cout << line << std::endl;
}
TEST(CoroTest, Test2)
{
cmd(find("../.."),
grep(".*\\.cpp$|.*\\.h$"),
cat(),
grep("class|struct|typedef|using|void|int|double|float"),
grep_v("enable_if|;|\"|\'"),
split(" "),
trim(),
uniq(),
join(" "),
out());
}
namespace cu {
class scheduler {
public:
using control_type = void;
template <typename Function>
void spawn(Function&& func)
{
_running.emplace_back(cu::make_generator<control_type>(std::forward<Function>(func)));
}
/*
return true if any is updated
*/
bool run()
{
bool any_updated = false;
_pid = 0;
for(auto& c : coros)
{
if(*c)
{
(*c)();
any_updated = true;
}
++_pid;
}
return any_updated;
}
/*
return true if have pending work
*/
// run_forever()
// run_until_complete()
void run_until_complete()
{
bool any_updated = true;
while(any_updated)
{
any_updated = run();
}
}
void run_forever()
{
while(true)
{
run();
}
}
int getpid() const {return _pid;}
protected:
// normal running
std::vector<cu::pull_type_ptr<control_type> > _running;
// locked
// std::vector<cu::pull_type_ptr<control_type> > _blocked;
// unlocked and prepared for return
// std::vector<cu::pull_type_ptr<control_type> > _ready;
private:
int _pid;
};
}
TEST(CoroTest, Test3)
{
cu::scheduler sch;
for(int i=1; i<10; ++i)
{
sch.spawn(
[=](auto& yield) {
std::cout << "create " << i << std::endl;
yield();
std::cout << "download " << i << std::endl;
yield();
std::cout << "patching " << i << std::endl;
yield();
std::cout << "compile " << i << std::endl;
yield();
std::cout << "tests " << i << std::endl;
yield();
std::cout << "packing " << i << std::endl;
yield();
std::cout << "destroy " << i << std::endl;
}
);
}
sch.run_until_complete();
}
|
Update test_shell.cpp
|
Update test_shell.cpp
|
C++
|
mit
|
makiolo/cppunix,makiolo/cppunix
|
4bf189cc5d9f59644ea4f829de9a3e397d155837
|
tools/ouzel/main.cpp
|
tools/ouzel/main.cpp
|
#include <cstdlib>
#include <iostream>
#include <stdexcept>
int main(int argc, const char* argv[])
{
enum class Action
{
NONE,
NEW_PROJECT,
GENERATE
};
enum class Project
{
ALL,
VISUAL_STUDIO,
XCODE,
MAKEFILE
};
Action action = Action::NONE;
std::string path;
std::string name;
Project project = Project::ALL;
for (int i = 1; i < argc; ++i)
{
if (std::string(argv[i]) == "--help")
{
std::cout << "Usage:" << std::endl;
std::cout << argv[0] << " [--help] [--new-project <name>] [--location <location>]" << std::endl;
return EXIT_SUCCESS;
}
else if (std::string(argv[i]) == "--new-project")
{
if (++i >= argc)
throw std::runtime_error("Invalid command");
action = Action::NEW_PROJECT;
path = std::string(argv[i]);
}
else if (std::string(argv[i]) == "--name")
{
if (++i >= argc)
throw std::runtime_error("Invalid command");
name = std::string(argv[i]);
}
else if (std::string(argv[i]) == "--generate")
{
action = Action::GENERATE;
if (++i >= argc)
throw std::runtime_error("Invalid command");
path = std::string(argv[i]);
}
else if (std::string(argv[i]) == "--project")
{
if (std::string(argv[i]) == "visualstudio")
project = Project::VISUAL_STUDIO;
else if (std::string(argv[i]) == "xcode")
project = Project::XCODE;
else if (std::string(argv[i]) == "makefile")
project = Project::MAKEFILE;
else
throw std::runtime_error("Invalid project");
}
}
try
{
switch (action)
{
case Action::NONE:
throw std::runtime_error("No action selected");
case Action::NEW_PROJECT:
break;
case Action::GENERATE:
break;
default:
throw std::runtime_error("Invalid action selected");
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return EXIT_SUCCESS;
}
|
#include <cstdlib>
#include <iostream>
#include <stdexcept>
int main(int argc, const char* argv[])
{
enum class Action
{
NONE,
NEW_PROJECT,
GENERATE
};
enum class Project
{
ALL,
VISUAL_STUDIO,
XCODE,
MAKEFILE
};
enum class Platform
{
ALL,
WINDOWS,
MACOS,
LINUX,
IOS,
TVOS,
ANDROID,
EMSCRIPTEN
};
Action action = Action::NONE;
std::string path;
std::string name;
Project project = Project::ALL;
Platform platform = Platform::ALL;
for (int i = 1; i < argc; ++i)
{
if (std::string(argv[i]) == "--help")
{
std::cout << "Usage:" << std::endl;
std::cout << argv[0] << " [--help] [--new-project <name>] [--location <location>]" << std::endl;
return EXIT_SUCCESS;
}
else if (std::string(argv[i]) == "--new-project")
{
if (++i >= argc)
throw std::runtime_error("Invalid command");
action = Action::NEW_PROJECT;
path = std::string(argv[i]);
}
else if (std::string(argv[i]) == "--name")
{
if (++i >= argc)
throw std::runtime_error("Invalid command");
name = std::string(argv[i]);
}
else if (std::string(argv[i]) == "--generate")
{
action = Action::GENERATE;
if (++i >= argc)
throw std::runtime_error("Invalid command");
path = std::string(argv[i]);
}
else if (std::string(argv[i]) == "--project")
{
if (std::string(argv[i]) == "all")
project = Project::ALL;
else if (std::string(argv[i]) == "visualstudio")
project = Project::VISUAL_STUDIO;
else if (std::string(argv[i]) == "xcode")
project = Project::XCODE;
else if (std::string(argv[i]) == "makefile")
project = Project::MAKEFILE;
else
throw std::runtime_error("Invalid project");
}
else if (std::string(argv[i]) == "--platform")
{
if (std::string(argv[i]) == "all")
platform = Platform::ALL;
else if (std::string(argv[i]) == "windows")
platform = Platform::WINDOWS;
else if (std::string(argv[i]) == "macos")
platform = Platform::MACOS;
else if (std::string(argv[i]) == "linux")
platform = Platform::LINUX;
else if (std::string(argv[i]) == "ios")
platform = Platform::IOS;
else if (std::string(argv[i]) == "tvos")
platform = Platform::TVOS;
else if (std::string(argv[i]) == "android")
platform = Platform::ANDROID;
else if (std::string(argv[i]) == "emscripten")
platform = Platform::EMSCRIPTEN;
else
throw std::runtime_error("Invalid platform");
}
}
try
{
switch (action)
{
case Action::NONE:
throw std::runtime_error("No action selected");
case Action::NEW_PROJECT:
break;
case Action::GENERATE:
break;
default:
throw std::runtime_error("Invalid action selected");
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return EXIT_SUCCESS;
}
|
Add platforms to the ouzel utility
|
Add platforms to the ouzel utility
|
C++
|
unlicense
|
elvman/ouzel,elvman/ouzel,elnormous/ouzel,elnormous/ouzel,elnormous/ouzel
|
c8f398df79ac051477ab0846e12258ef4dc3b78b
|
chrome/browser/bookmarks/enhanced_bookmarks_features.cc
|
chrome/browser/bookmarks/enhanced_bookmarks_features.cc
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/bookmarks/enhanced_bookmarks_features.h"
#include "base/command_line.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "base/sha1.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "components/sync_driver/pref_names.h"
#include "components/variations/variations_associated_data.h"
#include "extensions/common/features/feature.h"
#include "extensions/common/features/feature_provider.h"
namespace {
const char kFieldTrialName[] = "EnhancedBookmarks";
// Get extension id from Finch EnhancedBookmarks group parameters.
std::string GetEnhancedBookmarksExtensionIdFromFinch() {
return variations::GetVariationParamValue(kFieldTrialName, "id");
}
// Returns true if enhanced bookmarks experiment is enabled from Finch.
bool IsEnhancedBookmarksExperimentEnabledFromFinch() {
#if defined(OS_ANDROID)
return false;
#endif
std::string ext_id = GetEnhancedBookmarksExtensionIdFromFinch();
const extensions::FeatureProvider* feature_provider =
extensions::FeatureProvider::GetPermissionFeatures();
extensions::Feature* feature = feature_provider->GetFeature("metricsPrivate");
return feature && feature->IsIdInWhitelist(ext_id);
}
}; // namespace
bool GetBookmarksExperimentExtensionID(const PrefService* user_prefs,
std::string* extension_id) {
BookmarksExperimentState bookmarks_experiment_state =
static_cast<BookmarksExperimentState>(user_prefs->GetInteger(
sync_driver::prefs::kEnhancedBookmarksExperimentEnabled));
if (bookmarks_experiment_state == BOOKMARKS_EXPERIMENT_ENABLED_FROM_FINCH) {
*extension_id = GetEnhancedBookmarksExtensionIdFromFinch();
return !extension_id->empty();
}
if (bookmarks_experiment_state == BOOKMARKS_EXPERIMENT_ENABLED) {
*extension_id = user_prefs->GetString(
sync_driver::prefs::kEnhancedBookmarksExtensionId);
return !extension_id->empty();
}
return false;
}
void UpdateBookmarksExperimentState(
PrefService* user_prefs,
PrefService* local_state,
bool user_signed_in,
BookmarksExperimentState experiment_enabled_from_sync) {
PrefService* flags_storage = local_state;
#if defined(OS_CHROMEOS)
// Chrome OS is using user prefs for flags storage.
flags_storage = user_prefs;
#endif
BookmarksExperimentState bookmarks_experiment_state_before =
static_cast<BookmarksExperimentState>(user_prefs->GetInteger(
sync_driver::prefs::kEnhancedBookmarksExperimentEnabled));
// If user signed out, clear possible previous state.
if (!user_signed_in) {
bookmarks_experiment_state_before = BOOKMARKS_EXPERIMENT_NONE;
ForceFinchBookmarkExperimentIfNeeded(flags_storage,
BOOKMARKS_EXPERIMENT_NONE);
}
// kEnhancedBookmarksExperiment flag could have values "", "1" and "0".
// "0" - user opted out.
bool opt_out = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kEnhancedBookmarksExperiment) == "0";
BookmarksExperimentState bookmarks_experiment_new_state =
BOOKMARKS_EXPERIMENT_NONE;
if (IsEnhancedBookmarksExperimentEnabledFromFinch() && !user_signed_in) {
if (opt_out) {
// Experiment enabled but user opted out.
bookmarks_experiment_new_state = BOOKMARKS_EXPERIMENT_OPT_OUT_FROM_FINCH;
} else {
// Experiment enabled.
bookmarks_experiment_new_state = BOOKMARKS_EXPERIMENT_ENABLED_FROM_FINCH;
}
} else if (experiment_enabled_from_sync == BOOKMARKS_EXPERIMENT_ENABLED) {
// Experiment enabled from Chrome sync.
if (opt_out) {
// Experiment enabled but user opted out.
bookmarks_experiment_new_state =
BOOKMARKS_EXPERIMENT_ENABLED_USER_OPT_OUT;
} else {
// Experiment enabled.
bookmarks_experiment_new_state = BOOKMARKS_EXPERIMENT_ENABLED;
}
} else if (experiment_enabled_from_sync == BOOKMARKS_EXPERIMENT_NONE) {
// Experiment is not enabled from Chrome sync.
bookmarks_experiment_new_state = BOOKMARKS_EXPERIMENT_NONE;
} else if (bookmarks_experiment_state_before ==
BOOKMARKS_EXPERIMENT_ENABLED) {
if (opt_out) {
// Experiment enabled but user opted out.
bookmarks_experiment_new_state =
BOOKMARKS_EXPERIMENT_ENABLED_USER_OPT_OUT;
} else {
bookmarks_experiment_new_state = BOOKMARKS_EXPERIMENT_ENABLED;
}
} else if (bookmarks_experiment_state_before ==
BOOKMARKS_EXPERIMENT_ENABLED_USER_OPT_OUT) {
if (opt_out) {
bookmarks_experiment_new_state =
BOOKMARKS_EXPERIMENT_ENABLED_USER_OPT_OUT;
} else {
// User opted in again.
bookmarks_experiment_new_state = BOOKMARKS_EXPERIMENT_ENABLED;
}
}
UMA_HISTOGRAM_ENUMERATION("EnhancedBookmarks.SyncExperimentState",
bookmarks_experiment_new_state,
BOOKMARKS_EXPERIMENT_ENUM_SIZE);
user_prefs->SetInteger(
sync_driver::prefs::kEnhancedBookmarksExperimentEnabled,
bookmarks_experiment_new_state);
ForceFinchBookmarkExperimentIfNeeded(flags_storage,
bookmarks_experiment_new_state);
}
void ForceFinchBookmarkExperimentIfNeeded(
PrefService* flags_storage,
BookmarksExperimentState bookmarks_experiment_state) {
if (!flags_storage)
return;
ListPrefUpdate update(flags_storage, prefs::kEnabledLabsExperiments);
base::ListValue* experiments_list = update.Get();
if (!experiments_list)
return;
size_t index;
if (bookmarks_experiment_state == BOOKMARKS_EXPERIMENT_NONE) {
experiments_list->Remove(
base::StringValue(switches::kManualEnhancedBookmarks), &index);
experiments_list->Remove(
base::StringValue(switches::kManualEnhancedBookmarksOptout), &index);
} else if (bookmarks_experiment_state == BOOKMARKS_EXPERIMENT_ENABLED) {
experiments_list->Remove(
base::StringValue(switches::kManualEnhancedBookmarksOptout), &index);
experiments_list->AppendIfNotPresent(
new base::StringValue(switches::kManualEnhancedBookmarks));
} else if (bookmarks_experiment_state ==
BOOKMARKS_EXPERIMENT_ENABLED_USER_OPT_OUT) {
experiments_list->Remove(
base::StringValue(switches::kManualEnhancedBookmarks), &index);
experiments_list->AppendIfNotPresent(
new base::StringValue(switches::kManualEnhancedBookmarksOptout));
}
}
bool IsEnhancedBookmarksExperimentEnabled() {
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kManualEnhancedBookmarks) ||
command_line->HasSwitch(switches::kManualEnhancedBookmarksOptout)) {
return true;
}
return IsEnhancedBookmarksExperimentEnabledFromFinch();
}
#if defined(OS_ANDROID)
bool IsEnhancedBookmarkImageFetchingEnabled() {
if (IsEnhancedBookmarksExperimentEnabled())
return true;
// Salient images are collected from visited bookmarked pages even if the
// enhanced bookmark feature is turned off. This is to have some images
// available so that in the future, when the feature is turned on, the user
// experience is not a big list of flat colors. However as a precautionary
// measure it is possible to disable this collection of images from finch.
std::string disable_fetching = variations::GetVariationParamValue(
kFieldTrialName, "DisableImagesFetching");
return disable_fetching.empty();
}
#endif
bool IsEnableDomDistillerSet() {
if (CommandLine::ForCurrentProcess()->
HasSwitch(switches::kEnableDomDistiller)) {
return true;
}
if (variations::GetVariationParamValue(
kFieldTrialName, "enable-dom-distiller") == "1")
return true;
return false;
}
bool IsEnableSyncArticlesSet() {
if (CommandLine::ForCurrentProcess()->
HasSwitch(switches::kEnableSyncArticles)) {
return true;
}
if (variations::GetVariationParamValue(
kFieldTrialName, "enable-sync-articles") == "1")
return true;
return false;
}
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/bookmarks/enhanced_bookmarks_features.h"
#include "base/command_line.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "base/sha1.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "components/sync_driver/pref_names.h"
#include "components/variations/variations_associated_data.h"
#include "extensions/common/features/feature.h"
#include "extensions/common/features/feature_provider.h"
namespace {
const char kFieldTrialName[] = "EnhancedBookmarks";
// Get extension id from Finch EnhancedBookmarks group parameters.
std::string GetEnhancedBookmarksExtensionIdFromFinch() {
return variations::GetVariationParamValue(kFieldTrialName, "id");
}
// Returns true if enhanced bookmarks experiment is enabled from Finch.
bool IsEnhancedBookmarksExperimentEnabledFromFinch() {
const std::string ext_id = GetEnhancedBookmarksExtensionIdFromFinch();
#if defined(OS_ANDROID)
return !ext_id.empty();
#else
const extensions::FeatureProvider* feature_provider =
extensions::FeatureProvider::GetPermissionFeatures();
extensions::Feature* feature = feature_provider->GetFeature("metricsPrivate");
return feature && feature->IsIdInWhitelist(ext_id);
#endif
}
}; // namespace
bool GetBookmarksExperimentExtensionID(const PrefService* user_prefs,
std::string* extension_id) {
BookmarksExperimentState bookmarks_experiment_state =
static_cast<BookmarksExperimentState>(user_prefs->GetInteger(
sync_driver::prefs::kEnhancedBookmarksExperimentEnabled));
if (bookmarks_experiment_state == BOOKMARKS_EXPERIMENT_ENABLED_FROM_FINCH) {
*extension_id = GetEnhancedBookmarksExtensionIdFromFinch();
return !extension_id->empty();
}
if (bookmarks_experiment_state == BOOKMARKS_EXPERIMENT_ENABLED) {
*extension_id = user_prefs->GetString(
sync_driver::prefs::kEnhancedBookmarksExtensionId);
return !extension_id->empty();
}
return false;
}
void UpdateBookmarksExperimentState(
PrefService* user_prefs,
PrefService* local_state,
bool user_signed_in,
BookmarksExperimentState experiment_enabled_from_sync) {
PrefService* flags_storage = local_state;
#if defined(OS_CHROMEOS)
// Chrome OS is using user prefs for flags storage.
flags_storage = user_prefs;
#endif
BookmarksExperimentState bookmarks_experiment_state_before =
static_cast<BookmarksExperimentState>(user_prefs->GetInteger(
sync_driver::prefs::kEnhancedBookmarksExperimentEnabled));
// If user signed out, clear possible previous state.
if (!user_signed_in) {
bookmarks_experiment_state_before = BOOKMARKS_EXPERIMENT_NONE;
ForceFinchBookmarkExperimentIfNeeded(flags_storage,
BOOKMARKS_EXPERIMENT_NONE);
}
// kEnhancedBookmarksExperiment flag could have values "", "1" and "0".
// "0" - user opted out.
bool opt_out = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kEnhancedBookmarksExperiment) == "0";
BookmarksExperimentState bookmarks_experiment_new_state =
BOOKMARKS_EXPERIMENT_NONE;
if (IsEnhancedBookmarksExperimentEnabledFromFinch() && !user_signed_in) {
if (opt_out) {
// Experiment enabled but user opted out.
bookmarks_experiment_new_state = BOOKMARKS_EXPERIMENT_OPT_OUT_FROM_FINCH;
} else {
// Experiment enabled.
bookmarks_experiment_new_state = BOOKMARKS_EXPERIMENT_ENABLED_FROM_FINCH;
}
} else if (experiment_enabled_from_sync == BOOKMARKS_EXPERIMENT_ENABLED) {
// Experiment enabled from Chrome sync.
if (opt_out) {
// Experiment enabled but user opted out.
bookmarks_experiment_new_state =
BOOKMARKS_EXPERIMENT_ENABLED_USER_OPT_OUT;
} else {
// Experiment enabled.
bookmarks_experiment_new_state = BOOKMARKS_EXPERIMENT_ENABLED;
}
} else if (experiment_enabled_from_sync == BOOKMARKS_EXPERIMENT_NONE) {
// Experiment is not enabled from Chrome sync.
bookmarks_experiment_new_state = BOOKMARKS_EXPERIMENT_NONE;
} else if (bookmarks_experiment_state_before ==
BOOKMARKS_EXPERIMENT_ENABLED) {
if (opt_out) {
// Experiment enabled but user opted out.
bookmarks_experiment_new_state =
BOOKMARKS_EXPERIMENT_ENABLED_USER_OPT_OUT;
} else {
bookmarks_experiment_new_state = BOOKMARKS_EXPERIMENT_ENABLED;
}
} else if (bookmarks_experiment_state_before ==
BOOKMARKS_EXPERIMENT_ENABLED_USER_OPT_OUT) {
if (opt_out) {
bookmarks_experiment_new_state =
BOOKMARKS_EXPERIMENT_ENABLED_USER_OPT_OUT;
} else {
// User opted in again.
bookmarks_experiment_new_state = BOOKMARKS_EXPERIMENT_ENABLED;
}
}
UMA_HISTOGRAM_ENUMERATION("EnhancedBookmarks.SyncExperimentState",
bookmarks_experiment_new_state,
BOOKMARKS_EXPERIMENT_ENUM_SIZE);
user_prefs->SetInteger(
sync_driver::prefs::kEnhancedBookmarksExperimentEnabled,
bookmarks_experiment_new_state);
ForceFinchBookmarkExperimentIfNeeded(flags_storage,
bookmarks_experiment_new_state);
}
void ForceFinchBookmarkExperimentIfNeeded(
PrefService* flags_storage,
BookmarksExperimentState bookmarks_experiment_state) {
if (!flags_storage)
return;
ListPrefUpdate update(flags_storage, prefs::kEnabledLabsExperiments);
base::ListValue* experiments_list = update.Get();
if (!experiments_list)
return;
size_t index;
if (bookmarks_experiment_state == BOOKMARKS_EXPERIMENT_NONE) {
experiments_list->Remove(
base::StringValue(switches::kManualEnhancedBookmarks), &index);
experiments_list->Remove(
base::StringValue(switches::kManualEnhancedBookmarksOptout), &index);
} else if (bookmarks_experiment_state == BOOKMARKS_EXPERIMENT_ENABLED) {
experiments_list->Remove(
base::StringValue(switches::kManualEnhancedBookmarksOptout), &index);
experiments_list->AppendIfNotPresent(
new base::StringValue(switches::kManualEnhancedBookmarks));
} else if (bookmarks_experiment_state ==
BOOKMARKS_EXPERIMENT_ENABLED_USER_OPT_OUT) {
experiments_list->Remove(
base::StringValue(switches::kManualEnhancedBookmarks), &index);
experiments_list->AppendIfNotPresent(
new base::StringValue(switches::kManualEnhancedBookmarksOptout));
}
}
bool IsEnhancedBookmarksExperimentEnabled() {
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kManualEnhancedBookmarks) ||
command_line->HasSwitch(switches::kManualEnhancedBookmarksOptout)) {
return true;
}
return IsEnhancedBookmarksExperimentEnabledFromFinch();
}
#if defined(OS_ANDROID)
bool IsEnhancedBookmarkImageFetchingEnabled() {
if (IsEnhancedBookmarksExperimentEnabled())
return true;
// Salient images are collected from visited bookmarked pages even if the
// enhanced bookmark feature is turned off. This is to have some images
// available so that in the future, when the feature is turned on, the user
// experience is not a big list of flat colors. However as a precautionary
// measure it is possible to disable this collection of images from finch.
std::string disable_fetching = variations::GetVariationParamValue(
kFieldTrialName, "DisableImagesFetching");
return disable_fetching.empty();
}
#endif
bool IsEnableDomDistillerSet() {
if (CommandLine::ForCurrentProcess()->
HasSwitch(switches::kEnableDomDistiller)) {
return true;
}
if (variations::GetVariationParamValue(
kFieldTrialName, "enable-dom-distiller") == "1")
return true;
return false;
}
bool IsEnableSyncArticlesSet() {
if (CommandLine::ForCurrentProcess()->
HasSwitch(switches::kEnableSyncArticles)) {
return true;
}
if (variations::GetVariationParamValue(
kFieldTrialName, "enable-sync-articles") == "1")
return true;
return false;
}
|
Check if enhanced bookmarks id is set by finch.
|
[Android] Check if enhanced bookmarks id is set by finch.
BUG=401921
Review URL: https://codereview.chromium.org/454983002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@289265 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
ondra-novak/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,ondra-novak/chromium.src,littlstar/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,littlstar/chromium.src,littlstar/chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,littlstar/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src
|
5fde94c8c0b81c919e11dd94e702a038edfab5ce
|
include/affine_invariant_features/affine_invariant_feature.hpp
|
include/affine_invariant_features/affine_invariant_feature.hpp
|
#ifndef AFFINE_INVARIANT_FEATURES_AFFINE_INVARIANT_FEATURE
#define AFFINE_INVARIANT_FEATURES_AFFINE_INVARIANT_FEATURE
#include <algorithm>
#include <vector>
#include <affine_invariant_features/affine_invariant_feature_base.hpp>
#include <affine_invariant_features/parallel_tasks.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/imgproc.hpp>
namespace affine_invariant_features {
//
// AffineInvariantFeature that samples features in various affine transformation space
//
class AffineInvariantFeature : public AffineInvariantFeatureBase {
protected:
// the private constructor. users must use create() to instantiate an AffineInvariantFeature
AffineInvariantFeature(const cv::Ptr< cv::Feature2D > detector,
const cv::Ptr< cv::Feature2D > extractor, const double nstripes)
: AffineInvariantFeatureBase(detector, extractor), nstripes_(nstripes) {
// generate parameters for affine invariant sampling
phi_params_.push_back(0.);
tilt_params_.push_back(1.);
for (int i = 1; i < 6; ++i) {
const double tilt(std::pow(2., 0.5 * i));
for (double phi = 0.; phi < 180.; phi += 72. / tilt) {
phi_params_.push_back(phi);
tilt_params_.push_back(tilt);
}
}
ntasks_ = phi_params_.size();
}
public:
virtual ~AffineInvariantFeature() {}
//
// unique interfaces to instantiate an AffineInvariantFeature
//
static cv::Ptr< AffineInvariantFeature > create(const cv::Ptr< cv::Feature2D > feature,
const double nstripes = -1.) {
return new AffineInvariantFeature(feature, feature, nstripes);
}
static cv::Ptr< AffineInvariantFeature > create(const cv::Ptr< cv::Feature2D > detector,
const cv::Ptr< cv::Feature2D > extractor,
const double nstripes = -1.) {
return new AffineInvariantFeature(detector, extractor, nstripes);
}
//
// overloaded functions from AffineInvariantFeatureBase or its base class
//
virtual void compute(cv::InputArray image, std::vector< cv::KeyPoint > &keypoints,
cv::OutputArray descriptors) {
// extract the input
const cv::Mat image_mat(image.getMat());
// prepare outputs of following parallel processing
std::vector< std::vector< cv::KeyPoint > > keypoints_array(ntasks_, keypoints);
std::vector< cv::Mat > descriptors_array(ntasks_);
// bind each parallel task and arguments
ParallelTasks tasks(ntasks_);
for (std::size_t i = 0; i < ntasks_; ++i) {
tasks[i] = boost::bind(&AffineInvariantFeature::computeTask, this, boost::ref(image_mat),
boost::ref(keypoints_array[i]), boost::ref(descriptors_array[i]),
phi_params_[i], tilt_params_[i]);
}
// do parallel tasks
cv::parallel_for_(cv::Range(0, ntasks_), tasks, nstripes_);
// fill the final outputs
extendKeypoints(keypoints_array, keypoints);
extendDescriptors(descriptors_array, descriptors);
}
virtual void detect(cv::InputArray image, std::vector< cv::KeyPoint > &keypoints,
cv::InputArray mask = cv::noArray()) {
// extract inputs
const cv::Mat image_mat(image.getMat());
const cv::Mat mask_mat(mask.getMat());
// prepare an output of following parallel processing
std::vector< std::vector< cv::KeyPoint > > keypoints_array(ntasks_);
// bind each parallel task and arguments
ParallelTasks tasks(ntasks_);
for (std::size_t i = 0; i < ntasks_; ++i) {
tasks[i] = boost::bind(&AffineInvariantFeature::detectTask, this, boost::ref(image_mat),
boost::ref(mask_mat), boost::ref(keypoints_array[i]), phi_params_[i],
tilt_params_[i]);
}
// do parallel tasks
cv::parallel_for_(cv::Range(0, ntasks_), tasks, nstripes_);
// fill the final output
extendKeypoints(keypoints_array, keypoints);
}
virtual void detectAndCompute(cv::InputArray image, cv::InputArray mask,
std::vector< cv::KeyPoint > &keypoints, cv::OutputArray descriptors,
bool useProvidedKeypoints = false) {
// just compute descriptors if the keypoints are provided
if (useProvidedKeypoints) {
compute(image, keypoints, descriptors);
return;
}
// extract inputs
const cv::Mat image_mat(image.getMat());
const cv::Mat mask_mat(mask.getMat());
// prepare outputs of following parallel processing
std::vector< std::vector< cv::KeyPoint > > keypoints_array(ntasks_);
std::vector< cv::Mat > descriptors_array(ntasks_);
// bind each parallel task and arguments
ParallelTasks tasks(ntasks_);
for (std::size_t i = 0; i < ntasks_; ++i) {
tasks[i] =
boost::bind(&AffineInvariantFeature::detectAndComputeTask, this, boost::ref(image_mat),
boost::ref(mask_mat), boost::ref(keypoints_array[i]),
boost::ref(descriptors_array[i]), phi_params_[i], tilt_params_[i]);
}
// do parallel tasks
cv::parallel_for_(cv::Range(0, ntasks_), tasks, nstripes_);
// fill the final outputs
extendKeypoints(keypoints_array, keypoints);
extendDescriptors(descriptors_array, descriptors);
}
virtual cv::String getDefaultName() const { return "AffineInvariantFeature"; }
protected:
void computeTask(const cv::Mat &src_image, std::vector< cv::KeyPoint > &keypoints,
cv::Mat &descriptors, const double phi, const double tilt) const {
// apply the affine transformation to the image on the basis of the given parameters
cv::Mat image(src_image.clone());
cv::Matx23f affine;
warpImage(image, affine, phi, tilt);
// apply the affine transformation to keypoints
transformKeypoints(keypoints, affine);
// extract descriptors on the skewed image and keypoints
CV_Assert(extractor_);
extractor_->compute(image, keypoints, descriptors);
// invert keypoints
invertKeypoints(keypoints, affine);
}
void detectTask(const cv::Mat &src_image, const cv::Mat &src_mask,
std::vector< cv::KeyPoint > &keypoints, const double phi,
const double tilt) const {
// apply the affine transformation to the image on the basis of the given parameters
cv::Mat image(src_image.clone());
cv::Matx23f affine;
warpImage(image, affine, phi, tilt);
// apply the affine transformation to the mask
cv::Mat mask(src_mask.empty() ? cv::Mat(src_image.size(), CV_8UC1, 255) : src_mask.clone());
warpMask(mask, affine, image.size());
// detect keypoints on the skewed image and mask
CV_Assert(detector_);
detector_->detect(image, keypoints, mask);
// invert keypoints
invertKeypoints(keypoints, affine);
}
void detectAndComputeTask(const cv::Mat &src_image, const cv::Mat &src_mask,
std::vector< cv::KeyPoint > &keypoints, cv::Mat &descriptors,
const double phi, const double tilt) const {
// apply the affine transformation to the image on the basis of the given parameters
cv::Mat image(src_image.clone());
cv::Matx23f affine;
warpImage(image, affine, phi, tilt);
// if keypoints are not provided, first apply the affine transformation to the mask
cv::Mat mask(src_mask.empty() ? cv::Mat(src_image.size(), CV_8UC1, 255) : src_mask.clone());
warpMask(mask, affine, image.size());
// detect keypoints on the skewed image and mask
// and extract descriptors on the image and keypoints
if (detector_ == extractor_) {
CV_Assert(detector_);
detector_->detectAndCompute(image, mask, keypoints, descriptors, false);
} else {
CV_Assert(detector_);
CV_Assert(extractor_);
detector_->detect(image, keypoints, mask);
extractor_->compute(image, keypoints, descriptors);
}
// invert the positions of the detected keypoints
invertKeypoints(keypoints, affine);
}
static void warpImage(cv::Mat &image, cv::Matx23f &affine, const double phi, const double tilt) {
// initiate output
affine = cv::Matx23f::eye();
if (phi != 0.) {
// rotate the source frame
affine = cv::getRotationMatrix2D(cv::Point2f(0., 0.), phi, 1.);
cv::Rect tmp_rect;
{
std::vector< cv::Point2f > corners(4);
corners[0] = cv::Point2f(0., 0.);
corners[1] = cv::Point2f(image.cols, 0.);
corners[2] = cv::Point2f(image.cols, image.rows);
corners[3] = cv::Point2f(0., image.rows);
std::vector< cv::Point2f > tmp_corners;
cv::transform(corners, tmp_corners, affine);
tmp_rect = cv::boundingRect(tmp_corners);
}
// cancel the offset of the rotated frame
affine(0, 2) = -tmp_rect.x;
affine(1, 2) = -tmp_rect.y;
// apply the final transformation to the image
cv::warpAffine(image, image, affine, tmp_rect.size(), cv::INTER_LINEAR, cv::BORDER_REPLICATE);
}
if (tilt != 1.) {
// shrink the image in width
cv::GaussianBlur(image, image, cv::Size(0, 0), 0.8 * std::sqrt(tilt * tilt - 1.), 0.01);
cv::resize(image, image, cv::Size(0, 0), 1. / tilt, 1., cv::INTER_NEAREST);
affine(0, 0) /= tilt;
affine(0, 1) /= tilt;
affine(0, 2) /= tilt;
}
}
static void warpMask(cv::Mat &mask, const cv::Matx23f &affine, const cv::Size size) {
if (affine == cv::Matx23f::eye()) {
return;
}
cv::warpAffine(mask, mask, affine, size, cv::INTER_NEAREST);
}
static void transformKeypoints(std::vector< cv::KeyPoint > &keypoints,
const cv::Matx23f &affine) {
if (affine == cv::Matx23f::eye()) {
return;
}
for (std::vector< cv::KeyPoint >::iterator keypoint = keypoints.begin();
keypoint != keypoints.end(); ++keypoint) {
// convert cv::Point2f to cv::Mat (1x1,2ch) without copying data.
// this is required because cv::transform does not accept cv::Point2f.
cv::Mat pt(cv::Mat(keypoint->pt, false).reshape(2));
cv::transform(pt, pt, affine);
}
}
static void invertKeypoints(std::vector< cv::KeyPoint > &keypoints, const cv::Matx23f &affine) {
if (affine == cv::Matx23f::eye()) {
return;
}
cv::Matx23f invert_affine;
cv::invertAffineTransform(affine, invert_affine);
transformKeypoints(keypoints, invert_affine);
}
static void extendKeypoints(const std::vector< std::vector< cv::KeyPoint > > &src,
std::vector< cv::KeyPoint > &dst) {
dst.clear();
for (std::size_t i = 0; i < src.size(); ++i) {
dst.insert(dst.end(), src[i].begin(), src[i].end());
}
}
void extendDescriptors(const std::vector< cv::Mat > &src, cv::OutputArray dst) const {
// create the output array
int nrows(0);
for (std::size_t i = 0; i < src.size(); ++i) {
nrows += src[i].rows;
}
dst.create(nrows, descriptorSize(), descriptorType());
// fill the output array
cv::Mat dst_mat(dst.getMat());
int rows(0);
for (std::size_t i = 0; i < src.size(); ++i) {
src[i].copyTo(dst_mat.rowRange(rows, rows + src[i].rows));
rows += src[i].rows;
}
}
protected:
std::vector< double > phi_params_;
std::vector< double > tilt_params_;
std::size_t ntasks_;
const double nstripes_;
};
}
#endif
|
#ifndef AFFINE_INVARIANT_FEATURES_AFFINE_INVARIANT_FEATURE
#define AFFINE_INVARIANT_FEATURES_AFFINE_INVARIANT_FEATURE
#include <algorithm>
#include <vector>
#include <affine_invariant_features/affine_invariant_feature_base.hpp>
#include <affine_invariant_features/parallel_tasks.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/imgproc.hpp>
namespace affine_invariant_features {
//
// AffineInvariantFeature that samples features in various affine transformation space
//
class AffineInvariantFeature : public AffineInvariantFeatureBase {
protected:
// the private constructor. users must use create() to instantiate an AffineInvariantFeature
AffineInvariantFeature(const cv::Ptr< cv::Feature2D > detector,
const cv::Ptr< cv::Feature2D > extractor, const double nstripes)
: AffineInvariantFeatureBase(detector, extractor), nstripes_(nstripes) {
// generate parameters for affine invariant sampling
phi_params_.push_back(0.);
tilt_params_.push_back(1.);
for (int i = 1; i < 6; ++i) {
const double tilt(std::pow(2., 0.5 * i));
for (double phi = 0.; phi < 180.; phi += 72. / tilt) {
phi_params_.push_back(phi);
tilt_params_.push_back(tilt);
}
}
ntasks_ = phi_params_.size();
}
public:
virtual ~AffineInvariantFeature() {}
//
// unique interfaces to instantiate an AffineInvariantFeature
//
static cv::Ptr< AffineInvariantFeature > create(const cv::Ptr< cv::Feature2D > feature,
const double nstripes = -1.) {
return new AffineInvariantFeature(feature, feature, nstripes);
}
static cv::Ptr< AffineInvariantFeature > create(const cv::Ptr< cv::Feature2D > detector,
const cv::Ptr< cv::Feature2D > extractor,
const double nstripes = -1.) {
return new AffineInvariantFeature(detector, extractor, nstripes);
}
//
// overloaded functions from AffineInvariantFeatureBase or its base class
//
virtual void compute(cv::InputArray image, std::vector< cv::KeyPoint > &keypoints,
cv::OutputArray descriptors) {
// extract the input
const cv::Mat image_mat(image.getMat());
// prepare outputs of following parallel processing
std::vector< std::vector< cv::KeyPoint > > keypoints_array(ntasks_, keypoints);
std::vector< cv::Mat > descriptors_array(ntasks_);
// bind each parallel task and arguments
ParallelTasks tasks(ntasks_);
for (std::size_t i = 0; i < ntasks_; ++i) {
tasks[i] = boost::bind(&AffineInvariantFeature::computeTask, this, boost::ref(image_mat),
boost::ref(keypoints_array[i]), boost::ref(descriptors_array[i]),
phi_params_[i], tilt_params_[i]);
}
// do parallel tasks
cv::parallel_for_(cv::Range(0, ntasks_), tasks, nstripes_);
// fill the final outputs
extendKeypoints(keypoints_array, keypoints);
extendDescriptors(descriptors_array, descriptors);
}
virtual void detect(cv::InputArray image, std::vector< cv::KeyPoint > &keypoints,
cv::InputArray mask = cv::noArray()) {
// extract inputs
const cv::Mat image_mat(image.getMat());
const cv::Mat mask_mat(mask.getMat());
// prepare an output of following parallel processing
std::vector< std::vector< cv::KeyPoint > > keypoints_array(ntasks_);
// bind each parallel task and arguments
ParallelTasks tasks(ntasks_);
for (std::size_t i = 0; i < ntasks_; ++i) {
tasks[i] = boost::bind(&AffineInvariantFeature::detectTask, this, boost::ref(image_mat),
boost::ref(mask_mat), boost::ref(keypoints_array[i]), phi_params_[i],
tilt_params_[i]);
}
// do parallel tasks
cv::parallel_for_(cv::Range(0, ntasks_), tasks, nstripes_);
// fill the final output
extendKeypoints(keypoints_array, keypoints);
}
virtual void detectAndCompute(cv::InputArray image, cv::InputArray mask,
std::vector< cv::KeyPoint > &keypoints, cv::OutputArray descriptors,
bool useProvidedKeypoints = false) {
// just compute descriptors if the keypoints are provided
if (useProvidedKeypoints) {
compute(image, keypoints, descriptors);
return;
}
// extract inputs
const cv::Mat image_mat(image.getMat());
const cv::Mat mask_mat(mask.getMat());
// prepare outputs of following parallel processing
std::vector< std::vector< cv::KeyPoint > > keypoints_array(ntasks_);
std::vector< cv::Mat > descriptors_array(ntasks_);
// bind each parallel task and arguments
ParallelTasks tasks(ntasks_);
for (std::size_t i = 0; i < ntasks_; ++i) {
tasks[i] =
boost::bind(&AffineInvariantFeature::detectAndComputeTask, this, boost::ref(image_mat),
boost::ref(mask_mat), boost::ref(keypoints_array[i]),
boost::ref(descriptors_array[i]), phi_params_[i], tilt_params_[i]);
}
// do parallel tasks
cv::parallel_for_(cv::Range(0, ntasks_), tasks, nstripes_);
// fill the final outputs
extendKeypoints(keypoints_array, keypoints);
extendDescriptors(descriptors_array, descriptors);
}
virtual cv::String getDefaultName() const { return "AffineInvariantFeature"; }
protected:
void computeTask(const cv::Mat &src_image, std::vector< cv::KeyPoint > &keypoints,
cv::Mat &descriptors, const double phi, const double tilt) const {
// apply the affine transformation to the image on the basis of the given parameters
cv::Mat image(src_image.clone());
cv::Matx23f affine;
warpImage(image, affine, phi, tilt);
// apply the affine transformation to keypoints
transformKeypoints(keypoints, affine);
// extract descriptors on the skewed image and keypoints
CV_Assert(extractor_);
extractor_->compute(image, keypoints, descriptors);
// invert keypoints
invertKeypoints(keypoints, affine);
}
void detectTask(const cv::Mat &src_image, const cv::Mat &src_mask,
std::vector< cv::KeyPoint > &keypoints, const double phi,
const double tilt) const {
// apply the affine transformation to the image on the basis of the given parameters
cv::Mat image(src_image.clone());
cv::Matx23f affine;
warpImage(image, affine, phi, tilt);
// apply the affine transformation to the mask
cv::Mat mask(src_mask.empty() ? cv::Mat(src_image.size(), CV_8UC1, 255) : src_mask.clone());
warpMask(mask, affine, image.size());
// detect keypoints on the skewed image and mask
CV_Assert(detector_);
detector_->detect(image, keypoints, mask);
// invert keypoints
invertKeypoints(keypoints, affine);
}
void detectAndComputeTask(const cv::Mat &src_image, const cv::Mat &src_mask,
std::vector< cv::KeyPoint > &keypoints, cv::Mat &descriptors,
const double phi, const double tilt) const {
// apply the affine transformation to the image on the basis of the given parameters
cv::Mat image(src_image.clone());
cv::Matx23f affine;
warpImage(image, affine, phi, tilt);
// if keypoints are not provided, first apply the affine transformation to the mask
cv::Mat mask(src_mask.empty() ? cv::Mat(src_image.size(), CV_8UC1, 255) : src_mask.clone());
warpMask(mask, affine, image.size());
// detect keypoints on the skewed image and mask
// and extract descriptors on the image and keypoints
if (detector_ == extractor_) {
CV_Assert(detector_);
detector_->detectAndCompute(image, mask, keypoints, descriptors, false);
} else {
CV_Assert(detector_);
CV_Assert(extractor_);
detector_->detect(image, keypoints, mask);
extractor_->compute(image, keypoints, descriptors);
}
// invert the positions of the detected keypoints
invertKeypoints(keypoints, affine);
}
static void warpImage(cv::Mat &image, cv::Matx23f &affine, const double phi, const double tilt) {
// initiate output
affine = cv::Matx23f::eye();
if (phi != 0.) {
// rotate the source frame
affine = cv::getRotationMatrix2D(cv::Point2f(0., 0.), phi, 1.);
cv::Rect tmp_rect;
{
std::vector< cv::Point2f > corners(4);
corners[0] = cv::Point2f(0., 0.);
corners[1] = cv::Point2f(image.cols, 0.);
corners[2] = cv::Point2f(image.cols, image.rows);
corners[3] = cv::Point2f(0., image.rows);
std::vector< cv::Point2f > tmp_corners;
cv::transform(corners, tmp_corners, affine);
tmp_rect = cv::boundingRect(tmp_corners);
}
// cancel the offset of the rotated frame
affine(0, 2) = -tmp_rect.x;
affine(1, 2) = -tmp_rect.y;
// apply the final transformation to the image
cv::warpAffine(image, image, affine, tmp_rect.size(), cv::INTER_LINEAR, cv::BORDER_REPLICATE);
}
if (tilt != 1.) {
// shrink the image in width
cv::GaussianBlur(image, image, cv::Size(0, 0), 0.8 * std::sqrt(tilt * tilt - 1.), 0.01);
cv::resize(image, image, cv::Size(0, 0), 1. / tilt, 1., cv::INTER_NEAREST);
affine(0, 0) /= tilt;
affine(0, 1) /= tilt;
affine(0, 2) /= tilt;
}
}
static void warpMask(cv::Mat &mask, const cv::Matx23f &affine, const cv::Size size) {
if (affine == cv::Matx23f::eye()) {
return;
}
cv::warpAffine(mask, mask, affine, size, cv::INTER_NEAREST);
}
static void transformKeypoints(std::vector< cv::KeyPoint > &keypoints,
const cv::Matx23f &affine) {
if (affine == cv::Matx23f::eye()) {
return;
}
for (std::vector< cv::KeyPoint >::iterator keypoint = keypoints.begin();
keypoint != keypoints.end(); ++keypoint) {
// convert cv::Point2f to cv::Mat (1x1,2ch) without copying data.
// this is required because cv::transform does not accept cv::Point2f.
cv::Mat pt(cv::Mat(keypoint->pt, false).reshape(2));
cv::transform(pt, pt, affine);
}
}
static void invertKeypoints(std::vector< cv::KeyPoint > &keypoints, const cv::Matx23f &affine) {
if (affine == cv::Matx23f::eye()) {
return;
}
cv::Matx23f invert_affine;
cv::invertAffineTransform(affine, invert_affine);
transformKeypoints(keypoints, invert_affine);
}
static void extendKeypoints(const std::vector< std::vector< cv::KeyPoint > > &src,
std::vector< cv::KeyPoint > &dst) {
dst.clear();
for (std::size_t i = 0; i < src.size(); ++i) {
dst.insert(dst.end(), src[i].begin(), src[i].end());
}
}
void extendDescriptors(const std::vector< cv::Mat > &src, cv::OutputArray dst) const {
// create the output array
int nrows(0);
for (std::size_t i = 0; i < src.size(); ++i) {
nrows += src[i].rows;
}
dst.create(nrows, descriptorSize(), descriptorType());
// fill the output array
cv::Mat dst_mat(dst.getMat());
int rows(0);
for (std::size_t i = 0; i < src.size(); ++i) {
if (src[i].rows > 0) {
src[i].copyTo(dst_mat.rowRange(rows, rows + src[i].rows));
rows += src[i].rows;
}
}
}
protected:
std::vector< double > phi_params_;
std::vector< double > tilt_params_;
std::size_t ntasks_;
const double nstripes_;
};
} // namespace affine_invariant_features
#endif
|
fix crash with invalid matrix creation
|
fix crash with invalid matrix creation
|
C++
|
mit
|
yoshito-n-students/affine_invariant_features
|
645418941703881292ee429ac71c98aa0b202615
|
components/susi-authenticator/sources/Authenticator.cpp
|
components/susi-authenticator/sources/Authenticator.cpp
|
#include "susi/Authenticator.h"
Authenticator::Authenticator(std::string addr,short port, std::string key, std::string cert) :
susi_{new Susi::SusiClient{addr,port,key,cert}} {
load();
susi_->registerProcessor("authenticator::login",[this](Susi::EventPtr event){
login(std::move(event));
});
susi_->registerProcessor("authenticator::logout",[this](Susi::EventPtr event){
logout(std::move(event));
});
susi_->registerProcessor("authenticator::users::add",[this](Susi::EventPtr event){
addUser(std::move(event));
});
susi_->registerProcessor("authenticator::users::delete",[this](Susi::EventPtr event){
delUser(std::move(event));
});
susi_->registerProcessor("authenticator::users::get",[this](Susi::EventPtr event){
getUsers(std::move(event));
});
}
void Authenticator::login(Susi::EventPtr event){
auto name = event->payload["username"].getString();
// check username and password
if(usersByName.count(name) == 0){
throw std::runtime_error{"no such user"};
}
auto & user = usersByName[name];
if(!BCrypt::validatePassword(event->payload["password"].getString(),user->pwHash)){
std::this_thread::sleep_for(std::chrono::milliseconds{100}); //this is agains brute forcers
throw std::runtime_error{"wrong password"};
}
user->token = generateToken();
event->payload["token"] = user->token;
usersByToken[user->token] = user;
// prevent arbitary consumers from reading sensitive data
event->headers.push_back({"Event-Control","No-Consumer"});
susi_->ack(std::move(event));
}
void Authenticator::logout(Susi::EventPtr event){
std::string token = getTokenFromEvent(event);
auto & user = usersByToken[token];
user->token = "";
usersByToken.erase(user->token);
event->headers.push_back({"Event-Control","No-Consumer"});
susi_->ack(std::move(event));
}
void Authenticator::addUser(Susi::EventPtr event){
std::string username = event->payload["username"];
std::string password = event->payload["password"];
auto roles = event->payload["roles"];
auto user = std::make_shared<User>();
user->name = username;
user->pwHash = BCrypt::generateHash(password);
for(size_t i=0;i<roles.size();i++){
user->roles.emplace_back(roles[i].getString());
}
addUser(user);
save();
event->payload = true;
}
void Authenticator::delUser(Susi::EventPtr event){
std::string username = event->payload["username"];
auto user = usersByName[username];
usersByName.erase(username);
usersByToken.erase(user->token);
event->payload = true;
}
void Authenticator::getUsers(Susi::EventPtr event){
BSON::Array resultData;
for(auto & kv : usersByName){
auto & user = kv.second;
resultData.push_back(BSON::Object{
{"username",user->name},
{"roles",BSON::Array{user->roles.begin(),user->roles.end()}}
});
}
event->payload = resultData;
}
void Authenticator::addPermission(Susi::EventPtr event){
}
void Authenticator::delPermission(Susi::EventPtr event){
}
void Authenticator::getPermissions(Susi::EventPtr event){
}
void Authenticator::addUser(std::shared_ptr<User> user){
usersByName[user->name] = user;
}
void Authenticator::addPermission(Permission permission){
permissionsByTopic[permission.pattern.topic] = permission;
}
void Authenticator::load(){
auto userRequestEvent = susi_->createEvent("state::get");
userRequestEvent->payload["key"] = "authenticator::users";
susi_->publish(std::move(userRequestEvent),[this](Susi::SharedEventPtr event){
auto & users = event->payload["value"];
if(!users.isArray() || users.size()==0){
auto user = std::make_shared<User>();
user->name = "root";
user->pwHash = BCrypt::generateHash("toor");
user->roles.push_back("admin");
addUser(user);
save();
}else for(size_t i=0;i<users.size();i++){
auto & user = users[i];
auto u = std::shared_ptr<User>{ new User{
.name = user["name"].getString(),
.pwHash = user["pwHash"].getString(),
.token = ""
}};
for(size_t j=0;j<user["roles"].size();j++){
u->roles.push_back(user["roles"][j].getString());
}
addUser(u);
}
});
auto permissionRequestEvent = susi_->createEvent("state::get");
permissionRequestEvent->payload["key"] = "authenticator::permissions";
susi_->publish(std::move(permissionRequestEvent),[this](Susi::SharedEventPtr event){
auto & permissions = event->payload["value"];
if(permissions.isArray()){
for(size_t i=0;i<permissions.size();i++){
auto & permission = permissions[i];
Permission p = {
.pattern = Susi::Event{permission["pattern"]}
};
for(size_t j=0;j<permission["roles"].size();j++){
p.roles.push_back(permission["roles"][j].getString());
}
addPermission(p);
}
}
});
}
void Authenticator::save(){
BSON::Array userArray;
for(auto & kv : usersByName){
auto & user = kv.second;
userArray.push_back(BSON::Object{
{"name",user->name},
{"pwHash",user->pwHash},
{"roles",BSON::Array{
user->roles.begin(),
user->roles.end()
}}
});
}
auto userSaveEvent = susi_->createEvent("state::put");
userSaveEvent->payload["key"] = "authenticator::users";
userSaveEvent->payload["value"] = userArray;
susi_->publish(std::move(userSaveEvent));
BSON::Array permissionArray;
for(auto & kv : permissionsByTopic){
auto & permission = kv.second;
permissionArray.push_back(BSON::Object{
{"pattern",permission.pattern.toAny()},
{"roles",BSON::Array{
permission.roles.begin(),
permission.roles.end()
}}
});
}
auto permissionSaveEvent = susi_->createEvent("state::put");
permissionSaveEvent->payload["key"] = "authenticator::permissions";
permissionSaveEvent->payload["value"] = userArray;
susi_->publish(std::move(permissionSaveEvent));
}
void Authenticator::join(){
susi_->join();
}
std::string Authenticator::generateToken(){
std::string token;
size_t len = 64;
token.reserve(len);
static const std::string alphanums =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
static std::mt19937 rg(std::chrono::system_clock::now().time_since_epoch().count());
static std::uniform_int_distribution<> pick(0, alphanums.size() - 1);
for (int i = 0; i < len; ++i) {
token += alphanums[pick(rg)];
}
return token;
}
std::string Authenticator::getTokenFromEvent(const Susi::EventPtr & event){
for(const auto & header : event->headers){
if(header.first == "authenticator::token"){
return header.second;
}
}
return "";
}
bool Authenticator::checkIfPayloadMatchesPattern(BSON::Value pattern, BSON::Value payload){
if(pattern.getType() != payload.getType()){
return false;
}
switch(pattern.getType()){
case BSON::UNDEFINED:
case BSON::INT32:
case BSON::INT64:
case BSON::DOUBLE:
case BSON::BOOL:
case BSON::DATETIME: {
return pattern == payload;
}
case BSON::STRING:
case BSON::BINARY: {
std::regex r{pattern.getString()};
return std::regex_match(payload.getString(),r);
}
case BSON::OBJECT: {
for(auto & kv : pattern.getObject()){
if(!checkIfPayloadMatchesPattern(kv.second,payload[kv.first])){
return false;
}
}
return true;
}
case BSON::ARRAY: {
if(pattern.size() != payload.size()){
return false;
}
for(size_t i=0;i<pattern.size();i++){
if(!checkIfPayloadMatchesPattern(pattern[i],payload[i])){
return false;
}
}
return true;
}
}
return false;
}
void Authenticator::registerGuard(Permission permission){
susi_->registerProcessor(permission.pattern.topic,[permission,this](Susi::EventPtr event){
if(checkIfPayloadMatchesPattern(permission.pattern.payload,event->payload)){
std::string token = getTokenFromEvent(event);
if(!usersByToken.count(token)){
susi_->dismiss(std::move(event));
}else{
auto & u = usersByToken[token];
for(auto & userRole : u->roles){
for(auto & permissionRole: permission.roles){
if(userRole == permissionRole){
susi_->ack(std::move(event));
return;
}
}
}
susi_->dismiss(std::move(event));
}
}
});
}
|
#include "susi/Authenticator.h"
Authenticator::Authenticator(std::string addr,short port, std::string key, std::string cert) :
susi_{new Susi::SusiClient{addr,port,key,cert}} {
load();
susi_->registerProcessor("authenticator::login",[this](Susi::EventPtr event){
login(std::move(event));
});
susi_->registerProcessor("authenticator::logout",[this](Susi::EventPtr event){
logout(std::move(event));
});
susi_->registerProcessor("authenticator::users::add",[this](Susi::EventPtr event){
addUser(std::move(event));
});
susi_->registerProcessor("authenticator::users::delete",[this](Susi::EventPtr event){
delUser(std::move(event));
});
susi_->registerProcessor("authenticator::users::get",[this](Susi::EventPtr event){
getUsers(std::move(event));
});
}
void Authenticator::login(Susi::EventPtr event){
auto name = event->payload["username"].getString();
// check username and password
if(usersByName.count(name) == 0){
throw std::runtime_error{"no such user"};
}
auto & user = usersByName[name];
if(!BCrypt::validatePassword(event->payload["password"].getString(),user->pwHash)){
std::this_thread::sleep_for(std::chrono::milliseconds{100}); //this is agains brute forcers
throw std::runtime_error{"wrong password"};
}
user->token = generateToken();
event->payload["token"] = user->token;
usersByToken[user->token] = user;
// prevent arbitary consumers from reading sensitive data
event->headers.push_back({"Event-Control","No-Consumer"});
susi_->ack(std::move(event));
}
void Authenticator::logout(Susi::EventPtr event){
std::string token = getTokenFromEvent(event);
auto & user = usersByToken[token];
user->token = "";
usersByToken.erase(user->token);
event->headers.push_back({"Event-Control","No-Consumer"});
susi_->ack(std::move(event));
}
void Authenticator::addUser(Susi::EventPtr event){
std::string username = event->payload["username"];
std::string password = event->payload["password"];
auto roles = event->payload["roles"];
auto user = std::make_shared<User>();
user->name = username;
user->pwHash = BCrypt::generateHash(password);
for(size_t i=0;i<roles.size();i++){
user->roles.emplace_back(roles[i].getString());
}
addUser(user);
save();
event->payload = true;
}
void Authenticator::delUser(Susi::EventPtr event){
std::string username = event->payload["username"];
auto user = usersByName[username];
usersByName.erase(username);
usersByToken.erase(user->token);
event->payload = true;
}
void Authenticator::getUsers(Susi::EventPtr event){
BSON::Array resultData;
for(auto & kv : usersByName){
auto & user = kv.second;
resultData.push_back(BSON::Object{
{"username",user->name},
{"roles",BSON::Array{user->roles.begin(),user->roles.end()}}
});
}
event->payload = resultData;
}
void Authenticator::addPermission(Susi::EventPtr event){
auto & pattern = event->payload["pattern"];
auto roles = event->payload["roles"];
std::string topic = pattern["topic"].getString();
BSON::Value & payload = pattern["payload"];
Susi::Event evt;
evt.topic = topic;
evt.payload = payload;
Permission permission;
permission.pattern = evt;
std::vector<std::string> roleArray;
for(size_t i=0;i<roles.size();i++){
roleArray.emplace_back(roles[i].getString());
}
permission.roles = roleArray;
addPermission(permission);
}
void Authenticator::delPermission(Susi::EventPtr event){
}
void Authenticator::getPermissions(Susi::EventPtr event){
}
void Authenticator::addUser(std::shared_ptr<User> user){
usersByName[user->name] = user;
}
void Authenticator::addPermission(Permission permission){
permissionsByTopic[permission.pattern.topic] = permission;
}
void Authenticator::load(){
auto userRequestEvent = susi_->createEvent("state::get");
userRequestEvent->payload["key"] = "authenticator::users";
susi_->publish(std::move(userRequestEvent),[this](Susi::SharedEventPtr event){
auto & users = event->payload["value"];
if(!users.isArray() || users.size()==0){
auto user = std::make_shared<User>();
user->name = "root";
user->pwHash = BCrypt::generateHash("toor");
user->roles.push_back("admin");
addUser(user);
save();
}else for(size_t i=0;i<users.size();i++){
auto & user = users[i];
auto u = std::shared_ptr<User>{ new User{
.name = user["name"].getString(),
.pwHash = user["pwHash"].getString(),
.token = ""
}};
for(size_t j=0;j<user["roles"].size();j++){
u->roles.push_back(user["roles"][j].getString());
}
addUser(u);
}
});
auto permissionRequestEvent = susi_->createEvent("state::get");
permissionRequestEvent->payload["key"] = "authenticator::permissions";
susi_->publish(std::move(permissionRequestEvent),[this](Susi::SharedEventPtr event){
auto & permissions = event->payload["value"];
if(permissions.isArray()){
for(size_t i=0;i<permissions.size();i++){
auto & permission = permissions[i];
Permission p = {
.pattern = Susi::Event{permission["pattern"]}
};
for(size_t j=0;j<permission["roles"].size();j++){
p.roles.push_back(permission["roles"][j].getString());
}
addPermission(p);
}
}
});
}
void Authenticator::save(){
BSON::Array userArray;
for(auto & kv : usersByName){
auto & user = kv.second;
userArray.push_back(BSON::Object{
{"name",user->name},
{"pwHash",user->pwHash},
{"roles",BSON::Array{
user->roles.begin(),
user->roles.end()
}}
});
}
auto userSaveEvent = susi_->createEvent("state::put");
userSaveEvent->payload["key"] = "authenticator::users";
userSaveEvent->payload["value"] = userArray;
susi_->publish(std::move(userSaveEvent));
BSON::Array permissionArray;
for(auto & kv : permissionsByTopic){
auto & permission = kv.second;
permissionArray.push_back(BSON::Object{
{"pattern",permission.pattern.toAny()},
{"roles",BSON::Array{
permission.roles.begin(),
permission.roles.end()
}}
});
}
auto permissionSaveEvent = susi_->createEvent("state::put");
permissionSaveEvent->payload["key"] = "authenticator::permissions";
permissionSaveEvent->payload["value"] = userArray;
susi_->publish(std::move(permissionSaveEvent));
}
void Authenticator::join(){
susi_->join();
}
std::string Authenticator::generateToken(){
std::string token;
size_t len = 64;
token.reserve(len);
static const std::string alphanums =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
static std::mt19937 rg(std::chrono::system_clock::now().time_since_epoch().count());
static std::uniform_int_distribution<> pick(0, alphanums.size() - 1);
for (int i = 0; i < len; ++i) {
token += alphanums[pick(rg)];
}
return token;
}
std::string Authenticator::getTokenFromEvent(const Susi::EventPtr & event){
for(const auto & header : event->headers){
if(header.first == "User-Token"){
return header.second;
}
}
return "";
}
bool Authenticator::checkIfPayloadMatchesPattern(BSON::Value pattern, BSON::Value payload){
if(pattern.getType() != payload.getType()){
return false;
}
switch(pattern.getType()){
case BSON::UNDEFINED:
case BSON::INT32:
case BSON::INT64:
case BSON::DOUBLE:
case BSON::BOOL:
case BSON::DATETIME: {
return pattern == payload;
}
case BSON::STRING:
case BSON::BINARY: {
std::regex r{pattern.getString()};
return std::regex_match(payload.getString(),r);
}
case BSON::OBJECT: {
for(auto & kv : pattern.getObject()){
if(!checkIfPayloadMatchesPattern(kv.second,payload[kv.first])){
return false;
}
}
return true;
}
case BSON::ARRAY: {
if(pattern.size() != payload.size()){
return false;
}
for(size_t i=0;i<pattern.size();i++){
if(!checkIfPayloadMatchesPattern(pattern[i],payload[i])){
return false;
}
}
return true;
}
}
return false;
}
void Authenticator::registerGuard(Permission permission){
susi_->registerProcessor(permission.pattern.topic,[permission,this](Susi::EventPtr event){
if(checkIfPayloadMatchesPattern(permission.pattern.payload,event->payload)){
std::string token = getTokenFromEvent(event);
if(!usersByToken.count(token)){
susi_->dismiss(std::move(event));
}else{
auto & u = usersByToken[token];
for(auto & userRole : u->roles){
for(auto & permissionRole: permission.roles){
if(userRole == permissionRole){
susi_->ack(std::move(event));
return;
}
}
}
susi_->dismiss(std::move(event));
}
}
});
}
|
add permissions is now possible;
|
[auth] add permissions is now possible;
|
C++
|
mit
|
webvariants/susi,webvariants/susi,webvariants/susi,webvariants/susi
|
1197fb9c2a3064d2e5a163e629a9c0eaebaa04e2
|
modules/vectorfieldvisualization/processors/3d/streamlines.cpp
|
modules/vectorfieldvisualization/processors/3d/streamlines.cpp
|
#include "streamlines.h"
#include <inviwo/core/datastructures/buffer/buffer.h>
#include <inviwo/core/datastructures/buffer/bufferramprecision.h>
#include <inviwo/core/datastructures/geometry/basicmesh.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <inviwo/core/datastructures/volume/volumeram.h>
#include <modules/opengl/image/layergl.h>
#include <bitset>
#include <inviwo/core/util/imagesampler.h>
namespace inviwo {
const ProcessorInfo StreamLines::processorInfo_{
"org.inviwo.StreamLines", // Class identifier
"Stream Lines", // Display name
"Vector Field Visualization", // Category
CodeState::Experimental, // Code state
Tags::CPU, // Tags
};
const ProcessorInfo StreamLines::getProcessorInfo() const { return processorInfo_; }
StreamLines::StreamLines()
: Processor()
, sampler_("sampler")
, seedPoints_("seedpoints")
, linesStripsMesh_("linesStripsMesh_")
, streamLineProperties_("streamLineProperties", "Stream Line Properties")
, tf_("transferFunction", "Transfer Function")
, velocityScale_("velocityScale_", "Velocity Scale (inverse)", 1, 0, 10)
, maxVelocity_("minMaxVelocity", "Velocity Range", "0", InvalidationLevel::Valid) {
addPort(sampler_);
addPort(seedPoints_);
addPort(linesStripsMesh_);
maxVelocity_.setReadOnly(true);
addProperty(streamLineProperties_);
addProperty(tf_);
addProperty(velocityScale_);
addProperty(maxVelocity_);
tf_.get().clearPoints();
tf_.get().addPoint(vec2(0, 1), vec4(0, 0, 1, 1));
tf_.get().addPoint(vec2(0.5, 1), vec4(1, 1, 0, 1));
tf_.get().addPoint(vec2(1, 1), vec4(1, 0, 0, 1));
setAllPropertiesCurrentStateAsDefault();
}
StreamLines::~StreamLines() {}
void StreamLines::process() {
auto mesh = std::make_shared<BasicMesh>();
//mesh->setModelMatrix(sampler_.getData()->getModelMatrix());
mesh->setWorldMatrix(sampler_.getData()->getWorldMatrix());
auto m = streamLineProperties_.getSeedPointTransformationMatrix(
sampler_.getData()->getCoordinateTransformer());
ImageSampler tf(tf_.get().getData());
float maxVelocity = 0;
StreamLineTracer tracer(sampler_.getData(), streamLineProperties_);
std::vector<BasicMesh::Vertex> vertices;
for (const auto &seeds : seedPoints_) {
for (auto &p : (*seeds)) {
vec4 P = m * vec4(p, 1.0f);
auto line = tracer.traceFrom(P.xyz());
auto position = line.getPositions().begin();
auto velocity = line.getMetaData("velocity").begin();
auto size = line.getPositions().size();
if (size == 0) continue;
auto indexBuffer =
mesh->addIndexBuffer(DrawType::Lines, ConnectivityType::StripAdjacency);
indexBuffer->add(0);
for (size_t i = 0; i < size; i++) {
vec3 pos(*position);
vec3 v(*velocity);
float l = glm::length(vec3(*velocity));
float d = glm::clamp(l / velocityScale_.get(), 0.0f, 1.0f);
maxVelocity = std::max(maxVelocity, l);
auto c = vec4(tf.sample(dvec2(d, 0.0)));
indexBuffer->add(static_cast<std::uint32_t>(vertices.size()));
vertices.push_back({pos, glm::normalize(v), pos, c});
position++;
velocity++;
}
indexBuffer->add(static_cast<std::uint32_t>(vertices.size() - 1));
}
}
mesh->addVertices(vertices);
linesStripsMesh_.setData(mesh);
maxVelocity_.set(toString(maxVelocity));
}
} // namespace
|
#include "streamlines.h"
#include <inviwo/core/datastructures/buffer/buffer.h>
#include <inviwo/core/datastructures/buffer/bufferramprecision.h>
#include <inviwo/core/datastructures/geometry/basicmesh.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <inviwo/core/datastructures/volume/volumeram.h>
#include <modules/opengl/image/layergl.h>
#include <bitset>
#include <inviwo/core/util/imagesampler.h>
namespace inviwo {
const ProcessorInfo StreamLines::processorInfo_{
"org.inviwo.StreamLines", // Class identifier
"Stream Lines", // Display name
"Vector Field Visualization", // Category
CodeState::Experimental, // Code state
Tags::CPU, // Tags
};
const ProcessorInfo StreamLines::getProcessorInfo() const { return processorInfo_; }
StreamLines::StreamLines()
: Processor()
, sampler_("sampler")
, seedPoints_("seedpoints")
, linesStripsMesh_("linesStripsMesh_")
, streamLineProperties_("streamLineProperties", "Stream Line Properties")
, tf_("transferFunction", "Transfer Function")
, velocityScale_("velocityScale_", "Velocity Scale (inverse)", 1, 0, 10)
, maxVelocity_("minMaxVelocity", "Velocity Range", "0", InvalidationLevel::Valid) {
addPort(sampler_);
addPort(seedPoints_);
addPort(linesStripsMesh_);
maxVelocity_.setReadOnly(true);
addProperty(streamLineProperties_);
addProperty(tf_);
addProperty(velocityScale_);
addProperty(maxVelocity_);
tf_.get().clearPoints();
tf_.get().addPoint(vec2(0, 1), vec4(0, 0, 1, 1));
tf_.get().addPoint(vec2(0.5, 1), vec4(1, 1, 0, 1));
tf_.get().addPoint(vec2(1, 1), vec4(1, 0, 0, 1));
setAllPropertiesCurrentStateAsDefault();
}
StreamLines::~StreamLines() {}
void StreamLines::process() {
auto mesh = std::make_shared<BasicMesh>();
mesh->setModelMatrix(sampler_.getData()->getModelMatrix());
mesh->setWorldMatrix(sampler_.getData()->getWorldMatrix());
auto m = streamLineProperties_.getSeedPointTransformationMatrix(
sampler_.getData()->getCoordinateTransformer());
ImageSampler tf(tf_.get().getData());
float maxVelocity = 0;
StreamLineTracer tracer(sampler_.getData(), streamLineProperties_);
std::vector<BasicMesh::Vertex> vertices;
for (const auto &seeds : seedPoints_) {
for (auto &p : (*seeds)) {
vec4 P = m * vec4(p, 1.0f);
auto line = tracer.traceFrom(P.xyz());
auto position = line.getPositions().begin();
auto velocity = line.getMetaData("velocity").begin();
auto size = line.getPositions().size();
if (size == 0) continue;
auto indexBuffer =
mesh->addIndexBuffer(DrawType::Lines, ConnectivityType::StripAdjacency);
indexBuffer->add(0);
for (size_t i = 0; i < size; i++) {
vec3 pos(*position);
vec3 v(*velocity);
float l = glm::length(vec3(*velocity));
float d = glm::clamp(l / velocityScale_.get(), 0.0f, 1.0f);
maxVelocity = std::max(maxVelocity, l);
auto c = vec4(tf.sample(dvec2(d, 0.0)));
indexBuffer->add(static_cast<std::uint32_t>(vertices.size()));
vertices.push_back({pos, glm::normalize(v), pos, c});
position++;
velocity++;
}
indexBuffer->add(static_cast<std::uint32_t>(vertices.size() - 1));
}
}
mesh->addVertices(vertices);
linesStripsMesh_.setData(mesh);
maxVelocity_.set(toString(maxVelocity));
}
} // namespace
|
Revert of unwanted commit
|
VectorVis: Revert of unwanted commit
|
C++
|
bsd-2-clause
|
inviwo/inviwo,inviwo/inviwo,Sparkier/inviwo,inviwo/inviwo,inviwo/inviwo,Sparkier/inviwo,Sparkier/inviwo,Sparkier/inviwo,Sparkier/inviwo,inviwo/inviwo,inviwo/inviwo
|
0eee39dd21b431ef90d37b9a8159c044be66d436
|
source/collision/WorldCollision.cpp
|
source/collision/WorldCollision.cpp
|
/*
* Copyright (c) 2006, Ondrej Danek (www.ondrej-danek.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.
* * 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 Ondrej Danek 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 "WorldCollision.h"
#include "../Rectangle.h"
namespace Duel6 {
//TODO Duplicity
static const float GRAVITATIONAL_ACCELERATION = -11.0f;
void CollidingEntity::collideWithElevators(ElevatorList & elevators, Float32 elapsedTime, Float32 speed) {
elevator = elevators.checkCollider(*this, elapsedTime * speed);
if(elevator != nullptr) {
position.y = elevator->getPosition().y;
position += elevator->getVelocity() * elapsedTime;
velocity.y = 0.0f;
if(isInWall()) {
velocity.x = 0.0f;
}
}
}
void CollidingEntity::collideWithLevel(const Level & level, Float32 elapsedTime, Float32 speed) {
static bool bleft = false, bright = false, bup = false, bdown = false;
{
Float32 delta = 0.8f * VERTICAL_DELTA;
Float32 down = position.y - FLOOR_DISTANCE_THRESHOLD;
Float32 left = position.x + delta;
Float32 right = position.x + (1 - delta);
lastCollisionCheck.onGround = level.isWall(left, down, true) || level.isWall(right, down, true);
}
{
Float32 delta = VERTICAL_DELTA;
Float32 up = position.y + DELTA_HEIGHT;
Float32 left = position.x + delta;
Float32 right = position.x + (1.0f - delta);
lastCollisionCheck.clearForJump = !level.isWall(left, up, true) && !level.isWall(right, up, true);
}
lastCollisionCheck.inWall = level.isWall(Int32(getCollisionRect().getCentre().x), Int32(getCollisionRect().getCentre().y), true);
if (!isOnElevator()) {
velocity.y += GRAVITATIONAL_ACCELERATION * elapsedTime; // gravity
}
if (!isOnGround()) {
if (velocity.y < -D6_PLAYER_JUMP_SPEED) {
velocity.y = -D6_PLAYER_JUMP_SPEED;
}
}
externalForcesSpeed += externalForces;
externalForces.x = 0;
externalForces.y = 0;
if (externalForcesSpeed.length() < 0.01) {
externalForcesSpeed.x = 0;
externalForcesSpeed.y = 0;
}
//friction
if(velocity.x > 0.0f) {
acceleration.x -= std::min(elapsedTime, velocity.x);
}
if(velocity.x < 0.0f) {
acceleration.x += std::min(elapsedTime, std::abs(velocity.x));
}
//do not multiply by speed or elapsedTime !!!
velocity += acceleration;
acceleration.x = 0;
acceleration.y = 0;
// horizontal speed clamping
if (std::abs(velocity.x * speed) > 0.5f) {
velocity.x = std::copysign(0.5f, this->velocity.x) / speed;
}
if (std::abs(externalForcesSpeed.x * speed) > 0.5f) {
externalForcesSpeed.x = std::copysign(0.5f, externalForcesSpeed.x) / speed;
}
Vector totalSpeed = velocity + externalForcesSpeed;
bleft = false, bright = false, bup = false, bdown = false;
//collision detection here we go
{
Float32 delta = VERTICAL_DELTA;
Float32 up;
Float32 down;
Float32 left;
Float32 right;
/**
* Down
*/
up = position.y + DELTA_HEIGHT + totalSpeed.y * speed;
down = position.y + totalSpeed.y * speed;
left = position.x + delta + totalSpeed.x * speed;
right = position.x + (1.0f - delta) + totalSpeed.x * speed;
if (level.isWall(right, down, true) || level.isWall(left, down, true)) {
bdown = true;
velocity.y = 0;
totalSpeed.y = 0;
}
/**
* Up
*/
up = position.y + DELTA_HEIGHT + totalSpeed.y * speed;
down = position.y + totalSpeed.y * speed;
left = position.x + delta + totalSpeed.x * speed;
right = position.x + (1.0f - delta) + totalSpeed.x * speed;
if (totalSpeed.y > 0.0f && (level.isWall(right, up, true) || level.isWall(left, up, true))) {
bup = true;
totalSpeed.y = 0;
velocity.y = 0;
}
/**
* Right
*/
delta = HORIZONTAL_DELTA;
left = position.x + delta + totalSpeed.x * speed;
down = position.y + 0.1f;
if (totalSpeed.y > 0) {
up = position.y + DELTA_HEIGHT + totalSpeed.y * speed;
} else {
up = position.y + DELTA_HEIGHT;
}
right = position.x + (1.0f - delta) + totalSpeed.x * speed;
if (totalSpeed.x > 0 && (floorf(right) > floorf(position.x)) &&
((level.isWall(right, up, true) || level.isWall(right, down, true)))) {
bright = true;
}
/**
* Left
*/
up = position.y + DELTA_HEIGHT;
down = position.y + 0.1f;
left = position.x + delta + totalSpeed.x * speed;
right = position.x + (1.0f - delta) + totalSpeed.x * speed;
if (totalSpeed.y > 0) {
up = position.y + DELTA_HEIGHT + totalSpeed.y * speed;
} else {
up = position.y + DELTA_HEIGHT;
}
if (level.isWall(left, up, true) || level.isWall(left, down, true) || (left < 0)) {
bleft = true;
}
/**
* Put it all together
*/
if (!isOnElevator()) { //TODO POSSIBLE PROBLEM
if (bdown) {
position.y = std::ceil(position.y - 0.5f);
} else if (bup) {
position.y = std::floor(position.y + 0.5f);
}
if (bleft) {
position.x = std::ceil(position.x + totalSpeed.x * speed) - delta;
} else if (bright) {
position.x = floorf(this->position.x) + delta;
}
}
if (bleft || bright) {
externalForcesSpeed.x *= 0.5;
}
if (bup || bdown) {
externalForcesSpeed.y *= 0.5;
}
// waterForces *= 0.9;
externalForcesSpeed.x *= 0.9;
externalForcesSpeed.y *= 0.9;
position.x = std::max(-0.1f, std::min(position.x, level.getWidth() - 0.9f));
}
position.y += totalSpeed.y * speed; // the speed has the elapsedTime already factored in
position.x += totalSpeed.x * D6_PLAYER_ACCEL * speed; // the speed has the elapsedTime already factored in
lastCollisionCheck.up = bup;
lastCollisionCheck.right = bright;
lastCollisionCheck.down = bdown;
lastCollisionCheck.left = bleft;
}
void CollidingEntity::initPosition(Float32 x, Float32 y, Float32 z) {
position = {x, y, z};
velocity = {0, 0};
acceleration = {0, 0};
externalForces = {0, 0};
externalForcesSpeed = {0, 0};
lastCollisionCheck = {true, true, true, true, true, true, false};
}
Rectangle CollidingEntity::getCollisionRect() const {
return Rectangle::fromCornerAndSize(position, dimensions);
}
bool CollidingEntity::isInWall() const {
return lastCollisionCheck.inWall;
}
bool CollidingEntity::isOnHardSurface() const {
return isOnGround() || isOnElevator();
}
bool CollidingEntity::isUnderHardSurface() const {
return !lastCollisionCheck.clearForJump;
}
bool CollidingEntity::isOnElevator() const {
return elevator != nullptr;
}
bool CollidingEntity::isOnGround() const {
return lastCollisionCheck.onGround;
}
}
|
/*
* Copyright (c) 2006, Ondrej Danek (www.ondrej-danek.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.
* * 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 Ondrej Danek 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 "WorldCollision.h"
#include "../Rectangle.h"
namespace Duel6 {
//TODO Duplicity
static const float GRAVITATIONAL_ACCELERATION = -11.0f;
void CollidingEntity::collideWithElevators(ElevatorList & elevators, Float32 elapsedTime, Float32 speed) {
elevator = elevators.checkCollider(*this, elapsedTime * speed);
if(elevator != nullptr) {
position.y = elevator->getPosition().y;
position += elevator->getVelocity() * elapsedTime;
velocity.y = 0.0f;
if(isInWall()) {
velocity.x = 0.0f;
}
}
}
void CollidingEntity::collideWithLevel(const Level & level, Float32 elapsedTime, Float32 speed) {
static bool bleft = false, bright = false, bup = false, bdown = false;
{
Float32 delta = 0.8f * VERTICAL_DELTA;
Float32 down = position.y - FLOOR_DISTANCE_THRESHOLD;
Float32 left = position.x + delta;
Float32 right = position.x + (1 - delta);
lastCollisionCheck.onGround = level.isWall(left, down, true) || level.isWall(right, down, true);
}
{
Float32 delta = VERTICAL_DELTA;
Float32 up = position.y + DELTA_HEIGHT;
Float32 left = position.x + delta;
Float32 right = position.x + (1.0f - delta);
lastCollisionCheck.clearForJump = !level.isWall(left, up, true) && !level.isWall(right, up, true);
}
lastCollisionCheck.inWall = level.isWall(Int32(getCollisionRect().getCentre().x), Int32(getCollisionRect().getCentre().y), true);
if (!isOnElevator()) {
velocity.y += GRAVITATIONAL_ACCELERATION * elapsedTime; // gravity
}
if (!isOnGround()) {
if (velocity.y < -D6_PLAYER_JUMP_SPEED) {
velocity.y = -D6_PLAYER_JUMP_SPEED;
}
}
externalForcesSpeed += externalForces;
externalForces.x = 0;
externalForces.y = 0;
if (externalForcesSpeed.length() < 0.01) {
externalForcesSpeed.x = 0;
externalForcesSpeed.y = 0;
}
//friction
if(velocity.x > 0.0f) {
acceleration.x -= std::min(elapsedTime, velocity.x);
}
if(velocity.x < 0.0f) {
acceleration.x += std::min(elapsedTime, std::abs(velocity.x));
}
//do not multiply by speed or elapsedTime !!!
velocity += acceleration;
acceleration.x = 0;
acceleration.y = 0;
// horizontal speed clamping
if (std::abs(velocity.x * speed) > 0.5f) {
velocity.x = std::copysign(0.5f, this->velocity.x) / speed;
}
if (std::abs(externalForcesSpeed.x * speed) > 0.5f) {
externalForcesSpeed.x = std::copysign(0.5f, externalForcesSpeed.x) / speed;
}
Vector totalSpeed = velocity + externalForcesSpeed;
bleft = false, bright = false, bup = false, bdown = false;
//collision detection here we go
{
Float32 delta = VERTICAL_DELTA;
Float32 up;
Float32 down;
Float32 left;
Float32 right;
/**
* Down
*/
up = position.y + DELTA_HEIGHT + totalSpeed.y * speed;
down = position.y + totalSpeed.y * speed;
left = position.x + delta + totalSpeed.x * speed;
right = position.x + (1.0f - delta) + totalSpeed.x * speed;
if (level.isWall(right, down, true) || level.isWall(left, down, true)) {
bdown = true;
velocity.y = 0;
totalSpeed.y = 0;
}
/**
* Up
*/
up = position.y + DELTA_HEIGHT + totalSpeed.y * speed;
down = position.y + totalSpeed.y * speed;
left = position.x + delta + totalSpeed.x * speed;
right = position.x + (1.0f - delta) + totalSpeed.x * speed;
if (totalSpeed.y > 0.0f && (level.isWall(right, up, true) || level.isWall(left, up, true))) {
bup = true;
totalSpeed.y = 0;
velocity.y = 0;
}
/**
* Right
*/
delta = HORIZONTAL_DELTA;
left = position.x + delta + totalSpeed.x * speed;
down = position.y + 0.1f;
if (totalSpeed.y > 0) {
up = position.y + DELTA_HEIGHT + totalSpeed.y * speed;
} else {
up = position.y + DELTA_HEIGHT;
}
right = position.x + (1.0f - delta) + totalSpeed.x * speed;
if (totalSpeed.x > 0 && (floorf(right) > floorf(position.x)) &&
((level.isWall(right, up, true) || level.isWall(right, down, true)))) {
bright = true;
}
/**
* Left
*/
up = position.y + DELTA_HEIGHT;
down = position.y + 0.1f;
left = position.x + delta + totalSpeed.x * speed;
right = position.x + (1.0f - delta) + totalSpeed.x * speed;
if (totalSpeed.y > 0) {
up = position.y + DELTA_HEIGHT + totalSpeed.y * speed;
} else {
up = position.y + DELTA_HEIGHT;
}
if (level.isWall(left, up, true) || level.isWall(left, down, true) || (left < 0)) {
bleft = true;
}
/**
* Put it all together
*/
if (!isOnElevator()) {
if (bdown) {
position.y = std::ceil(position.y - 0.5f);
} else if (bup) {
position.y = std::floor(position.y + 0.5f);
}
if (bleft) {
position.x = std::ceil(position.x + totalSpeed.x * speed) - delta;
} else if (bright) {
position.x = floorf(this->position.x) + delta;
}
} else if(isInWall() && bleft || bright){
externalForces.x = (elevator->getPosition().x - position.x);
}
if (bleft || bright) {
externalForcesSpeed.x *= 0.5;
}
if (bup || bdown) {
externalForcesSpeed.y *= 0.5;
}
externalForcesSpeed.x *= 0.9;
externalForcesSpeed.y *= 0.9;
position.x = std::max(-0.1f, std::min(position.x, level.getWidth() - 0.9f));
}
position.y += totalSpeed.y * speed; // the speed has the elapsedTime already factored in
position.x += totalSpeed.x * D6_PLAYER_ACCEL * speed; // the speed has the elapsedTime already factored in
lastCollisionCheck.up = bup;
lastCollisionCheck.right = bright;
lastCollisionCheck.down = bdown;
lastCollisionCheck.left = bleft;
}
void CollidingEntity::initPosition(Float32 x, Float32 y, Float32 z) {
position = {x, y, z};
velocity = {0, 0};
acceleration = {0, 0};
externalForces = {0, 0};
externalForcesSpeed = {0, 0};
lastCollisionCheck = {true, true, true, true, true, true, false};
}
Rectangle CollidingEntity::getCollisionRect() const {
return Rectangle::fromCornerAndSize(position, dimensions);
}
bool CollidingEntity::isInWall() const {
return lastCollisionCheck.inWall;
}
bool CollidingEntity::isOnHardSurface() const {
return isOnGround() || isOnElevator();
}
bool CollidingEntity::isUnderHardSurface() const {
return !lastCollisionCheck.clearForJump;
}
bool CollidingEntity::isOnElevator() const {
return elevator != nullptr;
}
bool CollidingEntity::isOnGround() const {
return lastCollisionCheck.onGround;
}
}
|
Fix getting stuck in walls when standing beyond the edge of an elevator
|
Fix getting stuck in walls when standing beyond the edge of an elevator
|
C++
|
bsd-3-clause
|
mkapusnik/duel6r,odanek/duel6r,DaleRunner/duel6r,DaleRunner/duel6r,odanek/duel6r,mkapusnik/duel6r
|
8b59ad4862cd9a3a9dd647199312b931d9dc2175
|
src/jet/fdm_gauss_seidel_solver3.cpp
|
src/jet/fdm_gauss_seidel_solver3.cpp
|
// Copyright (c) 2017 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include <pch.h>
#include <jet/constants.h>
#include <jet/fdm_gauss_seidel_solver3.h>
using namespace jet;
FdmGaussSeidelSolver3::FdmGaussSeidelSolver3(unsigned int maxNumberOfIterations,
unsigned int residualCheckInterval,
double tolerance, double sorFactor,
bool useRedBlackOrdering)
: _maxNumberOfIterations(maxNumberOfIterations),
_lastNumberOfIterations(0),
_residualCheckInterval(residualCheckInterval),
_tolerance(tolerance),
_lastResidual(kMaxD),
_sorFactor(sorFactor),
_useRedBlackOrdering(useRedBlackOrdering) {}
bool FdmGaussSeidelSolver3::solve(FdmLinearSystem3* system) {
clearCompressedVectors();
_residual.resize(system->x.size());
_lastNumberOfIterations = _maxNumberOfIterations;
for (unsigned int iter = 0; iter < _maxNumberOfIterations; ++iter) {
relax(system->A, system->b, _sorFactor, &system->x);
if (iter != 0 && iter % _residualCheckInterval == 0) {
FdmBlas3::residual(system->A, system->x, system->b, &_residual);
if (FdmBlas3::l2Norm(_residual) < _tolerance) {
_lastNumberOfIterations = iter + 1;
break;
}
}
}
FdmBlas3::residual(system->A, system->x, system->b, &_residual);
_lastResidual = FdmBlas3::l2Norm(_residual);
return _lastResidual < _tolerance;
}
bool FdmGaussSeidelSolver3::solveCompressed(
FdmCompressedLinearSystem3* system) {
clearUncompressedVectors();
_residualComp.resize(system->x.size());
_lastNumberOfIterations = _maxNumberOfIterations;
for (unsigned int iter = 0; iter < _maxNumberOfIterations; ++iter) {
relax(system->A, system->b, _sorFactor, &system->x);
if (iter != 0 && iter % _residualCheckInterval == 0) {
FdmCompressedBlas3::residual(system->A, system->x, system->b,
&_residualComp);
if (FdmCompressedBlas3::l2Norm(_residualComp) < _tolerance) {
_lastNumberOfIterations = iter + 1;
break;
}
}
}
FdmCompressedBlas3::residual(system->A, system->x, system->b,
&_residualComp);
_lastResidual = FdmCompressedBlas3::l2Norm(_residualComp);
return _lastResidual < _tolerance;
}
unsigned int FdmGaussSeidelSolver3::maxNumberOfIterations() const {
return _maxNumberOfIterations;
}
unsigned int FdmGaussSeidelSolver3::lastNumberOfIterations() const {
return _lastNumberOfIterations;
}
double FdmGaussSeidelSolver3::tolerance() const { return _tolerance; }
double FdmGaussSeidelSolver3::lastResidual() const { return _lastResidual; }
double FdmGaussSeidelSolver3::sorFactor() const { return _sorFactor; }
bool FdmGaussSeidelSolver3::useRedBlackOrdering() const {
return _useRedBlackOrdering;
}
void FdmGaussSeidelSolver3::relax(const FdmMatrix3& A, const FdmVector3& b,
double sorFactor, FdmVector3* x_) {
Size3 size = A.size();
FdmVector3& x = *x_;
A.forEachIndex([&](size_t i, size_t j, size_t k) {
double r =
((i > 0) ? A(i - 1, j, k).right * x(i - 1, j, k) : 0.0) +
((i + 1 < size.x) ? A(i, j, k).right * x(i + 1, j, k) : 0.0) +
((j > 0) ? A(i, j - 1, k).up * x(i, j - 1, k) : 0.0) +
((j + 1 < size.y) ? A(i, j, k).up * x(i, j + 1, k) : 0.0) +
((k > 0) ? A(i, j, k - 1).front * x(i, j, k - 1) : 0.0) +
((k + 1 < size.z) ? A(i, j, k).front * x(i, j, k + 1) : 0.0);
x(i, j, k) = (1.0 - sorFactor) * x(i, j, k) +
sorFactor * (b(i, j, k) - r) / A(i, j, k).center;
});
}
void FdmGaussSeidelSolver3::relax(const MatrixCsrD& A, const VectorND& b,
double sorFactor, VectorND* x_) {
const auto rp = A.rowPointersBegin();
const auto ci = A.columnIndicesBegin();
const auto nnz = A.nonZeroBegin();
VectorND& x = *x_;
b.forEachIndex([&](size_t i) {
const size_t rowBegin = rp[i];
const size_t rowEnd = rp[i + 1];
double r = 0.0;
double diag = 1.0;
for (size_t jj = rowBegin; jj < rowEnd; ++jj) {
size_t j = ci[jj];
if (i == j) {
diag = nnz[jj];
} else {
r += nnz[jj] * x[j];
}
}
x[i] = (1.0 - sorFactor) * x[i] + sorFactor * (b[i] - r) / diag;
});
}
void FdmGaussSeidelSolver3::relaxRedBlack(const FdmMatrix3& A,
const FdmVector3& b, double sorFactor,
FdmVector3* x_) {
Size3 size = A.size();
FdmVector3& x = *x_;
// Red update
parallelRangeFor(
kZeroSize, size.x, kZeroSize, size.y, kZeroSize, size.z,
[&](size_t iBegin, size_t iEnd, size_t jBegin, size_t jEnd,
size_t kBegin, size_t kEnd) {
for (size_t k = kBegin; k < kEnd; ++k) {
for (size_t j = jBegin; j < jEnd; ++j) {
size_t i = (j + k) % 2 + iBegin; // i.e. (0, 0, 0)
for (; i < iEnd; i += 2) {
double r =
((i > 0) ? A(i - 1, j, k).right * x(i - 1, j, k)
: 0.0) +
((i + 1 < size.x)
? A(i, j, k).right * x(i + 1, j, k)
: 0.0) +
((j > 0) ? A(i, j - 1, k).up * x(i, j - 1, k)
: 0.0) +
((j + 1 < size.y) ? A(i, j, k).up * x(i, j + 1, k)
: 0.0) +
((k > 0) ? A(i, j, k - 1).front * x(i, j, k - 1)
: 0.0) +
((k + 1 < size.z)
? A(i, j, k).front * x(i, j, k + 1)
: 0.0);
x(i, j, k) =
(1.0 - sorFactor) * x(i, j, k) +
sorFactor * (b(i, j, k) - r) / A(i, j, k).center;
}
}
}
});
// Black update
parallelRangeFor(
kZeroSize, size.x, kZeroSize, size.y, kZeroSize, size.z,
[&](size_t iBegin, size_t iEnd, size_t jBegin, size_t jEnd,
size_t kBegin, size_t kEnd) {
for (size_t k = kBegin; k < kEnd; ++k) {
for (size_t j = jBegin; j < jEnd; ++j) {
size_t i = 1 - (j + k) % 2 + iBegin; // i.e. (1, 1, 1)
for (; i < iEnd; i += 2) {
double r =
((i > 0) ? A(i - 1, j, k).right * x(i - 1, j, k)
: 0.0) +
((i + 1 < size.x)
? A(i, j, k).right * x(i + 1, j, k)
: 0.0) +
((j > 0) ? A(i, j - 1, k).up * x(i, j - 1, k)
: 0.0) +
((j + 1 < size.y) ? A(i, j, k).up * x(i, j + 1, k)
: 0.0) +
((k > 0) ? A(i, j, k - 1).front * x(i, j, k - 1)
: 0.0) +
((k + 1 < size.z)
? A(i, j, k).front * x(i, j, k + 1)
: 0.0);
x(i, j, k) =
(1.0 - sorFactor) * x(i, j, k) +
sorFactor * (b(i, j, k) - r) / A(i, j, k).center;
}
}
}
});
}
void FdmGaussSeidelSolver3::clearUncompressedVectors() { _residual.clear(); }
void FdmGaussSeidelSolver3::clearCompressedVectors() { _residualComp.clear(); }
|
// Copyright (c) 2017 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include <pch.h>
#include <jet/constants.h>
#include <jet/fdm_gauss_seidel_solver3.h>
using namespace jet;
FdmGaussSeidelSolver3::FdmGaussSeidelSolver3(unsigned int maxNumberOfIterations,
unsigned int residualCheckInterval,
double tolerance, double sorFactor,
bool useRedBlackOrdering)
: _maxNumberOfIterations(maxNumberOfIterations),
_lastNumberOfIterations(0),
_residualCheckInterval(residualCheckInterval),
_tolerance(tolerance),
_lastResidual(kMaxD),
_sorFactor(sorFactor),
_useRedBlackOrdering(useRedBlackOrdering) {}
bool FdmGaussSeidelSolver3::solve(FdmLinearSystem3* system) {
clearCompressedVectors();
_residual.resize(system->x.size());
_lastNumberOfIterations = _maxNumberOfIterations;
for (unsigned int iter = 0; iter < _maxNumberOfIterations; ++iter) {
if (_useRedBlackOrdering) {
relaxRedBlack(system->A, system->b, _sorFactor, &system->x);
} else {
relax(system->A, system->b, _sorFactor, &system->x);
}
if (iter != 0 && iter % _residualCheckInterval == 0) {
FdmBlas3::residual(system->A, system->x, system->b, &_residual);
if (FdmBlas3::l2Norm(_residual) < _tolerance) {
_lastNumberOfIterations = iter + 1;
break;
}
}
}
FdmBlas3::residual(system->A, system->x, system->b, &_residual);
_lastResidual = FdmBlas3::l2Norm(_residual);
return _lastResidual < _tolerance;
}
bool FdmGaussSeidelSolver3::solveCompressed(
FdmCompressedLinearSystem3* system) {
clearUncompressedVectors();
_residualComp.resize(system->x.size());
_lastNumberOfIterations = _maxNumberOfIterations;
for (unsigned int iter = 0; iter < _maxNumberOfIterations; ++iter) {
relax(system->A, system->b, _sorFactor, &system->x);
if (iter != 0 && iter % _residualCheckInterval == 0) {
FdmCompressedBlas3::residual(system->A, system->x, system->b,
&_residualComp);
if (FdmCompressedBlas3::l2Norm(_residualComp) < _tolerance) {
_lastNumberOfIterations = iter + 1;
break;
}
}
}
FdmCompressedBlas3::residual(system->A, system->x, system->b,
&_residualComp);
_lastResidual = FdmCompressedBlas3::l2Norm(_residualComp);
return _lastResidual < _tolerance;
}
unsigned int FdmGaussSeidelSolver3::maxNumberOfIterations() const {
return _maxNumberOfIterations;
}
unsigned int FdmGaussSeidelSolver3::lastNumberOfIterations() const {
return _lastNumberOfIterations;
}
double FdmGaussSeidelSolver3::tolerance() const { return _tolerance; }
double FdmGaussSeidelSolver3::lastResidual() const { return _lastResidual; }
double FdmGaussSeidelSolver3::sorFactor() const { return _sorFactor; }
bool FdmGaussSeidelSolver3::useRedBlackOrdering() const {
return _useRedBlackOrdering;
}
void FdmGaussSeidelSolver3::relax(const FdmMatrix3& A, const FdmVector3& b,
double sorFactor, FdmVector3* x_) {
Size3 size = A.size();
FdmVector3& x = *x_;
A.forEachIndex([&](size_t i, size_t j, size_t k) {
double r =
((i > 0) ? A(i - 1, j, k).right * x(i - 1, j, k) : 0.0) +
((i + 1 < size.x) ? A(i, j, k).right * x(i + 1, j, k) : 0.0) +
((j > 0) ? A(i, j - 1, k).up * x(i, j - 1, k) : 0.0) +
((j + 1 < size.y) ? A(i, j, k).up * x(i, j + 1, k) : 0.0) +
((k > 0) ? A(i, j, k - 1).front * x(i, j, k - 1) : 0.0) +
((k + 1 < size.z) ? A(i, j, k).front * x(i, j, k + 1) : 0.0);
x(i, j, k) = (1.0 - sorFactor) * x(i, j, k) +
sorFactor * (b(i, j, k) - r) / A(i, j, k).center;
});
}
void FdmGaussSeidelSolver3::relax(const MatrixCsrD& A, const VectorND& b,
double sorFactor, VectorND* x_) {
const auto rp = A.rowPointersBegin();
const auto ci = A.columnIndicesBegin();
const auto nnz = A.nonZeroBegin();
VectorND& x = *x_;
b.forEachIndex([&](size_t i) {
const size_t rowBegin = rp[i];
const size_t rowEnd = rp[i + 1];
double r = 0.0;
double diag = 1.0;
for (size_t jj = rowBegin; jj < rowEnd; ++jj) {
size_t j = ci[jj];
if (i == j) {
diag = nnz[jj];
} else {
r += nnz[jj] * x[j];
}
}
x[i] = (1.0 - sorFactor) * x[i] + sorFactor * (b[i] - r) / diag;
});
}
void FdmGaussSeidelSolver3::relaxRedBlack(const FdmMatrix3& A,
const FdmVector3& b, double sorFactor,
FdmVector3* x_) {
Size3 size = A.size();
FdmVector3& x = *x_;
// Red update
parallelRangeFor(
kZeroSize, size.x, kZeroSize, size.y, kZeroSize, size.z,
[&](size_t iBegin, size_t iEnd, size_t jBegin, size_t jEnd,
size_t kBegin, size_t kEnd) {
for (size_t k = kBegin; k < kEnd; ++k) {
for (size_t j = jBegin; j < jEnd; ++j) {
size_t i = (j + k) % 2 + iBegin; // i.e. (0, 0, 0)
for (; i < iEnd; i += 2) {
double r =
((i > 0) ? A(i - 1, j, k).right * x(i - 1, j, k)
: 0.0) +
((i + 1 < size.x)
? A(i, j, k).right * x(i + 1, j, k)
: 0.0) +
((j > 0) ? A(i, j - 1, k).up * x(i, j - 1, k)
: 0.0) +
((j + 1 < size.y) ? A(i, j, k).up * x(i, j + 1, k)
: 0.0) +
((k > 0) ? A(i, j, k - 1).front * x(i, j, k - 1)
: 0.0) +
((k + 1 < size.z)
? A(i, j, k).front * x(i, j, k + 1)
: 0.0);
x(i, j, k) =
(1.0 - sorFactor) * x(i, j, k) +
sorFactor * (b(i, j, k) - r) / A(i, j, k).center;
}
}
}
});
// Black update
parallelRangeFor(
kZeroSize, size.x, kZeroSize, size.y, kZeroSize, size.z,
[&](size_t iBegin, size_t iEnd, size_t jBegin, size_t jEnd,
size_t kBegin, size_t kEnd) {
for (size_t k = kBegin; k < kEnd; ++k) {
for (size_t j = jBegin; j < jEnd; ++j) {
size_t i = 1 - (j + k) % 2 + iBegin; // i.e. (1, 1, 1)
for (; i < iEnd; i += 2) {
double r =
((i > 0) ? A(i - 1, j, k).right * x(i - 1, j, k)
: 0.0) +
((i + 1 < size.x)
? A(i, j, k).right * x(i + 1, j, k)
: 0.0) +
((j > 0) ? A(i, j - 1, k).up * x(i, j - 1, k)
: 0.0) +
((j + 1 < size.y) ? A(i, j, k).up * x(i, j + 1, k)
: 0.0) +
((k > 0) ? A(i, j, k - 1).front * x(i, j, k - 1)
: 0.0) +
((k + 1 < size.z)
? A(i, j, k).front * x(i, j, k + 1)
: 0.0);
x(i, j, k) =
(1.0 - sorFactor) * x(i, j, k) +
sorFactor * (b(i, j, k) - r) / A(i, j, k).center;
}
}
}
});
}
void FdmGaussSeidelSolver3::clearUncompressedVectors() { _residual.clear(); }
void FdmGaussSeidelSolver3::clearCompressedVectors() { _residualComp.clear(); }
|
Fix missing logic in FDM gauss-seidel solver (#129)
|
Fix missing logic in FDM gauss-seidel solver (#129)
|
C++
|
mit
|
doyubkim/fluid-engine-dev,doyubkim/fluid-engine-dev,doyubkim/fluid-engine-dev,doyubkim/fluid-engine-dev
|
a643a7fde21801c0f8bb27060169d0130f66cd41
|
PWGJE/EMCALJetTasks/UserTasks/AliAnalysisTaskJetMassResponseDet.cxx
|
PWGJE/EMCALJetTasks/UserTasks/AliAnalysisTaskJetMassResponseDet.cxx
|
//
// Detector response jet mass analysis task.
//
// Author: M.Verweij
#include <TClonesArray.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TH3F.h>
#include <THnSparse.h>
#include <TList.h>
#include <TLorentzVector.h>
#include <TProfile.h>
#include <TChain.h>
#include <TSystem.h>
#include <TFile.h>
#include <TKey.h>
#include "AliVCluster.h"
#include "AliVTrack.h"
#include "AliEmcalJet.h"
#include "AliRhoParameter.h"
#include "AliLog.h"
#include "AliEmcalParticle.h"
#include "AliMCEvent.h"
#include "AliGenPythiaEventHeader.h"
#include "AliAODMCHeader.h"
#include "AliMCEvent.h"
#include "AliAnalysisManager.h"
#include "AliJetContainer.h"
#include "AliAODEvent.h"
#include "AliAnalysisTaskJetMassResponseDet.h"
ClassImp(AliAnalysisTaskJetMassResponseDet)
//________________________________________________________________________
AliAnalysisTaskJetMassResponseDet::AliAnalysisTaskJetMassResponseDet() :
AliAnalysisTaskEmcalJet("AliAnalysisTaskJetMassResponseDet", kTRUE),
fContainerPart(0),
fContainerDet(0),
fJetMassType(kRaw),
fh2PtVsMassJetPartAll(0),
fh2PtVsMassJetPartMatch(0),
fh2PtVsMassJetPartTagged(0),
fh2PtVsMassJetPartTaggedMatch(0),
fh2PtVsMassJetDetAll(0),
fh2PtVsMassJetDetTagged(0),
fh2EtaPhiMatchedDet(0),
fh2EtaPhiMatchedPart(0),
fhnMassResponse(0)
{
// Default constructor.
SetMakeGeneralHistograms(kTRUE);
}
//________________________________________________________________________
AliAnalysisTaskJetMassResponseDet::AliAnalysisTaskJetMassResponseDet(const char *name) :
AliAnalysisTaskEmcalJet(name, kTRUE),
fContainerPart(0),
fContainerDet(0),
fJetMassType(kRaw),
fh2PtVsMassJetPartAll(0),
fh2PtVsMassJetPartMatch(0),
fh2PtVsMassJetPartTagged(0),
fh2PtVsMassJetPartTaggedMatch(0),
fh2PtVsMassJetDetAll(0),
fh2PtVsMassJetDetTagged(0),
fh2EtaPhiMatchedDet(0),
fh2EtaPhiMatchedPart(0),
fhnMassResponse(0)
{
// Standard constructor.
SetMakeGeneralHistograms(kTRUE);
}
//________________________________________________________________________
AliAnalysisTaskJetMassResponseDet::~AliAnalysisTaskJetMassResponseDet()
{
// Destructor.
}
//________________________________________________________________________
void AliAnalysisTaskJetMassResponseDet::UserCreateOutputObjects()
{
// Create user output.
AliAnalysisTaskEmcalJet::UserCreateOutputObjects();
Bool_t oldStatus = TH1::AddDirectoryStatus();
TH1::AddDirectory(kFALSE);
const Int_t nBinsPt = 200;
const Double_t minPt = 0.;
const Double_t maxPt = 200.;
const Int_t nBinsM = 100;
const Double_t minM = 0.;
const Double_t maxM = 50.;
const Int_t nBinsConstEff = 24;
const Double_t minConstEff = 0.;
const Double_t maxConstEff = 1.2;
// const Int_t nBinsConst = 26;
// const Double_t minConst = -5.5;
// const Double_t maxConst = 20.5;
//Binning for THnSparse
const Int_t nBinsSparse0 = 5;
const Int_t nBins0[nBinsSparse0] = {nBinsM,nBinsM,nBinsPt,nBinsPt,nBinsConstEff};
const Double_t xmin0[nBinsSparse0] = { minM, minM, minPt, minPt, minConstEff};
const Double_t xmax0[nBinsSparse0] = { maxM, maxM, maxPt, maxPt, maxConstEff};
//Create histograms
TString histName = "";
TString histTitle = "";
histName = "fh2PtVsMassJetPartAll";
histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{M}_{jet1}",histName.Data());
fh2PtVsMassJetPartAll = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsM,minM,maxM);
fOutput->Add(fh2PtVsMassJetPartAll);
histName = "fh2PtVsMassJetPartMatch";
histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{M}_{jet1}",histName.Data());
fh2PtVsMassJetPartMatch = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsM,minM,maxM);
fOutput->Add(fh2PtVsMassJetPartMatch);
histName = "fh2PtVsMassJetPartTagged";
histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{M}_{jet1}",histName.Data());
fh2PtVsMassJetPartTagged = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsM,minM,maxM);
fOutput->Add(fh2PtVsMassJetPartTagged);
histName = "fh2PtVsMassJetPartTaggedMatch";
histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{M}_{jet1}",histName.Data());
fh2PtVsMassJetPartTaggedMatch = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsM,minM,maxM);
fOutput->Add(fh2PtVsMassJetPartTaggedMatch);
histName = "fh2PtVsMassJetDetAll";
histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{M}_{jet1}",histName.Data());
fh2PtVsMassJetDetAll = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsM,minM,maxM);
fOutput->Add(fh2PtVsMassJetDetAll);
histName = "fh2PtVsMassJetDetTagged";
histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{M}_{jet1}",histName.Data());
fh2PtVsMassJetDetTagged = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsM,minM,maxM);
fOutput->Add(fh2PtVsMassJetDetTagged);
histName = "fh2EtaPhiMatchedDet";
histTitle = TString::Format("%s;#eta;#varphi",histName.Data());
fh2EtaPhiMatchedDet = new TH2F(histName.Data(),histTitle.Data(),100,-1.,1.,72,0.,TMath::TwoPi());
fOutput->Add(fh2EtaPhiMatchedDet);
histName = "fh2EtaPhiMatchedPart";
histTitle = TString::Format("%s;#eta;#varphi",histName.Data());
fh2EtaPhiMatchedPart = new TH2F(histName.Data(),histTitle.Data(),100,-1.,1.,72,0.,TMath::TwoPi());
fOutput->Add(fh2EtaPhiMatchedPart);
histName = "fhnMassResponse";
histTitle = Form("%s;#it{M}_{det};#it{M}_{part};#it{p}_{T,det};#it{p}_{T,part};#it{M}_{det}^{tagged}",histName.Data());
fhnMassResponse = new THnSparseF(histName.Data(),histTitle.Data(),nBinsSparse0,nBins0,xmin0,xmax0);
fOutput->Add(fhnMassResponse);
// =========== Switch on Sumw2 for all histos ===========
for (Int_t i=0; i<fOutput->GetEntries(); ++i) {
TH1 *h1 = dynamic_cast<TH1*>(fOutput->At(i));
if (h1){
h1->Sumw2();
continue;
}
THnSparse *hn = dynamic_cast<THnSparse*>(fOutput->At(i));
if(hn)hn->Sumw2();
}
TH1::AddDirectory(oldStatus);
PostData(1, fOutput); // Post data for ALL output slots > 0 here.
}
//________________________________________________________________________
Bool_t AliAnalysisTaskJetMassResponseDet::Run()
{
// Run analysis code here, if needed. It will be executed before FillHistograms().
return kTRUE;
}
//________________________________________________________________________
Bool_t AliAnalysisTaskJetMassResponseDet::FillHistograms()
{
// Fill histograms.
AliJetContainer *cPart = GetJetContainer(fContainerPart);
AliJetContainer *cDet = GetJetContainer(fContainerDet);
AliEmcalJet* jPart = NULL;
AliEmcalJet* jDet = NULL;
//loop on particle level jets
if(cPart) {
cPart->ResetCurrentID();
while((jPart = cPart->GetNextAcceptJet())) {
fh2PtVsMassJetPartAll->Fill(jPart->Pt(),jPart->M());
jDet = jPart->ClosestJet();
if(jDet) fh2PtVsMassJetPartMatch->Fill(jPart->Pt(),jPart->M());
if(jPart->GetTagStatus()<1 || !jPart->GetTaggedJet())
continue;
fh2PtVsMassJetPartTagged->Fill(jPart->Pt(),jPart->M());
if(jDet) fh2PtVsMassJetPartTaggedMatch->Fill(jPart->Pt(),jPart->M());
}
}
//loop on detector level jets
if(cDet) {
cDet->ResetCurrentID();
while((jDet = cDet->GetNextAcceptJet())) {
Double_t mjet = GetJetMass(jDet);
fh2PtVsMassJetDetAll->Fill(jDet->Pt(),mjet);
if(jDet->GetTagStatus()>=1 && jDet->GetTaggedJet())
fh2PtVsMassJetDetTagged->Fill(jDet->Pt(),mjet);
//fill detector response
jPart = jDet->ClosestJet();
if(jPart) {
fh2EtaPhiMatchedDet->Fill(jDet->Eta(),jDet->Phi());
fh2EtaPhiMatchedPart->Fill(jPart->Eta(),jPart->Phi());
Int_t nConstPart = jPart->GetNumberOfConstituents();
Int_t nConstDet = jDet->GetNumberOfConstituents();
Int_t diff = nConstPart-nConstDet;
Double_t eff = -1.;
if(nConstPart>0) eff = (Double_t)nConstDet/((Double_t)nConstPart);
Double_t var[5] = {GetJetMass(jDet),jPart->M(),jDet->Pt(),jPart->Pt(),eff};
fhnMassResponse->Fill(var);
if(jPart->Pt()>40. && jPart->Pt()<50.) {
if(jDet->Pt()>50.) Printf("feed-out high");
else if(jDet->Pt()<40.) Printf("feed-out low");
else Printf("correct");
Printf("pT Part: %f Det: %f",jPart->Pt(),jDet->Pt());
Printf("mass Part: %f Det: %f",jPart->M(),jDet->M());
Printf("nConst Part: %d Det: %d diff: %d",nConstPart,nConstDet,diff);
}
}
}
}
return kTRUE;
}
//________________________________________________________________________
Double_t AliAnalysisTaskJetMassResponseDet::GetJetMass(AliEmcalJet *jet) {
//calc subtracted jet mass
if(fJetMassType==kRaw)
return jet->M();
else if(fJetMassType==kDeriv)
return jet->GetSecondOrderSubtracted();
return 0;
}
//________________________________________________________________________
Bool_t AliAnalysisTaskJetMassResponseDet::RetrieveEventObjects() {
//
// retrieve event objects
if (!AliAnalysisTaskEmcalJet::RetrieveEventObjects())
return kFALSE;
return kTRUE;
}
//_______________________________________________________________________
void AliAnalysisTaskJetMassResponseDet::Terminate(Option_t *)
{
// Called once at the end of the analysis.
}
|
//
// Detector response jet mass analysis task.
//
// Author: M.Verweij
#include <TClonesArray.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TH3F.h>
#include <THnSparse.h>
#include <TList.h>
#include <TLorentzVector.h>
#include <TProfile.h>
#include <TChain.h>
#include <TSystem.h>
#include <TFile.h>
#include <TKey.h>
#include "AliVCluster.h"
#include "AliVTrack.h"
#include "AliEmcalJet.h"
#include "AliRhoParameter.h"
#include "AliLog.h"
#include "AliEmcalParticle.h"
#include "AliMCEvent.h"
#include "AliGenPythiaEventHeader.h"
#include "AliAODMCHeader.h"
#include "AliMCEvent.h"
#include "AliAnalysisManager.h"
#include "AliJetContainer.h"
#include "AliAODEvent.h"
#include "AliAnalysisTaskJetMassResponseDet.h"
ClassImp(AliAnalysisTaskJetMassResponseDet)
//________________________________________________________________________
AliAnalysisTaskJetMassResponseDet::AliAnalysisTaskJetMassResponseDet() :
AliAnalysisTaskEmcalJet("AliAnalysisTaskJetMassResponseDet", kTRUE),
fContainerPart(0),
fContainerDet(0),
fJetMassType(kRaw),
fh2PtVsMassJetPartAll(0),
fh2PtVsMassJetPartMatch(0),
fh2PtVsMassJetPartTagged(0),
fh2PtVsMassJetPartTaggedMatch(0),
fh2PtVsMassJetDetAll(0),
fh2PtVsMassJetDetTagged(0),
fh2EtaPhiMatchedDet(0),
fh2EtaPhiMatchedPart(0),
fhnMassResponse(0)
{
// Default constructor.
SetMakeGeneralHistograms(kTRUE);
}
//________________________________________________________________________
AliAnalysisTaskJetMassResponseDet::AliAnalysisTaskJetMassResponseDet(const char *name) :
AliAnalysisTaskEmcalJet(name, kTRUE),
fContainerPart(0),
fContainerDet(0),
fJetMassType(kRaw),
fh2PtVsMassJetPartAll(0),
fh2PtVsMassJetPartMatch(0),
fh2PtVsMassJetPartTagged(0),
fh2PtVsMassJetPartTaggedMatch(0),
fh2PtVsMassJetDetAll(0),
fh2PtVsMassJetDetTagged(0),
fh2EtaPhiMatchedDet(0),
fh2EtaPhiMatchedPart(0),
fhnMassResponse(0)
{
// Standard constructor.
SetMakeGeneralHistograms(kTRUE);
}
//________________________________________________________________________
AliAnalysisTaskJetMassResponseDet::~AliAnalysisTaskJetMassResponseDet()
{
// Destructor.
}
//________________________________________________________________________
void AliAnalysisTaskJetMassResponseDet::UserCreateOutputObjects()
{
// Create user output.
AliAnalysisTaskEmcalJet::UserCreateOutputObjects();
Bool_t oldStatus = TH1::AddDirectoryStatus();
TH1::AddDirectory(kFALSE);
const Int_t nBinsPt = 200;
const Double_t minPt = 0.;
const Double_t maxPt = 200.;
const Int_t nBinsM = 100;
const Double_t minM = 0.;
const Double_t maxM = 50.;
const Int_t nBinsConstEff = 40;
const Double_t minConstEff = 0.;
const Double_t maxConstEff = 2.;
// const Int_t nBinsConst = 26;
// const Double_t minConst = -5.5;
// const Double_t maxConst = 20.5;
//Binning for THnSparse
const Int_t nBinsSparse0 = 5;
const Int_t nBins0[nBinsSparse0] = {nBinsM,nBinsM,nBinsPt,nBinsPt,nBinsConstEff};
const Double_t xmin0[nBinsSparse0] = { minM, minM, minPt, minPt, minConstEff};
const Double_t xmax0[nBinsSparse0] = { maxM, maxM, maxPt, maxPt, maxConstEff};
//Create histograms
TString histName = "";
TString histTitle = "";
histName = "fh2PtVsMassJetPartAll";
histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{M}_{jet1}",histName.Data());
fh2PtVsMassJetPartAll = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsM,minM,maxM);
fOutput->Add(fh2PtVsMassJetPartAll);
histName = "fh2PtVsMassJetPartMatch";
histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{M}_{jet1}",histName.Data());
fh2PtVsMassJetPartMatch = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsM,minM,maxM);
fOutput->Add(fh2PtVsMassJetPartMatch);
histName = "fh2PtVsMassJetPartTagged";
histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{M}_{jet1}",histName.Data());
fh2PtVsMassJetPartTagged = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsM,minM,maxM);
fOutput->Add(fh2PtVsMassJetPartTagged);
histName = "fh2PtVsMassJetPartTaggedMatch";
histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{M}_{jet1}",histName.Data());
fh2PtVsMassJetPartTaggedMatch = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsM,minM,maxM);
fOutput->Add(fh2PtVsMassJetPartTaggedMatch);
histName = "fh2PtVsMassJetDetAll";
histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{M}_{jet1}",histName.Data());
fh2PtVsMassJetDetAll = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsM,minM,maxM);
fOutput->Add(fh2PtVsMassJetDetAll);
histName = "fh2PtVsMassJetDetTagged";
histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{M}_{jet1}",histName.Data());
fh2PtVsMassJetDetTagged = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsM,minM,maxM);
fOutput->Add(fh2PtVsMassJetDetTagged);
histName = "fh2EtaPhiMatchedDet";
histTitle = TString::Format("%s;#eta;#varphi",histName.Data());
fh2EtaPhiMatchedDet = new TH2F(histName.Data(),histTitle.Data(),100,-1.,1.,72,0.,TMath::TwoPi());
fOutput->Add(fh2EtaPhiMatchedDet);
histName = "fh2EtaPhiMatchedPart";
histTitle = TString::Format("%s;#eta;#varphi",histName.Data());
fh2EtaPhiMatchedPart = new TH2F(histName.Data(),histTitle.Data(),100,-1.,1.,72,0.,TMath::TwoPi());
fOutput->Add(fh2EtaPhiMatchedPart);
histName = "fhnMassResponse";
histTitle = Form("%s;#it{M}_{det};#it{M}_{part};#it{p}_{T,det};#it{p}_{T,part};#it{N}_{const}^{det}/#it{N}_{const}^{part}",histName.Data());
fhnMassResponse = new THnSparseF(histName.Data(),histTitle.Data(),nBinsSparse0,nBins0,xmin0,xmax0);
fOutput->Add(fhnMassResponse);
// =========== Switch on Sumw2 for all histos ===========
for (Int_t i=0; i<fOutput->GetEntries(); ++i) {
TH1 *h1 = dynamic_cast<TH1*>(fOutput->At(i));
if (h1){
h1->Sumw2();
continue;
}
THnSparse *hn = dynamic_cast<THnSparse*>(fOutput->At(i));
if(hn)hn->Sumw2();
}
TH1::AddDirectory(oldStatus);
PostData(1, fOutput); // Post data for ALL output slots > 0 here.
}
//________________________________________________________________________
Bool_t AliAnalysisTaskJetMassResponseDet::Run()
{
// Run analysis code here, if needed. It will be executed before FillHistograms().
return kTRUE;
}
//________________________________________________________________________
Bool_t AliAnalysisTaskJetMassResponseDet::FillHistograms()
{
// Fill histograms.
AliJetContainer *cPart = GetJetContainer(fContainerPart);
AliJetContainer *cDet = GetJetContainer(fContainerDet);
AliEmcalJet* jPart = NULL;
AliEmcalJet* jDet = NULL;
//loop on particle level jets
if(cPart) {
cPart->ResetCurrentID();
while((jPart = cPart->GetNextAcceptJet())) {
fh2PtVsMassJetPartAll->Fill(jPart->Pt(),jPart->M());
jDet = jPart->ClosestJet();
if(jDet) fh2PtVsMassJetPartMatch->Fill(jPart->Pt(),jPart->M());
if(jPart->GetTagStatus()<1 || !jPart->GetTaggedJet())
continue;
fh2PtVsMassJetPartTagged->Fill(jPart->Pt(),jPart->M());
if(jDet) fh2PtVsMassJetPartTaggedMatch->Fill(jPart->Pt(),jPart->M());
}
}
//loop on detector level jets
if(cDet) {
cDet->ResetCurrentID();
while((jDet = cDet->GetNextAcceptJet())) {
Double_t mjet = GetJetMass(jDet);
fh2PtVsMassJetDetAll->Fill(jDet->Pt(),mjet);
if(jDet->GetTagStatus()>=1 && jDet->GetTaggedJet())
fh2PtVsMassJetDetTagged->Fill(jDet->Pt(),mjet);
//fill detector response
jPart = jDet->ClosestJet();
if(jPart) {
fh2EtaPhiMatchedDet->Fill(jDet->Eta(),jDet->Phi());
fh2EtaPhiMatchedPart->Fill(jPart->Eta(),jPart->Phi());
Int_t nConstPart = jPart->GetNumberOfConstituents();
Int_t nConstDet = jDet->GetNumberOfConstituents();
Double_t eff = -1.;
if(nConstPart>0) eff = (Double_t)nConstDet/((Double_t)nConstPart);
Double_t var[5] = {GetJetMass(jDet),jPart->M(),jDet->Pt(),jPart->Pt(),eff};
fhnMassResponse->Fill(var);
}
}
}
return kTRUE;
}
//________________________________________________________________________
Double_t AliAnalysisTaskJetMassResponseDet::GetJetMass(AliEmcalJet *jet) {
//calc subtracted jet mass
if(fJetMassType==kRaw)
return jet->M();
else if(fJetMassType==kDeriv)
return jet->GetSecondOrderSubtracted();
return 0;
}
//________________________________________________________________________
Bool_t AliAnalysisTaskJetMassResponseDet::RetrieveEventObjects() {
//
// retrieve event objects
if (!AliAnalysisTaskEmcalJet::RetrieveEventObjects())
return kFALSE;
return kTRUE;
}
//_______________________________________________________________________
void AliAnalysisTaskJetMassResponseDet::Terminate(Option_t *)
{
// Called once at the end of the analysis.
}
|
change histo filling fhnMassResponse
|
change histo filling fhnMassResponse
|
C++
|
bsd-3-clause
|
lcunquei/AliPhysics,rderradi/AliPhysics,pchrista/AliPhysics,dstocco/AliPhysics,AudreyFrancisco/AliPhysics,alisw/AliPhysics,pbuehler/AliPhysics,fbellini/AliPhysics,pbatzing/AliPhysics,fcolamar/AliPhysics,dstocco/AliPhysics,AMechler/AliPhysics,alisw/AliPhysics,yowatana/AliPhysics,pbuehler/AliPhysics,mazimm/AliPhysics,dstocco/AliPhysics,btrzecia/AliPhysics,aaniin/AliPhysics,ALICEHLT/AliPhysics,pbatzing/AliPhysics,btrzecia/AliPhysics,lcunquei/AliPhysics,hzanoli/AliPhysics,lfeldkam/AliPhysics,akubera/AliPhysics,AudreyFrancisco/AliPhysics,hzanoli/AliPhysics,mkrzewic/AliPhysics,sebaleh/AliPhysics,jgronefe/AliPhysics,adriansev/AliPhysics,SHornung1/AliPhysics,ALICEHLT/AliPhysics,fcolamar/AliPhysics,pbatzing/AliPhysics,rihanphys/AliPhysics,kreisl/AliPhysics,mvala/AliPhysics,ppribeli/AliPhysics,mpuccio/AliPhysics,mvala/AliPhysics,fbellini/AliPhysics,fcolamar/AliPhysics,btrzecia/AliPhysics,pbuehler/AliPhysics,rderradi/AliPhysics,amatyja/AliPhysics,amatyja/AliPhysics,aaniin/AliPhysics,AudreyFrancisco/AliPhysics,dlodato/AliPhysics,mbjadhav/AliPhysics,lcunquei/AliPhysics,sebaleh/AliPhysics,yowatana/AliPhysics,hzanoli/AliPhysics,mazimm/AliPhysics,victor-gonzalez/AliPhysics,pchrista/AliPhysics,mazimm/AliPhysics,preghenella/AliPhysics,kreisl/AliPhysics,pchrista/AliPhysics,yowatana/AliPhysics,SHornung1/AliPhysics,preghenella/AliPhysics,sebaleh/AliPhysics,akubera/AliPhysics,rihanphys/AliPhysics,adriansev/AliPhysics,jmargutt/AliPhysics,lfeldkam/AliPhysics,AMechler/AliPhysics,aaniin/AliPhysics,lfeldkam/AliPhysics,dlodato/AliPhysics,fbellini/AliPhysics,carstooon/AliPhysics,adriansev/AliPhysics,rderradi/AliPhysics,lfeldkam/AliPhysics,aaniin/AliPhysics,yowatana/AliPhysics,pbuehler/AliPhysics,jmargutt/AliPhysics,fcolamar/AliPhysics,yowatana/AliPhysics,mpuccio/AliPhysics,lcunquei/AliPhysics,alisw/AliPhysics,amatyja/AliPhysics,mkrzewic/AliPhysics,fbellini/AliPhysics,dstocco/AliPhysics,adriansev/AliPhysics,hzanoli/AliPhysics,dlodato/AliPhysics,jgronefe/AliPhysics,hcab14/AliPhysics,rbailhac/AliPhysics,carstooon/AliPhysics,pbatzing/AliPhysics,hcab14/AliPhysics,mbjadhav/AliPhysics,jgronefe/AliPhysics,kreisl/AliPhysics,lfeldkam/AliPhysics,AMechler/AliPhysics,AudreyFrancisco/AliPhysics,sebaleh/AliPhysics,ppribeli/AliPhysics,hcab14/AliPhysics,carstooon/AliPhysics,btrzecia/AliPhysics,kreisl/AliPhysics,rbailhac/AliPhysics,alisw/AliPhysics,ALICEHLT/AliPhysics,hzanoli/AliPhysics,mbjadhav/AliPhysics,dmuhlhei/AliPhysics,kreisl/AliPhysics,carstooon/AliPhysics,amaringarcia/AliPhysics,pchrista/AliPhysics,alisw/AliPhysics,amaringarcia/AliPhysics,rderradi/AliPhysics,dmuhlhei/AliPhysics,dlodato/AliPhysics,nschmidtALICE/AliPhysics,preghenella/AliPhysics,dstocco/AliPhysics,ppribeli/AliPhysics,amaringarcia/AliPhysics,lfeldkam/AliPhysics,jgronefe/AliPhysics,mbjadhav/AliPhysics,pbuehler/AliPhysics,aaniin/AliPhysics,AMechler/AliPhysics,victor-gonzalez/AliPhysics,rihanphys/AliPhysics,fcolamar/AliPhysics,jgronefe/AliPhysics,dmuhlhei/AliPhysics,rihanphys/AliPhysics,dmuhlhei/AliPhysics,ppribeli/AliPhysics,mvala/AliPhysics,rbailhac/AliPhysics,amatyja/AliPhysics,pchrista/AliPhysics,mkrzewic/AliPhysics,dmuhlhei/AliPhysics,akubera/AliPhysics,sebaleh/AliPhysics,amatyja/AliPhysics,pbuehler/AliPhysics,ppribeli/AliPhysics,preghenella/AliPhysics,preghenella/AliPhysics,AMechler/AliPhysics,rderradi/AliPhysics,amatyja/AliPhysics,mpuccio/AliPhysics,nschmidtALICE/AliPhysics,mkrzewic/AliPhysics,adriansev/AliPhysics,kreisl/AliPhysics,amaringarcia/AliPhysics,mazimm/AliPhysics,hcab14/AliPhysics,jmargutt/AliPhysics,AMechler/AliPhysics,preghenella/AliPhysics,victor-gonzalez/AliPhysics,jmargutt/AliPhysics,fbellini/AliPhysics,nschmidtALICE/AliPhysics,nschmidtALICE/AliPhysics,jgronefe/AliPhysics,dlodato/AliPhysics,aaniin/AliPhysics,AudreyFrancisco/AliPhysics,hcab14/AliPhysics,alisw/AliPhysics,ppribeli/AliPhysics,SHornung1/AliPhysics,carstooon/AliPhysics,mvala/AliPhysics,nschmidtALICE/AliPhysics,SHornung1/AliPhysics,victor-gonzalez/AliPhysics,pbatzing/AliPhysics,nschmidtALICE/AliPhysics,victor-gonzalez/AliPhysics,mbjadhav/AliPhysics,dmuhlhei/AliPhysics,dstocco/AliPhysics,pbuehler/AliPhysics,mazimm/AliPhysics,rihanphys/AliPhysics,btrzecia/AliPhysics,carstooon/AliPhysics,fcolamar/AliPhysics,jmargutt/AliPhysics,lcunquei/AliPhysics,lcunquei/AliPhysics,mazimm/AliPhysics,akubera/AliPhysics,SHornung1/AliPhysics,victor-gonzalez/AliPhysics,adriansev/AliPhysics,akubera/AliPhysics,amaringarcia/AliPhysics,ALICEHLT/AliPhysics,mbjadhav/AliPhysics,rbailhac/AliPhysics,yowatana/AliPhysics,mvala/AliPhysics,amaringarcia/AliPhysics,mkrzewic/AliPhysics,rbailhac/AliPhysics,akubera/AliPhysics,mpuccio/AliPhysics,adriansev/AliPhysics,fbellini/AliPhysics,mvala/AliPhysics,rderradi/AliPhysics,btrzecia/AliPhysics,mkrzewic/AliPhysics,fbellini/AliPhysics,pbatzing/AliPhysics,AMechler/AliPhysics,pbatzing/AliPhysics,mpuccio/AliPhysics,ALICEHLT/AliPhysics,pchrista/AliPhysics,hcab14/AliPhysics,rderradi/AliPhysics,sebaleh/AliPhysics,hzanoli/AliPhysics,akubera/AliPhysics,dstocco/AliPhysics,jmargutt/AliPhysics,aaniin/AliPhysics,AudreyFrancisco/AliPhysics,btrzecia/AliPhysics,mazimm/AliPhysics,hcab14/AliPhysics,lcunquei/AliPhysics,ALICEHLT/AliPhysics,mkrzewic/AliPhysics,mvala/AliPhysics,rihanphys/AliPhysics,alisw/AliPhysics,SHornung1/AliPhysics,pchrista/AliPhysics,ALICEHLT/AliPhysics,jgronefe/AliPhysics,amatyja/AliPhysics,mpuccio/AliPhysics,nschmidtALICE/AliPhysics,rbailhac/AliPhysics,ppribeli/AliPhysics,mpuccio/AliPhysics,kreisl/AliPhysics,yowatana/AliPhysics,hzanoli/AliPhysics,SHornung1/AliPhysics,dlodato/AliPhysics,rbailhac/AliPhysics,lfeldkam/AliPhysics,sebaleh/AliPhysics,amaringarcia/AliPhysics,rihanphys/AliPhysics,jmargutt/AliPhysics,AudreyFrancisco/AliPhysics,preghenella/AliPhysics,dlodato/AliPhysics,fcolamar/AliPhysics,carstooon/AliPhysics,mbjadhav/AliPhysics,dmuhlhei/AliPhysics,victor-gonzalez/AliPhysics
|
bf4f0b0adcc170e326c92f9534228e57439eee4c
|
server/src/unittest/gpopt/operators/CScalarIsDistinctFromTest.cpp
|
server/src/unittest/gpopt/operators/CScalarIsDistinctFromTest.cpp
|
#include "unittest/gpopt/operators/CScalarIsDistinctFromTest.h"
#include "gpos/common/CDynamicPtrArray.h"
#include "gpopt/operators/CScalarIsDistinctFrom.h"
#include "gpos/string/CWStringConst.h"
#include "unittest/gpopt/CTestUtils.h"
namespace gpopt
{
using namespace gpos;
class SEberFixture
{
private:
CAutoMemoryPool m_amp;
CMDAccessor m_mda;
CAutoOptCtxt m_aoc;
CScalarIsDistinctFrom* m_pScalarIDF;
public:
SEberFixture():
m_mda(m_amp.Pmp(), CMDCache::Pcache(), CTestUtils::m_sysidDefault, CTestUtils::m_pmdpf),
m_aoc(m_amp.Pmp(), &m_mda, NULL /* pceeval */, CTestUtils::Pcm(m_amp.Pmp()))
{
CMDIdGPDB *pmdidEqOp = GPOS_NEW(m_amp.Pmp()) CMDIdGPDB(GPDB_INT4_EQ_OP);
const CWStringConst *pwsOpName = GPOS_NEW(Pmp()) CWStringConst(GPOS_WSZ_LIT("="));
m_pScalarIDF = GPOS_NEW(m_amp.Pmp()) CScalarIsDistinctFrom
(Pmp(),
pmdidEqOp,
pwsOpName
);
CTestUtils::m_pmdpf->AddRef();
}
~SEberFixture()
{
m_pScalarIDF->Release();
}
IMemoryPool* Pmp() const
{
return m_amp.Pmp();
}
CScalarIsDistinctFrom *PScalarIDF() const
{
return m_pScalarIDF;
}
};
static GPOS_RESULT EresUnittest_Eber_WhenBothInputsAreNull()
{
SEberFixture fixture;
IMemoryPool *pmp = fixture.Pmp();
DrgPul *pdrgpulChildren = GPOS_NEW(pmp) DrgPul(pmp);
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberNull));
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberNull));
CScalarIsDistinctFrom *pScalarIDF = fixture.PScalarIDF();
CScalar::EBoolEvalResult eberResult = pScalarIDF->Eber(pdrgpulChildren);
GPOS_RTL_ASSERT(eberResult == CScalar::EberFalse);
pdrgpulChildren->Release();
return GPOS_OK;
}
static GPOS_RESULT EresUnittest_Eber_WhenFirstInputIsUnknown()
{
SEberFixture fixture;
IMemoryPool *pmp = fixture.Pmp();
DrgPul *pdrgpulChildren = GPOS_NEW(pmp) DrgPul(pmp);
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberUnknown));
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberNull));
CScalarIsDistinctFrom *pScalarIDF = fixture.PScalarIDF();
CScalar::EBoolEvalResult eberResult = pScalarIDF->Eber(pdrgpulChildren);
GPOS_RTL_ASSERT(eberResult == CScalar::EberUnknown);
pdrgpulChildren->Release();
return GPOS_OK;
}
static GPOS_RESULT EresUnittest_Eber_WhenSecondInputIsUnknown()
{
SEberFixture fixture;
IMemoryPool *pmp = fixture.Pmp();
DrgPul *pdrgpulChildren = GPOS_NEW(pmp) DrgPul(pmp);
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberNull));
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberUnknown));
CScalarIsDistinctFrom *pScalarIDF = fixture.PScalarIDF();
CScalar::EBoolEvalResult eberResult = pScalarIDF->Eber(pdrgpulChildren);
GPOS_RTL_ASSERT(eberResult == CScalar::EberUnknown);
pdrgpulChildren->Release();
return GPOS_OK;
}
static GPOS_RESULT EresUnittest_Eber_WhenFirstInputDiffersFromSecondInput()
{
SEberFixture fixture;
IMemoryPool *pmp = fixture.Pmp();
DrgPul *pdrgpulChildren = GPOS_NEW(pmp) DrgPul(pmp);
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberNull));
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberTrue));
CScalarIsDistinctFrom *pScalarIDF = fixture.PScalarIDF();
CScalar::EBoolEvalResult eberResult = pScalarIDF->Eber(pdrgpulChildren);
GPOS_RTL_ASSERT(eberResult == CScalar::EberTrue);
pdrgpulChildren->Release();
return GPOS_OK;
}
static GPOS_RESULT EresUnittest_Eber_WhenBothInputsAreSameAndNotNull()
{
SEberFixture fixture;
IMemoryPool *pmp = fixture.Pmp();
DrgPul *pdrgpulChildren = GPOS_NEW(pmp) DrgPul(pmp);
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberTrue));
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberTrue));
CScalarIsDistinctFrom *pScalarIDF = fixture.PScalarIDF();
CScalar::EBoolEvalResult eberResult = pScalarIDF->Eber(pdrgpulChildren);
GPOS_RTL_ASSERT(eberResult == CScalar::EberFalse);
pdrgpulChildren->Release();
return GPOS_OK;
}
GPOS_RESULT CScalarIsDistinctFromTest::EresUnittest()
{
CUnittest rgut[] =
{
GPOS_UNITTEST_FUNC(EresUnittest_Eber_WhenBothInputsAreNull),
GPOS_UNITTEST_FUNC(EresUnittest_Eber_WhenFirstInputIsUnknown),
GPOS_UNITTEST_FUNC(EresUnittest_Eber_WhenSecondInputIsUnknown),
GPOS_UNITTEST_FUNC(EresUnittest_Eber_WhenFirstInputDiffersFromSecondInput),
GPOS_UNITTEST_FUNC(EresUnittest_Eber_WhenBothInputsAreSameAndNotNull),
};
return CUnittest::EresExecute(rgut, GPOS_ARRAY_SIZE(rgut));
}
}
|
#include "unittest/gpopt/operators/CScalarIsDistinctFromTest.h"
#include "gpos/common/CDynamicPtrArray.h"
#include "gpopt/operators/CScalarIsDistinctFrom.h"
#include "gpos/string/CWStringConst.h"
#include "unittest/gpopt/CTestUtils.h"
namespace gpopt
{
using namespace gpos;
class SEberFixture
{
private:
const CAutoMemoryPool m_amp;
CMDAccessor m_mda;
const CAutoOptCtxt m_aoc;
CScalarIsDistinctFrom* const m_pScalarIDF;
static IMDProvider* Pmdp()
{
CTestUtils::m_pmdpf->AddRef();
return CTestUtils::m_pmdpf;
}
public:
SEberFixture():
m_amp(),
m_mda(m_amp.Pmp(), CMDCache::Pcache(), CTestUtils::m_sysidDefault, Pmdp()),
m_aoc(m_amp.Pmp(), &m_mda, NULL /* pceeval */, CTestUtils::Pcm(m_amp.Pmp())),
m_pScalarIDF(GPOS_NEW(m_amp.Pmp()) CScalarIsDistinctFrom(
Pmp(),
GPOS_NEW(m_amp.Pmp()) CMDIdGPDB(GPDB_INT4_EQ_OP),
GPOS_NEW(m_amp.Pmp()) CWStringConst(GPOS_WSZ_LIT("="))
))
{
}
~SEberFixture()
{
m_pScalarIDF->Release();
}
IMemoryPool* Pmp() const
{
return m_amp.Pmp();
}
CScalarIsDistinctFrom *PScalarIDF() const
{
return m_pScalarIDF;
}
};
static GPOS_RESULT EresUnittest_Eber_WhenBothInputsAreNull()
{
SEberFixture fixture;
IMemoryPool *pmp = fixture.Pmp();
DrgPul *pdrgpulChildren = GPOS_NEW(pmp) DrgPul(pmp);
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberNull));
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberNull));
CScalarIsDistinctFrom *pScalarIDF = fixture.PScalarIDF();
CScalar::EBoolEvalResult eberResult = pScalarIDF->Eber(pdrgpulChildren);
GPOS_RTL_ASSERT(eberResult == CScalar::EberFalse);
pdrgpulChildren->Release();
return GPOS_OK;
}
static GPOS_RESULT EresUnittest_Eber_WhenFirstInputIsUnknown()
{
SEberFixture fixture;
IMemoryPool *pmp = fixture.Pmp();
DrgPul *pdrgpulChildren = GPOS_NEW(pmp) DrgPul(pmp);
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberUnknown));
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberNull));
CScalarIsDistinctFrom *pScalarIDF = fixture.PScalarIDF();
CScalar::EBoolEvalResult eberResult = pScalarIDF->Eber(pdrgpulChildren);
GPOS_RTL_ASSERT(eberResult == CScalar::EberUnknown);
pdrgpulChildren->Release();
return GPOS_OK;
}
static GPOS_RESULT EresUnittest_Eber_WhenSecondInputIsUnknown()
{
SEberFixture fixture;
IMemoryPool *pmp = fixture.Pmp();
DrgPul *pdrgpulChildren = GPOS_NEW(pmp) DrgPul(pmp);
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberNull));
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberUnknown));
CScalarIsDistinctFrom *pScalarIDF = fixture.PScalarIDF();
CScalar::EBoolEvalResult eberResult = pScalarIDF->Eber(pdrgpulChildren);
GPOS_RTL_ASSERT(eberResult == CScalar::EberUnknown);
pdrgpulChildren->Release();
return GPOS_OK;
}
static GPOS_RESULT EresUnittest_Eber_WhenFirstInputDiffersFromSecondInput()
{
SEberFixture fixture;
IMemoryPool *pmp = fixture.Pmp();
DrgPul *pdrgpulChildren = GPOS_NEW(pmp) DrgPul(pmp);
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberNull));
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberTrue));
CScalarIsDistinctFrom *pScalarIDF = fixture.PScalarIDF();
CScalar::EBoolEvalResult eberResult = pScalarIDF->Eber(pdrgpulChildren);
GPOS_RTL_ASSERT(eberResult == CScalar::EberTrue);
pdrgpulChildren->Release();
return GPOS_OK;
}
static GPOS_RESULT EresUnittest_Eber_WhenBothInputsAreSameAndNotNull()
{
SEberFixture fixture;
IMemoryPool *pmp = fixture.Pmp();
DrgPul *pdrgpulChildren = GPOS_NEW(pmp) DrgPul(pmp);
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberTrue));
pdrgpulChildren->Append(GPOS_NEW(pmp) ULONG(CScalar::EberTrue));
CScalarIsDistinctFrom *pScalarIDF = fixture.PScalarIDF();
CScalar::EBoolEvalResult eberResult = pScalarIDF->Eber(pdrgpulChildren);
GPOS_RTL_ASSERT(eberResult == CScalar::EberFalse);
pdrgpulChildren->Release();
return GPOS_OK;
}
GPOS_RESULT CScalarIsDistinctFromTest::EresUnittest()
{
CUnittest rgut[] =
{
GPOS_UNITTEST_FUNC(EresUnittest_Eber_WhenBothInputsAreNull),
GPOS_UNITTEST_FUNC(EresUnittest_Eber_WhenFirstInputIsUnknown),
GPOS_UNITTEST_FUNC(EresUnittest_Eber_WhenSecondInputIsUnknown),
GPOS_UNITTEST_FUNC(EresUnittest_Eber_WhenFirstInputDiffersFromSecondInput),
GPOS_UNITTEST_FUNC(EresUnittest_Eber_WhenBothInputsAreSameAndNotNull),
};
return CUnittest::EresExecute(rgut, GPOS_ARRAY_SIZE(rgut));
}
}
|
Refactor test fixture
|
Refactor test fixture
Signed-off-by: Ekta Khanna <[email protected]>
|
C++
|
apache-2.0
|
adam8157/gpdb,adam8157/gpdb,lisakowen/gpdb,xinzweb/gpdb,50wu/gpdb,50wu/gpdb,greenplum-db/gpdb,greenplum-db/gpdb,adam8157/gpdb,jmcatamney/gpdb,jmcatamney/gpdb,greenplum-db/gporca,greenplum-db/gpdb,xinzweb/gpdb,lisakowen/gpdb,greenplum-db/gpdb,lisakowen/gpdb,greenplum-db/gporca,lisakowen/gpdb,50wu/gpdb,jmcatamney/gpdb,50wu/gpdb,lisakowen/gpdb,xinzweb/gpdb,50wu/gpdb,greenplum-db/gpdb,greenplum-db/gporca,adam8157/gpdb,50wu/gpdb,50wu/gpdb,greenplum-db/gporca,xinzweb/gpdb,adam8157/gpdb,xinzweb/gpdb,jmcatamney/gpdb,greenplum-db/gpdb,jmcatamney/gpdb,greenplum-db/gpdb,jmcatamney/gpdb,xinzweb/gpdb,xinzweb/gpdb,lisakowen/gpdb,lisakowen/gpdb,50wu/gpdb,jmcatamney/gpdb,jmcatamney/gpdb,adam8157/gpdb,xinzweb/gpdb,lisakowen/gpdb,adam8157/gpdb,greenplum-db/gpdb,adam8157/gpdb
|
142e999fd0e4671bb6c042e7725b230421cac4aa
|
setup_native/source/win32/customactions/regactivex/regactivex.cxx
|
setup_native/source/win32/customactions/regactivex/regactivex.cxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#define UNICODE
#ifdef _MSC_VER
#pragma warning(push, 1) /* disable warnings within system headers */
#endif
#include <windows.h>
#include <msiquery.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <string.h>
#include <malloc.h>
#define CHART_COMPONENT 1
#define DRAW_COMPONENT 2
#define IMPRESS_COMPONENT 4
#define CALC_COMPONENT 8
#define WRITER_COMPONENT 16
#define MATH_COMPONENT 32
// #define OWN_DEBUG_PRINT
typedef int ( __stdcall * DllNativeRegProc ) ( int, BOOL, BOOL, const char* );
typedef int ( __stdcall * DllNativeUnregProc ) ( int, BOOL, BOOL );
BOOL UnicodeEquals( wchar_t* pStr1, wchar_t* pStr2 )
{
if ( pStr1 == NULL && pStr2 == NULL )
return TRUE;
else if ( pStr1 == NULL || pStr2 == NULL )
return FALSE;
while( *pStr1 == *pStr2 && *pStr1 && *pStr2 )
pStr1++, pStr2++;
return ( *pStr1 == 0 && *pStr2 == 0 );
}
//----------------------------------------------------------
char* UnicodeToAnsiString( wchar_t* pUniString )
{
int len = WideCharToMultiByte(
CP_ACP, 0, pUniString, -1, 0, 0, 0, 0 );
char* buff = reinterpret_cast<char*>( malloc( len ) );
WideCharToMultiByte(
CP_ACP, 0, pUniString, -1, buff, len, 0, 0 );
return buff;
}
#ifdef OWN_DEBUG_PRINT
void WarningMessageInt( wchar_t* pWarning, unsigned int nValue )
{
wchar_t pStr[5] = { nValue%10000/1000 + 48, nValue%1000/100 + 48, nValue%100/10 + 48, nValue%10 + 48, 0 };
MessageBox(NULL, pStr, pWarning, MB_OK | MB_ICONINFORMATION);
}
#endif
//----------------------------------------------------------
void RegisterActiveXNative( const char* pActiveXPath, int nMode, BOOL InstallForAllUser, BOOL InstallFor64Bit )
{
#ifdef OWN_DEBUG_PRINT
MessageBoxW(NULL, L"RegisterActiveXNative", L"Information", MB_OK | MB_ICONINFORMATION);
MessageBoxA(NULL, pActiveXPath, "Library Path", MB_OK | MB_ICONINFORMATION);
#endif
// For Win98/WinME the values should be written to the local machine
OSVERSIONINFO aVerInfo;
aVerInfo.dwOSVersionInfoSize = sizeof( aVerInfo );
if ( GetVersionEx( &aVerInfo ) && aVerInfo.dwPlatformId != VER_PLATFORM_WIN32_NT )
InstallForAllUser = TRUE;
HINSTANCE hModule = LoadLibraryExA( pActiveXPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH );
if( !( hModule <= ( HINSTANCE )HINSTANCE_ERROR ) )
{
DllNativeRegProc pNativeProc = ( DllNativeRegProc )GetProcAddress( hModule, "DllRegisterServerNative" );
if( pNativeProc!=NULL )
{
#ifdef OWN_DEBUG_PRINT
MessageBoxA(NULL, pActiveXPath, "Library Path", MB_OK | MB_ICONINFORMATION);
#endif
int nLen = strlen( pActiveXPath );
int nRemoveLen = strlen( "\\so_activex.dll" );
if ( nLen > nRemoveLen )
{
char* pProgramPath = reinterpret_cast<char*>( malloc( nLen - nRemoveLen + 1 ) );
strncpy( pProgramPath, pActiveXPath, nLen - nRemoveLen );
pProgramPath[ nLen - nRemoveLen ] = 0;
( *pNativeProc )( nMode, InstallForAllUser, InstallFor64Bit, pProgramPath );
free( pProgramPath );
}
}
FreeLibrary( hModule );
}
}
//----------------------------------------------------------
void UnregisterActiveXNative( const char* pActiveXPath, int nMode, BOOL InstallForAllUser, BOOL InstallFor64Bit )
{
// For Win98/WinME the values should be written to the local machine
OSVERSIONINFO aVerInfo;
aVerInfo.dwOSVersionInfoSize = sizeof( aVerInfo );
if ( GetVersionEx( &aVerInfo ) && aVerInfo.dwPlatformId != VER_PLATFORM_WIN32_NT )
InstallForAllUser = TRUE;
HINSTANCE hModule = LoadLibraryExA( pActiveXPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH );
if( !( hModule <= ( HINSTANCE )HINSTANCE_ERROR ) )
{
DllNativeUnregProc pNativeProc = ( DllNativeUnregProc )GetProcAddress( hModule, "DllUnregisterServerNative" );
if( pNativeProc!=NULL )
( *pNativeProc )( nMode, InstallForAllUser, InstallFor64Bit );
FreeLibrary( hModule );
}
}
//----------------------------------------------------------
BOOL GetMsiProp( MSIHANDLE hMSI, const wchar_t* pPropName, wchar_t** ppValue )
{
DWORD sz = 0;
if ( MsiGetProperty( hMSI, pPropName, L"", &sz ) == ERROR_MORE_DATA )
{
sz++;
DWORD nbytes = sz * sizeof( wchar_t );
wchar_t* buff = reinterpret_cast<wchar_t*>( malloc( nbytes ) );
ZeroMemory( buff, nbytes );
MsiGetProperty( hMSI, pPropName, buff, &sz );
*ppValue = buff;
return TRUE;
}
return FALSE;
}
//----------------------------------------------------------
BOOL GetActiveXControlPath( MSIHANDLE hMSI, char** ppActiveXPath )
{
wchar_t* pProgPath = NULL;
if ( GetMsiProp( hMSI, L"INSTALLLOCATION", &pProgPath ) && pProgPath )
{
char* pCharProgPath = UnicodeToAnsiString( pProgPath );
#ifdef OWN_DEBUG_PRINT
MessageBox(NULL, pProgPath, L"Basis Installation Path", MB_OK | MB_ICONINFORMATION);
MessageBoxA(NULL, pCharProgPath, "Basis Installation Path( char )", MB_OK | MB_ICONINFORMATION);
#endif
if ( pCharProgPath )
{
int nLen = strlen( pCharProgPath );
*ppActiveXPath = reinterpret_cast<char*>( malloc( nLen + 23 ) );
strncpy( *ppActiveXPath, pCharProgPath, nLen );
strncpy( (*ppActiveXPath) + nLen, "program\\so_activex.dll", 22 );
(*ppActiveXPath)[nLen+22] = 0;
free( pCharProgPath );
return TRUE;
}
free( pProgPath );
}
return FALSE;
}
//----------------------------------------------------------
BOOL GetDelta( MSIHANDLE hMSI, int& nOldInstallMode, int& nInstallMode, int& nDeinstallMode )
{
// for now the chart is always installed
nOldInstallMode = CHART_COMPONENT;
nInstallMode = CHART_COMPONENT;
nDeinstallMode = 0;
INSTALLSTATE current_state;
INSTALLSTATE future_state;
if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Wrt_Bin", ¤t_state, &future_state ) )
{
#ifdef OWN_DEBUG_PRINT
WarningMessageInt( L"writer current_state = ", current_state );
WarningMessageInt( L"writer future_state = ", future_state );
#endif
// analyze writer installation mode
if ( current_state == INSTALLSTATE_LOCAL )
nOldInstallMode |= WRITER_COMPONENT;
if ( future_state == INSTALLSTATE_LOCAL
|| ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_UNKNOWN ) )
nInstallMode |= WRITER_COMPONENT;
else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT )
nDeinstallMode |= WRITER_COMPONENT;
}
else
{
// assert( FALSE );
}
if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Calc_Bin", ¤t_state, &future_state ) )
{
#ifdef OWN_DEBUG_PRINT
WarningMessageInt( L"calc current_state = ", current_state );
WarningMessageInt( L"calc future_state = ", future_state );
#endif
// analyze calc installation mode
if ( current_state == INSTALLSTATE_LOCAL )
nOldInstallMode |= CALC_COMPONENT;
if ( future_state == INSTALLSTATE_LOCAL
|| ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_UNKNOWN ) )
nInstallMode |= CALC_COMPONENT;
else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT )
nDeinstallMode |= CALC_COMPONENT;
}
else
{
// assert( FALSE );
}
if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Draw_Bin", ¤t_state, &future_state ) )
{
// analyze draw installation mode
if ( current_state == INSTALLSTATE_LOCAL )
nOldInstallMode |= DRAW_COMPONENT;
if ( future_state == INSTALLSTATE_LOCAL
|| ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_UNKNOWN ) )
nInstallMode |= DRAW_COMPONENT;
else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT )
nDeinstallMode |= DRAW_COMPONENT;
}
else
{
// assert( FALSE );
}
if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Impress_Bin", ¤t_state, &future_state ) )
{
// analyze impress installation mode
if ( current_state == INSTALLSTATE_LOCAL )
nOldInstallMode |= IMPRESS_COMPONENT;
if ( future_state == INSTALLSTATE_LOCAL
|| ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_UNKNOWN ) )
nInstallMode |= IMPRESS_COMPONENT;
else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT )
nDeinstallMode |= IMPRESS_COMPONENT;
}
else
{
// assert( FALSE );
}
if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Math_Bin", ¤t_state, &future_state ) )
{
// analyze math installation mode
if ( current_state == INSTALLSTATE_LOCAL )
nOldInstallMode |= MATH_COMPONENT;
if ( future_state == INSTALLSTATE_LOCAL
|| ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_UNKNOWN ) )
nInstallMode |= MATH_COMPONENT;
else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT )
nDeinstallMode |= MATH_COMPONENT;
}
else
{
// assert( FALSE );
}
return TRUE;
}
//----------------------------------------------------------
BOOL MakeInstallForAllUsers( MSIHANDLE hMSI )
{
BOOL bResult = FALSE;
wchar_t* pVal = NULL;
if ( GetMsiProp( hMSI, L"ALLUSERS", &pVal ) && pVal )
{
bResult = UnicodeEquals( pVal , L"1" );
free( pVal );
}
return bResult;
}
//----------------------------------------------------------
BOOL MakeInstallFor64Bit( MSIHANDLE hMSI )
{
BOOL bResult = FALSE;
wchar_t* pVal = NULL;
if ( GetMsiProp( hMSI, L"VersionNT64", &pVal ) && pVal )
{
bResult = TRUE;
free( pVal );
}
return bResult;
}
//----------------------------------------------------------
extern "C" UINT __stdcall InstallActiveXControl( MSIHANDLE hMSI )
{
int nOldInstallMode = 0;
int nInstallMode = 0;
int nDeinstallMode = 0;
#ifdef OWN_DEBUG_PRINT
MessageBox(NULL, L"InstallActiveXControl", L"Information", MB_OK | MB_ICONINFORMATION);
#endif
INSTALLSTATE current_state;
INSTALLSTATE future_state;
if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_o_Activexcontrol", ¤t_state, &future_state ) )
{
#ifdef OWN_DEBUG_PRINT
MessageBox(NULL, L"InstallActiveXControl Step2", L"Information", MB_OK | MB_ICONINFORMATION);
#endif
BOOL bInstallForAllUser = MakeInstallForAllUsers( hMSI );
BOOL bInstallFor64Bit = MakeInstallFor64Bit( hMSI );
char* pActiveXPath = NULL;
if ( GetActiveXControlPath( hMSI, &pActiveXPath ) && pActiveXPath
&& GetDelta( hMSI, nOldInstallMode, nInstallMode, nDeinstallMode ) )
{
#ifdef OWN_DEBUG_PRINT
MessageBox(NULL, L"InstallActiveXControl Step3", L"Information", MB_OK | MB_ICONINFORMATION);
#endif
if ( future_state == INSTALLSTATE_LOCAL
|| ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_UNKNOWN ) )
{
#ifdef OWN_DEBUG_PRINT
MessageBox(NULL, L"InstallActiveXControl, adjusting", L"Information", MB_OK | MB_ICONINFORMATION);
WarningMessageInt( L"nInstallMode = ", nInstallMode );
#endif
// the control is installed in the new selected configuration
if ( current_state == INSTALLSTATE_LOCAL && nDeinstallMode )
UnregisterActiveXNative( pActiveXPath, nDeinstallMode, bInstallForAllUser, bInstallFor64Bit );
if ( nInstallMode )
RegisterActiveXNative( pActiveXPath, nInstallMode, bInstallForAllUser, bInstallFor64Bit );
}
else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT )
{
#ifdef OWN_DEBUG_PRINT
MessageBox(NULL, L"InstallActiveXControl, removing", L"Information", MB_OK | MB_ICONINFORMATION);
#endif
if ( nOldInstallMode )
UnregisterActiveXNative( pActiveXPath, nOldInstallMode, bInstallForAllUser, bInstallFor64Bit );
}
}
if ( pActiveXPath )
free( pActiveXPath );
}
else
{
// assert( FALSE );
}
return ERROR_SUCCESS;
}
//----------------------------------------------------------
extern "C" UINT __stdcall DeinstallActiveXControl( MSIHANDLE hMSI )
{
INSTALLSTATE current_state;
INSTALLSTATE future_state;
#ifdef OWN_DEBUG_PRINT
MessageBox(NULL, L"DeinstallActiveXControl", L"Information", MB_OK | MB_ICONINFORMATION);
#endif
if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_o_Activexcontrol", ¤t_state, &future_state ) )
{
char* pActiveXPath = NULL;
if ( current_state == INSTALLSTATE_LOCAL && GetActiveXControlPath( hMSI, &pActiveXPath ) && pActiveXPath )
{
BOOL bInstallForAllUser = MakeInstallForAllUsers( hMSI );
BOOL bInstallFor64Bit = MakeInstallFor64Bit( hMSI );
{
UnregisterActiveXNative( pActiveXPath,
CHART_COMPONENT
| DRAW_COMPONENT
| IMPRESS_COMPONENT
| CALC_COMPONENT
| WRITER_COMPONENT
| MATH_COMPONENT,
bInstallForAllUser,
bInstallFor64Bit );
}
free( pActiveXPath );
}
}
return ERROR_SUCCESS;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#define UNICODE
#ifdef _MSC_VER
#pragma warning(push, 1) /* disable warnings within system headers */
#endif
#include <windows.h>
#include <msiquery.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <string.h>
#include <malloc.h>
#define CHART_COMPONENT 1
#define DRAW_COMPONENT 2
#define IMPRESS_COMPONENT 4
#define CALC_COMPONENT 8
#define WRITER_COMPONENT 16
#define MATH_COMPONENT 32
typedef int ( __stdcall * DllNativeRegProc ) ( int, BOOL, BOOL, const char* );
typedef int ( __stdcall * DllNativeUnregProc ) ( int, BOOL, BOOL );
BOOL UnicodeEquals( wchar_t* pStr1, wchar_t* pStr2 )
{
if ( pStr1 == NULL && pStr2 == NULL )
return TRUE;
else if ( pStr1 == NULL || pStr2 == NULL )
return FALSE;
while( *pStr1 == *pStr2 && *pStr1 && *pStr2 )
pStr1++, pStr2++;
return ( *pStr1 == 0 && *pStr2 == 0 );
}
//----------------------------------------------------------
char* UnicodeToAnsiString( wchar_t* pUniString )
{
int len = WideCharToMultiByte(
CP_ACP, 0, pUniString, -1, 0, 0, 0, 0 );
char* buff = reinterpret_cast<char*>( malloc( len ) );
WideCharToMultiByte(
CP_ACP, 0, pUniString, -1, buff, len, 0, 0 );
return buff;
}
//----------------------------------------------------------
void RegisterActiveXNative( const char* pActiveXPath, int nMode, BOOL InstallForAllUser, BOOL InstallFor64Bit )
{
// For Win98/WinME the values should be written to the local machine
OSVERSIONINFO aVerInfo;
aVerInfo.dwOSVersionInfoSize = sizeof( aVerInfo );
if ( GetVersionEx( &aVerInfo ) && aVerInfo.dwPlatformId != VER_PLATFORM_WIN32_NT )
InstallForAllUser = TRUE;
HINSTANCE hModule = LoadLibraryExA( pActiveXPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH );
if( !( hModule <= ( HINSTANCE )HINSTANCE_ERROR ) )
{
DllNativeRegProc pNativeProc = ( DllNativeRegProc )GetProcAddress( hModule, "DllRegisterServerNative" );
if( pNativeProc!=NULL )
{
int nLen = strlen( pActiveXPath );
int nRemoveLen = strlen( "\\so_activex.dll" );
if ( nLen > nRemoveLen )
{
char* pProgramPath = reinterpret_cast<char*>( malloc( nLen - nRemoveLen + 1 ) );
strncpy( pProgramPath, pActiveXPath, nLen - nRemoveLen );
pProgramPath[ nLen - nRemoveLen ] = 0;
( *pNativeProc )( nMode, InstallForAllUser, InstallFor64Bit, pProgramPath );
free( pProgramPath );
}
}
FreeLibrary( hModule );
}
}
//----------------------------------------------------------
void UnregisterActiveXNative( const char* pActiveXPath, int nMode, BOOL InstallForAllUser, BOOL InstallFor64Bit )
{
// For Win98/WinME the values should be written to the local machine
OSVERSIONINFO aVerInfo;
aVerInfo.dwOSVersionInfoSize = sizeof( aVerInfo );
if ( GetVersionEx( &aVerInfo ) && aVerInfo.dwPlatformId != VER_PLATFORM_WIN32_NT )
InstallForAllUser = TRUE;
HINSTANCE hModule = LoadLibraryExA( pActiveXPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH );
if( !( hModule <= ( HINSTANCE )HINSTANCE_ERROR ) )
{
DllNativeUnregProc pNativeProc = ( DllNativeUnregProc )GetProcAddress( hModule, "DllUnregisterServerNative" );
if( pNativeProc!=NULL )
( *pNativeProc )( nMode, InstallForAllUser, InstallFor64Bit );
FreeLibrary( hModule );
}
}
//----------------------------------------------------------
BOOL GetMsiProp( MSIHANDLE hMSI, const wchar_t* pPropName, wchar_t** ppValue )
{
DWORD sz = 0;
if ( MsiGetProperty( hMSI, pPropName, L"", &sz ) == ERROR_MORE_DATA )
{
sz++;
DWORD nbytes = sz * sizeof( wchar_t );
wchar_t* buff = reinterpret_cast<wchar_t*>( malloc( nbytes ) );
ZeroMemory( buff, nbytes );
MsiGetProperty( hMSI, pPropName, buff, &sz );
*ppValue = buff;
return TRUE;
}
return FALSE;
}
//----------------------------------------------------------
BOOL GetActiveXControlPath( MSIHANDLE hMSI, char** ppActiveXPath )
{
wchar_t* pProgPath = NULL;
if ( GetMsiProp( hMSI, L"INSTALLLOCATION", &pProgPath ) && pProgPath )
{
char* pCharProgPath = UnicodeToAnsiString( pProgPath );
if ( pCharProgPath )
{
int nLen = strlen( pCharProgPath );
*ppActiveXPath = reinterpret_cast<char*>( malloc( nLen + 23 ) );
strncpy( *ppActiveXPath, pCharProgPath, nLen );
strncpy( (*ppActiveXPath) + nLen, "program\\so_activex.dll", 22 );
(*ppActiveXPath)[nLen+22] = 0;
free( pCharProgPath );
return TRUE;
}
free( pProgPath );
}
return FALSE;
}
//----------------------------------------------------------
BOOL GetDelta( MSIHANDLE hMSI, int& nOldInstallMode, int& nInstallMode, int& nDeinstallMode )
{
// for now the chart is always installed
nOldInstallMode = CHART_COMPONENT;
nInstallMode = CHART_COMPONENT;
nDeinstallMode = 0;
INSTALLSTATE current_state;
INSTALLSTATE future_state;
if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Wrt_Bin", ¤t_state, &future_state ) )
{
// analyze writer installation mode
if ( current_state == INSTALLSTATE_LOCAL )
nOldInstallMode |= WRITER_COMPONENT;
if ( future_state == INSTALLSTATE_LOCAL
|| ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_UNKNOWN ) )
nInstallMode |= WRITER_COMPONENT;
else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT )
nDeinstallMode |= WRITER_COMPONENT;
}
else
{
// assert( FALSE );
}
if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Calc_Bin", ¤t_state, &future_state ) )
{
// analyze calc installation mode
if ( current_state == INSTALLSTATE_LOCAL )
nOldInstallMode |= CALC_COMPONENT;
if ( future_state == INSTALLSTATE_LOCAL
|| ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_UNKNOWN ) )
nInstallMode |= CALC_COMPONENT;
else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT )
nDeinstallMode |= CALC_COMPONENT;
}
else
{
// assert( FALSE );
}
if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Draw_Bin", ¤t_state, &future_state ) )
{
// analyze draw installation mode
if ( current_state == INSTALLSTATE_LOCAL )
nOldInstallMode |= DRAW_COMPONENT;
if ( future_state == INSTALLSTATE_LOCAL
|| ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_UNKNOWN ) )
nInstallMode |= DRAW_COMPONENT;
else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT )
nDeinstallMode |= DRAW_COMPONENT;
}
else
{
// assert( FALSE );
}
if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Impress_Bin", ¤t_state, &future_state ) )
{
// analyze impress installation mode
if ( current_state == INSTALLSTATE_LOCAL )
nOldInstallMode |= IMPRESS_COMPONENT;
if ( future_state == INSTALLSTATE_LOCAL
|| ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_UNKNOWN ) )
nInstallMode |= IMPRESS_COMPONENT;
else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT )
nDeinstallMode |= IMPRESS_COMPONENT;
}
else
{
// assert( FALSE );
}
if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Math_Bin", ¤t_state, &future_state ) )
{
// analyze math installation mode
if ( current_state == INSTALLSTATE_LOCAL )
nOldInstallMode |= MATH_COMPONENT;
if ( future_state == INSTALLSTATE_LOCAL
|| ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_UNKNOWN ) )
nInstallMode |= MATH_COMPONENT;
else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT )
nDeinstallMode |= MATH_COMPONENT;
}
else
{
// assert( FALSE );
}
return TRUE;
}
//----------------------------------------------------------
BOOL MakeInstallForAllUsers( MSIHANDLE hMSI )
{
BOOL bResult = FALSE;
wchar_t* pVal = NULL;
if ( GetMsiProp( hMSI, L"ALLUSERS", &pVal ) && pVal )
{
bResult = UnicodeEquals( pVal , L"1" );
free( pVal );
}
return bResult;
}
//----------------------------------------------------------
BOOL MakeInstallFor64Bit( MSIHANDLE hMSI )
{
BOOL bResult = FALSE;
wchar_t* pVal = NULL;
if ( GetMsiProp( hMSI, L"VersionNT64", &pVal ) && pVal )
{
bResult = TRUE;
free( pVal );
}
return bResult;
}
//----------------------------------------------------------
extern "C" UINT __stdcall InstallActiveXControl( MSIHANDLE hMSI )
{
int nOldInstallMode = 0;
int nInstallMode = 0;
int nDeinstallMode = 0;
INSTALLSTATE current_state;
INSTALLSTATE future_state;
if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_o_Activexcontrol", ¤t_state, &future_state ) )
{
BOOL bInstallForAllUser = MakeInstallForAllUsers( hMSI );
BOOL bInstallFor64Bit = MakeInstallFor64Bit( hMSI );
char* pActiveXPath = NULL;
if ( GetActiveXControlPath( hMSI, &pActiveXPath ) && pActiveXPath
&& GetDelta( hMSI, nOldInstallMode, nInstallMode, nDeinstallMode ) )
{
if ( future_state == INSTALLSTATE_LOCAL
|| ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_UNKNOWN ) )
{
// the control is installed in the new selected configuration
if ( current_state == INSTALLSTATE_LOCAL && nDeinstallMode )
UnregisterActiveXNative( pActiveXPath, nDeinstallMode, bInstallForAllUser, bInstallFor64Bit );
if ( nInstallMode )
RegisterActiveXNative( pActiveXPath, nInstallMode, bInstallForAllUser, bInstallFor64Bit );
}
else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT )
{
if ( nOldInstallMode )
UnregisterActiveXNative( pActiveXPath, nOldInstallMode, bInstallForAllUser, bInstallFor64Bit );
}
}
if ( pActiveXPath )
free( pActiveXPath );
}
else
{
// assert( FALSE );
}
return ERROR_SUCCESS;
}
//----------------------------------------------------------
extern "C" UINT __stdcall DeinstallActiveXControl( MSIHANDLE hMSI )
{
INSTALLSTATE current_state;
INSTALLSTATE future_state;
if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_o_Activexcontrol", ¤t_state, &future_state ) )
{
char* pActiveXPath = NULL;
if ( current_state == INSTALLSTATE_LOCAL && GetActiveXControlPath( hMSI, &pActiveXPath ) && pActiveXPath )
{
BOOL bInstallForAllUser = MakeInstallForAllUsers( hMSI );
BOOL bInstallFor64Bit = MakeInstallFor64Bit( hMSI );
{
UnregisterActiveXNative( pActiveXPath,
CHART_COMPONENT
| DRAW_COMPONENT
| IMPRESS_COMPONENT
| CALC_COMPONENT
| WRITER_COMPONENT
| MATH_COMPONENT,
bInstallForAllUser,
bInstallFor64Bit );
}
free( pActiveXPath );
}
}
return ERROR_SUCCESS;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Remove OWN_DEBUG_PRINT
|
Remove OWN_DEBUG_PRINT
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
0275a5528dd5dde0db50f588e88bc2b200f60c21
|
chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc
|
chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h"
#include "base/bind.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "chrome/browser/local_discovery/privet_device_lister_impl.h"
#include "chrome/browser/local_discovery/privet_http_impl.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/profile_oauth2_token_service.h"
#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
#include "chrome/browser/signin/signin_manager.h"
#include "chrome/browser/signin/signin_manager_base.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "content/public/browser/web_ui.h"
#include "net/base/host_port_pair.h"
#include "net/base/net_util.h"
#include "net/http/http_status_code.h"
namespace local_discovery {
namespace {
// TODO(noamsml): This is a temporary shim until automated_url is in the
// response.
const char kPrivetAutomatedClaimURLFormat[] = "%s/confirm?token=%s";
LocalDiscoveryUIHandler::Factory* g_factory = NULL;
} // namepsace
LocalDiscoveryUIHandler::LocalDiscoveryUIHandler() {
}
LocalDiscoveryUIHandler::LocalDiscoveryUIHandler(
scoped_ptr<PrivetDeviceLister> privet_lister) {
privet_lister.swap(privet_lister_);
}
LocalDiscoveryUIHandler::~LocalDiscoveryUIHandler() {
}
// static
LocalDiscoveryUIHandler* LocalDiscoveryUIHandler::Create() {
if (g_factory) return g_factory->CreateLocalDiscoveryUIHandler();
return new LocalDiscoveryUIHandler();
}
// static
void LocalDiscoveryUIHandler::SetFactory(Factory* factory) {
g_factory = factory;
}
void LocalDiscoveryUIHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback("start", base::Bind(
&LocalDiscoveryUIHandler::HandleStart,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("registerDevice", base::Bind(
&LocalDiscoveryUIHandler::HandleRegisterDevice,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("info", base::Bind(
&LocalDiscoveryUIHandler::HandleInfoRequested,
base::Unretained(this)));
}
void LocalDiscoveryUIHandler::HandleStart(const base::ListValue* args) {
// If privet_lister_ is already set, it is a mock used for tests.
if (!privet_lister_) {
service_discovery_client_ = new ServiceDiscoveryHostClient();
service_discovery_client_->Start();
privet_lister_.reset(new PrivetDeviceListerImpl(
service_discovery_client_.get(), this));
}
privet_lister_->Start();
privet_lister_->DiscoverNewDevices(false);
}
void LocalDiscoveryUIHandler::HandleRegisterDevice(
const base::ListValue* args) {
std::string device_name;
bool rv = args->GetString(0, &device_name);
DCHECK(rv);
current_http_device_ = device_name;
domain_resolver_ = service_discovery_client_->CreateLocalDomainResolver(
device_descriptions_[device_name].address.host(),
net::ADDRESS_FAMILY_UNSPECIFIED,
base::Bind(&LocalDiscoveryUIHandler::StartRegisterHTTP,
base::Unretained(this)));
domain_resolver_->Start();
}
void LocalDiscoveryUIHandler::HandleInfoRequested(const base::ListValue* args) {
std::string device_name;
args->GetString(0, &device_name);
current_http_device_ = device_name;
domain_resolver_ = service_discovery_client_->CreateLocalDomainResolver(
device_descriptions_[device_name].address.host(),
net::ADDRESS_FAMILY_UNSPECIFIED,
base::Bind(&LocalDiscoveryUIHandler::StartInfoHTTP,
base::Unretained(this)));
domain_resolver_->Start();
}
void LocalDiscoveryUIHandler::StartRegisterHTTP(bool success,
const net::IPAddressNumber& address) {
if (!success) {
LogRegisterErrorToWeb("Resolution failed");
return;
}
if (device_descriptions_.count(current_http_device_) == 0) {
LogRegisterErrorToWeb("Device no longer exists");
return;
}
Profile* profile = Profile::FromWebUI(web_ui());
SigninManagerBase* signin_manager =
SigninManagerFactory::GetForProfileIfExists(profile);
if (!signin_manager) {
LogRegisterErrorToWeb("You must be signed in");
return;
}
std::string username = signin_manager->GetAuthenticatedUsername();
std::string address_str = net::IPAddressToString(address);
int port = device_descriptions_[current_http_device_].address.port();
current_http_client_.reset(new PrivetHTTPClientImpl(
net::HostPortPair(address_str, port),
Profile::FromWebUI(web_ui())->GetRequestContext()));
current_register_operation_ =
current_http_client_->CreateRegisterOperation(username, this);
current_register_operation_->Start();
}
void LocalDiscoveryUIHandler::StartInfoHTTP(bool success,
const net::IPAddressNumber& address) {
if (!success) {
LogInfoErrorToWeb("Resolution failed");
return;
}
if (device_descriptions_.count(current_http_device_) == 0) {
LogRegisterErrorToWeb("Device no longer exists");
return;
}
std::string address_str = net::IPAddressToString(address);
int port = device_descriptions_[current_http_device_].address.port();
current_http_client_.reset(new PrivetHTTPClientImpl(
net::HostPortPair(address_str, port),
Profile::FromWebUI(web_ui())->GetRequestContext()));
current_info_operation_ = current_http_client_->CreateInfoOperation(this);
current_info_operation_->Start();
}
void LocalDiscoveryUIHandler::OnPrivetRegisterClaimToken(
const std::string& token,
const GURL& url) {
if (device_descriptions_.count(current_http_device_) == 0) {
LogRegisterErrorToWeb("Device no longer exists");
return;
}
GURL automated_claim_url(base::StringPrintf(
kPrivetAutomatedClaimURLFormat,
device_descriptions_[current_http_device_].url.c_str(),
token.c_str()));
Profile* profile = Profile::FromWebUI(web_ui());
OAuth2TokenService* token_service =
ProfileOAuth2TokenServiceFactory::GetForProfile(profile);
if (!token_service) {
LogRegisterErrorToWeb("Could not get token service");
return;
}
confirm_api_call_flow_.reset(new PrivetConfirmApiCallFlow(
profile->GetRequestContext(),
token_service,
automated_claim_url,
base::Bind(&LocalDiscoveryUIHandler::OnConfirmDone,
base::Unretained(this))));
confirm_api_call_flow_->Start();
}
void LocalDiscoveryUIHandler::OnPrivetRegisterError(
const std::string& action,
PrivetRegisterOperation::FailureReason reason,
int printer_http_code,
const DictionaryValue* json) {
// TODO(noamsml): Add detailed error message.
LogRegisterErrorToWeb("Registration error");
}
void LocalDiscoveryUIHandler::OnPrivetRegisterDone(
const std::string& device_id) {
current_register_operation_.reset();
current_http_client_.reset();
LogRegisterDoneToWeb(device_id);
}
void LocalDiscoveryUIHandler::OnConfirmDone(
PrivetConfirmApiCallFlow::Status status) {
if (status == PrivetConfirmApiCallFlow::SUCCESS) {
DLOG(INFO) << "Confirm success.";
confirm_api_call_flow_.reset();
current_register_operation_->CompleteRegistration();
} else {
// TODO(noamsml): Add detailed error message.
LogRegisterErrorToWeb("Confirm error");
}
}
void LocalDiscoveryUIHandler::DeviceChanged(
bool added,
const std::string& name,
const DeviceDescription& description) {
device_descriptions_[name] = description;
base::StringValue service_name(name);
base::DictionaryValue info;
info.SetString("domain", description.address.host());
info.SetInteger("port", description.address.port());
std::string ip_addr_string;
if (!description.ip_address.empty())
ip_addr_string = net::IPAddressToString(description.ip_address);
info.SetString("ip", ip_addr_string);
info.SetString("lastSeen", "unknown");
info.SetBoolean("registered", !description.id.empty());
web_ui()->CallJavascriptFunction("local_discovery.onServiceUpdate",
service_name, info);
}
void LocalDiscoveryUIHandler::DeviceRemoved(const std::string& name) {
device_descriptions_.erase(name);
scoped_ptr<base::Value> null_value(base::Value::CreateNullValue());
base::StringValue name_value(name);
web_ui()->CallJavascriptFunction("local_discovery.onServiceUpdate",
name_value, *null_value);
}
void LocalDiscoveryUIHandler::LogRegisterErrorToWeb(const std::string& error) {
base::StringValue error_value(error);
web_ui()->CallJavascriptFunction("local_discovery.registrationFailed",
error_value);
DLOG(ERROR) << error;
}
void LocalDiscoveryUIHandler::LogRegisterDoneToWeb(const std::string& id) {
base::StringValue id_value(id);
web_ui()->CallJavascriptFunction("local_discovery.registrationSuccess",
id_value);
DLOG(INFO) << "Registered " << id;
}
void LocalDiscoveryUIHandler::LogInfoErrorToWeb(const std::string& error) {
base::StringValue error_value(error);
web_ui()->CallJavascriptFunction("local_discovery.infoFailed", error_value);
LOG(ERROR) << error;
}
void LocalDiscoveryUIHandler::OnPrivetInfoDone(
int http_code,
const base::DictionaryValue* json_value) {
if (http_code != net::HTTP_OK || !json_value) {
LogInfoErrorToWeb(base::StringPrintf("HTTP error %d", http_code));
return;
}
web_ui()->CallJavascriptFunction("local_discovery.renderInfo", *json_value);
}
} // namespace local_discovery
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h"
#include "base/bind.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "chrome/browser/local_discovery/privet_device_lister_impl.h"
#include "chrome/browser/local_discovery/privet_http_impl.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/profile_oauth2_token_service.h"
#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
#include "chrome/browser/signin/signin_manager.h"
#include "chrome/browser/signin/signin_manager_base.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "content/public/browser/web_ui.h"
#include "net/base/host_port_pair.h"
#include "net/base/net_util.h"
#include "net/http/http_status_code.h"
namespace local_discovery {
namespace {
// TODO(noamsml): This is a temporary shim until automated_url is in the
// response.
const char kPrivetAutomatedClaimURLFormat[] = "%s/confirm?token=%s";
std::string IPAddressToHostString(const net::IPAddressNumber& address) {
std::string address_str = net::IPAddressToString(address);
// IPv6 addresses need to be surrounded by brackets.
if (address.size() == net::kIPv6AddressSize) {
address_str = base::StringPrintf("[%s]", address_str.c_str());
}
return address_str;
}
LocalDiscoveryUIHandler::Factory* g_factory = NULL;
} // namespace
LocalDiscoveryUIHandler::LocalDiscoveryUIHandler() {
}
LocalDiscoveryUIHandler::LocalDiscoveryUIHandler(
scoped_ptr<PrivetDeviceLister> privet_lister) {
privet_lister.swap(privet_lister_);
}
LocalDiscoveryUIHandler::~LocalDiscoveryUIHandler() {
}
// static
LocalDiscoveryUIHandler* LocalDiscoveryUIHandler::Create() {
if (g_factory) return g_factory->CreateLocalDiscoveryUIHandler();
return new LocalDiscoveryUIHandler();
}
// static
void LocalDiscoveryUIHandler::SetFactory(Factory* factory) {
g_factory = factory;
}
void LocalDiscoveryUIHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback("start", base::Bind(
&LocalDiscoveryUIHandler::HandleStart,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("registerDevice", base::Bind(
&LocalDiscoveryUIHandler::HandleRegisterDevice,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("info", base::Bind(
&LocalDiscoveryUIHandler::HandleInfoRequested,
base::Unretained(this)));
}
void LocalDiscoveryUIHandler::HandleStart(const base::ListValue* args) {
// If privet_lister_ is already set, it is a mock used for tests.
if (!privet_lister_) {
service_discovery_client_ = new ServiceDiscoveryHostClient();
service_discovery_client_->Start();
privet_lister_.reset(new PrivetDeviceListerImpl(
service_discovery_client_.get(), this));
}
privet_lister_->Start();
privet_lister_->DiscoverNewDevices(false);
}
void LocalDiscoveryUIHandler::HandleRegisterDevice(
const base::ListValue* args) {
std::string device_name;
bool rv = args->GetString(0, &device_name);
DCHECK(rv);
current_http_device_ = device_name;
domain_resolver_ = service_discovery_client_->CreateLocalDomainResolver(
device_descriptions_[device_name].address.host(),
net::ADDRESS_FAMILY_UNSPECIFIED,
base::Bind(&LocalDiscoveryUIHandler::StartRegisterHTTP,
base::Unretained(this)));
domain_resolver_->Start();
}
void LocalDiscoveryUIHandler::HandleInfoRequested(const base::ListValue* args) {
std::string device_name;
args->GetString(0, &device_name);
current_http_device_ = device_name;
domain_resolver_ = service_discovery_client_->CreateLocalDomainResolver(
device_descriptions_[device_name].address.host(),
net::ADDRESS_FAMILY_UNSPECIFIED,
base::Bind(&LocalDiscoveryUIHandler::StartInfoHTTP,
base::Unretained(this)));
domain_resolver_->Start();
}
void LocalDiscoveryUIHandler::StartRegisterHTTP(bool success,
const net::IPAddressNumber& address) {
if (!success) {
LogRegisterErrorToWeb("Resolution failed");
return;
}
if (device_descriptions_.count(current_http_device_) == 0) {
LogRegisterErrorToWeb("Device no longer exists");
return;
}
Profile* profile = Profile::FromWebUI(web_ui());
SigninManagerBase* signin_manager =
SigninManagerFactory::GetForProfileIfExists(profile);
if (!signin_manager) {
LogRegisterErrorToWeb("You must be signed in");
return;
}
std::string username = signin_manager->GetAuthenticatedUsername();
std::string address_str = IPAddressToHostString(address);
int port = device_descriptions_[current_http_device_].address.port();
current_http_client_.reset(new PrivetHTTPClientImpl(
net::HostPortPair(address_str, port),
Profile::FromWebUI(web_ui())->GetRequestContext()));
current_register_operation_ =
current_http_client_->CreateRegisterOperation(username, this);
current_register_operation_->Start();
}
void LocalDiscoveryUIHandler::StartInfoHTTP(bool success,
const net::IPAddressNumber& address) {
if (!success) {
LogInfoErrorToWeb("Resolution failed");
return;
}
if (device_descriptions_.count(current_http_device_) == 0) {
LogRegisterErrorToWeb("Device no longer exists");
return;
}
std::string address_str = IPAddressToHostString(address);
int port = device_descriptions_[current_http_device_].address.port();
current_http_client_.reset(new PrivetHTTPClientImpl(
net::HostPortPair(address_str, port),
Profile::FromWebUI(web_ui())->GetRequestContext()));
current_info_operation_ = current_http_client_->CreateInfoOperation(this);
current_info_operation_->Start();
}
void LocalDiscoveryUIHandler::OnPrivetRegisterClaimToken(
const std::string& token,
const GURL& url) {
if (device_descriptions_.count(current_http_device_) == 0) {
LogRegisterErrorToWeb("Device no longer exists");
return;
}
GURL automated_claim_url(base::StringPrintf(
kPrivetAutomatedClaimURLFormat,
device_descriptions_[current_http_device_].url.c_str(),
token.c_str()));
Profile* profile = Profile::FromWebUI(web_ui());
OAuth2TokenService* token_service =
ProfileOAuth2TokenServiceFactory::GetForProfile(profile);
if (!token_service) {
LogRegisterErrorToWeb("Could not get token service");
return;
}
confirm_api_call_flow_.reset(new PrivetConfirmApiCallFlow(
profile->GetRequestContext(),
token_service,
automated_claim_url,
base::Bind(&LocalDiscoveryUIHandler::OnConfirmDone,
base::Unretained(this))));
confirm_api_call_flow_->Start();
}
void LocalDiscoveryUIHandler::OnPrivetRegisterError(
const std::string& action,
PrivetRegisterOperation::FailureReason reason,
int printer_http_code,
const DictionaryValue* json) {
// TODO(noamsml): Add detailed error message.
LogRegisterErrorToWeb("Registration error");
}
void LocalDiscoveryUIHandler::OnPrivetRegisterDone(
const std::string& device_id) {
current_register_operation_.reset();
current_http_client_.reset();
LogRegisterDoneToWeb(device_id);
}
void LocalDiscoveryUIHandler::OnConfirmDone(
PrivetConfirmApiCallFlow::Status status) {
if (status == PrivetConfirmApiCallFlow::SUCCESS) {
DLOG(INFO) << "Confirm success.";
confirm_api_call_flow_.reset();
current_register_operation_->CompleteRegistration();
} else {
// TODO(noamsml): Add detailed error message.
LogRegisterErrorToWeb("Confirm error");
}
}
void LocalDiscoveryUIHandler::DeviceChanged(
bool added,
const std::string& name,
const DeviceDescription& description) {
device_descriptions_[name] = description;
base::StringValue service_name(name);
base::DictionaryValue info;
info.SetString("domain", description.address.host());
info.SetInteger("port", description.address.port());
std::string ip_addr_string;
if (!description.ip_address.empty())
ip_addr_string = net::IPAddressToString(description.ip_address);
info.SetString("ip", ip_addr_string);
info.SetString("lastSeen", "unknown");
info.SetBoolean("registered", !description.id.empty());
web_ui()->CallJavascriptFunction("local_discovery.onServiceUpdate",
service_name, info);
}
void LocalDiscoveryUIHandler::DeviceRemoved(const std::string& name) {
device_descriptions_.erase(name);
scoped_ptr<base::Value> null_value(base::Value::CreateNullValue());
base::StringValue name_value(name);
web_ui()->CallJavascriptFunction("local_discovery.onServiceUpdate",
name_value, *null_value);
}
void LocalDiscoveryUIHandler::LogRegisterErrorToWeb(const std::string& error) {
base::StringValue error_value(error);
web_ui()->CallJavascriptFunction("local_discovery.registrationFailed",
error_value);
DLOG(ERROR) << error;
}
void LocalDiscoveryUIHandler::LogRegisterDoneToWeb(const std::string& id) {
base::StringValue id_value(id);
web_ui()->CallJavascriptFunction("local_discovery.registrationSuccess",
id_value);
DLOG(INFO) << "Registered " << id;
}
void LocalDiscoveryUIHandler::LogInfoErrorToWeb(const std::string& error) {
base::StringValue error_value(error);
web_ui()->CallJavascriptFunction("local_discovery.infoFailed", error_value);
LOG(ERROR) << error;
}
void LocalDiscoveryUIHandler::OnPrivetInfoDone(
int http_code,
const base::DictionaryValue* json_value) {
if (http_code != net::HTTP_OK || !json_value) {
LogInfoErrorToWeb(base::StringPrintf("HTTP error %d", http_code));
return;
}
web_ui()->CallJavascriptFunction("local_discovery.renderInfo", *json_value);
}
} // namespace local_discovery
|
Fix issue with ipv6 addresses in local discovery page
|
Fix issue with ipv6 addresses in local discovery page
Currently, the URLs the local discovery page creates when the printer has an
ipv6 address are incorrect, since ipv6 addresses need to be in brackets.
BUG=
Review URL: https://chromiumcodereview.appspot.com/20850002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@217906 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,littlstar/chromium.src,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,fujunwei/chromium-crosswalk,anirudhSK/chromium,Chilledheart/chromium,markYoungH/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,ltilve/chromium,patrickm/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,markYoungH/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,ChromiumWebApps/chromium,jaruba/chromium.src,ltilve/chromium,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,jaruba/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,Jonekee/chromium.src,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,ltilve/chromium,anirudhSK/chromium,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,ltilve/chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,ltilve/chromium,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,M4sse/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,hgl888/chromium-crosswalk,dednal/chromium.src,anirudhSK/chromium,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,ChromiumWebApps/chromium,Chilledheart/chromium,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,axinging/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,dednal/chromium.src,patrickm/chromium.src,anirudhSK/chromium,dushu1203/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,Jonekee/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,ltilve/chromium,patrickm/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,littlstar/chromium.src,anirudhSK/chromium,patrickm/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,littlstar/chromium.src,anirudhSK/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,ltilve/chromium,bright-sparks/chromium-spacewalk,jaruba/chromium.src,littlstar/chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,Fireblend/chromium-crosswalk,markYoungH/chromium.src,patrickm/chromium.src,patrickm/chromium.src,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,M4sse/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,littlstar/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,Just-D/chromium-1,dednal/chromium.src,dushu1203/chromium.src,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk
|
c24fb5c2c64ff78a1f84c85afca4c36341b13c26
|
openCherry/Bundles/org.opencherry.ui.qt/src/cherryQtAssistantUtil.cpp
|
openCherry/Bundles/org.opencherry.ui.qt/src/cherryQtAssistantUtil.cpp
|
/*=========================================================================
Program: openCherry Platform
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "cherryQtAssistantUtil.h"
#include <cherryConfig.h>
#include <cherryLog.h>
#include <cherryIBundleStorage.h>
#include <QFileInfo>
#include <QProgressDialog>
namespace cherry
{
QProcess* QtAssistantUtil::assistantProcess = 0;
QString* QtAssistantUtil::HelpCollectionFile = new QString("");
void QtAssistantUtil::SetHelpColletionFile(QString* file)
{
HelpCollectionFile = file;
}
void QtAssistantUtil::OpenHelpPage()
{
if (assistantProcess!=0) assistantProcess->kill();
OpenAssistant(*HelpCollectionFile,"");
}
void QtAssistantUtil::OpenAssistant(const QString& collectionFile, const QString& startPage)
{
QString assistantExec = GetAssistantExecutable();
assistantProcess = new QProcess;
QStringList thisCollection;
thisCollection << QLatin1String("-collectionFile")
<< QLatin1String(collectionFile.toLatin1())
<< QLatin1String("-enableRemoteControl");
assistantProcess->start(assistantExec, thisCollection);
}
bool QtAssistantUtil::RegisterQCHFiles(const QString& collectionFile,
const std::vector<IBundle::Pointer>& bundles)
{
QString assistantExec = GetAssistantExecutable();
QList<QStringList> argsVector;
for (std::size_t i = 0; i < bundles.size(); ++i)
{
std::vector<std::string> resourceFiles;
bundles[i]->GetStorage().List("resources", resourceFiles);
for (std::size_t j = 0; j < resourceFiles.size(); ++j)
{
QString resource = QString::fromStdString(resourceFiles[j]);
if (resource.endsWith(".qch"))
{
QStringList args;
args << QLatin1String("-collectionFile") << collectionFile;
Poco::Path qchPath = bundles[i]->GetPath();
qchPath.pushDirectory("resources");
qchPath.setFileName(resourceFiles[j]);
args << QLatin1String("-register") << QString::fromStdString(qchPath.toString());
argsVector.push_back(args);
}
}
}
bool success = true;
QProgressDialog progress("Registering help files...", "Abort Registration", 0, argsVector.size());
progress.setWindowModality(Qt::WindowModal);
if (argsVector.isEmpty())
{
CHERRY_WARN << "No .qch files found. Help contents will not be available.";
}
for (std::size_t i = 0; i < argsVector.size(); ++i)
{
const QStringList& args = argsVector[i];
progress.setValue(i);
QString labelText = QString("Registering ") + args[3];
progress.setLabelText(labelText);
if (progress.wasCanceled())
{
success = false;
break;
}
QProcess* process = new QProcess;
process->start(assistantExec, args);
if (!process->waitForStarted())
{
success = false;
CHERRY_ERROR << "Registering compressed help file" << args[3].toStdString() << " failed";
}
}
progress.setValue(argsVector.size());
return success;
}
QString QtAssistantUtil::GetAssistantExecutable()
{
QFileInfo assistantFile(QT_ASSISTANT_EXECUTABLE);
return assistantFile.fileName();
}
}
|
/*=========================================================================
Program: openCherry Platform
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "cherryQtAssistantUtil.h"
#include <cherryConfig.h>
#include <cherryLog.h>
#include <cherryIBundleStorage.h>
#include <QFileInfo>
#include <QProgressDialog>
namespace cherry
{
QProcess* QtAssistantUtil::assistantProcess = 0;
QString* QtAssistantUtil::HelpCollectionFile = new QString("");
void QtAssistantUtil::SetHelpColletionFile(QString* file)
{
HelpCollectionFile = file;
}
void QtAssistantUtil::OpenHelpPage()
{
if (assistantProcess!=0) assistantProcess->kill();
OpenAssistant(*HelpCollectionFile,"");
}
void QtAssistantUtil::OpenAssistant(const QString& collectionFile, const QString& startPage)
{
QString assistantExec = GetAssistantExecutable();
assistantProcess = new QProcess;
QStringList thisCollection;
thisCollection << QLatin1String("-collectionFile")
<< QLatin1String(collectionFile.toLatin1())
<< QLatin1String("-enableRemoteControl");
assistantProcess->start(assistantExec, thisCollection);
}
bool QtAssistantUtil::RegisterQCHFiles(const QString& collectionFile,
const std::vector<IBundle::Pointer>& bundles)
{
QString assistantExec = GetAssistantExecutable();
QList<QStringList> argsVector;
for (std::size_t i = 0; i < bundles.size(); ++i)
{
std::vector<std::string> resourceFiles;
bundles[i]->GetStorage().List("resources", resourceFiles);
for (std::size_t j = 0; j < resourceFiles.size(); ++j)
{
QString resource = QString::fromStdString(resourceFiles[j]);
if (resource.endsWith(".qch"))
{
QStringList args;
args << QLatin1String("-collectionFile") << collectionFile;
Poco::Path qchPath = bundles[i]->GetPath();
qchPath.pushDirectory("resources");
qchPath.setFileName(resourceFiles[j]);
args << QLatin1String("-register") << QString::fromStdString(qchPath.toString());
args << QLatin1String("-quiet");
argsVector.push_back(args);
}
}
}
bool success = true;
QProgressDialog progress("Registering help files...", "Abort Registration", 0, argsVector.size());
progress.setWindowModality(Qt::WindowModal);
if (argsVector.isEmpty())
{
CHERRY_WARN << "No .qch files found. Help contents will not be available.";
}
for (std::size_t i = 0; i < argsVector.size(); ++i)
{
const QStringList& args = argsVector[i];
progress.setValue(i);
QString labelText = QString("Registering ") + args[3];
progress.setLabelText(labelText);
if (progress.wasCanceled())
{
success = false;
break;
}
QProcess* process = new QProcess;
process->start(assistantExec, args);
if (!process->waitForStarted())
{
success = false;
CHERRY_ERROR << "Registering compressed help file" << args[3].toStdString() << " failed";
}
}
progress.setValue(argsVector.size());
return success;
}
QString QtAssistantUtil::GetAssistantExecutable()
{
QFileInfo assistantFile(QT_ASSISTANT_EXECUTABLE);
return assistantFile.fileName();
}
}
|
FIX (#2977): suppressing Qt Assistant popups
|
FIX (#2977): suppressing Qt Assistant popups
|
C++
|
bsd-3-clause
|
nocnokneo/MITK,lsanzdiaz/MITK-BiiG,fmilano/mitk,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,danielknorr/MITK,RabadanLab/MITKats,rfloca/MITK,NifTK/MITK,iwegner/MITK,danielknorr/MITK,MITK/MITK,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,fmilano/mitk,danielknorr/MITK,nocnokneo/MITK,MITK/MITK,rfloca/MITK,lsanzdiaz/MITK-BiiG,iwegner/MITK,lsanzdiaz/MITK-BiiG,iwegner/MITK,nocnokneo/MITK,fmilano/mitk,danielknorr/MITK,fmilano/mitk,nocnokneo/MITK,fmilano/mitk,NifTK/MITK,danielknorr/MITK,NifTK/MITK,MITK/MITK,MITK/MITK,iwegner/MITK,iwegner/MITK,RabadanLab/MITKats,RabadanLab/MITKats,rfloca/MITK,fmilano/mitk,NifTK/MITK,RabadanLab/MITKats,rfloca/MITK,MITK/MITK,fmilano/mitk,RabadanLab/MITKats,iwegner/MITK,nocnokneo/MITK,rfloca/MITK,rfloca/MITK,rfloca/MITK,MITK/MITK,NifTK/MITK,RabadanLab/MITKats,danielknorr/MITK,NifTK/MITK,danielknorr/MITK,nocnokneo/MITK
|
8b9bd1650591b8f6ae2d3c5b0042848fe02af2ef
|
paddle/fluid/string/string_helper_test.cc
|
paddle/fluid/string/string_helper_test.cc
|
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/string/string_helper.h"
#include <string>
#include "gtest/gtest.h"
TEST(StringHelper, EndsWith) {
std::string input("hello world");
std::string test1("world");
std::string test2("helloworld");
std::string test3("hello world hello world");
EXPECT_TRUE(paddle::string::ends_with(input, test1));
EXPECT_TRUE(paddle::string::ends_with(input, input));
EXPECT_FALSE(paddle::string::ends_with(input, test2));
EXPECT_FALSE(paddle::string::ends_with(input, test3));
}
TEST(StringHelper, FormatStringAppend) {
std::string str("hello");
char fmt[] = "hhh";
paddle::string::format_string_append(str, fmt);
EXPECT_EQ(str, "hellohhh");
}
TEST(StringHelper, JoinStrings) {
std::vector<std::string> v;
v.push_back("hello");
v.push_back("world");
std::string result = paddle::string::join_strings(v, ' ');
EXPECT_EQ(result, "hello world");
result = paddle::string::join_strings(v, '\n');
EXPECT_EQ(result, "hello\nworld");
result = paddle::string::join_strings(v, ',');
EXPECT_EQ(result, "hello,world");
result = paddle::string::join_strings(v, " new ");
EXPECT_EQ(result, "hello new world");
}
|
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/string/string_helper.h"
#include <string>
#include "gtest/gtest.h"
TEST(StringHelper, EndsWith) {
std::string input("hello world");
std::string test1("world");
std::string test2("helloworld");
std::string test3("hello world hello world");
EXPECT_TRUE(paddle::string::ends_with(input, test1));
EXPECT_TRUE(paddle::string::ends_with(input, input));
EXPECT_FALSE(paddle::string::ends_with(input, test2));
EXPECT_FALSE(paddle::string::ends_with(input, test3));
}
TEST(StringHelper, FormatStringAppend) {
std::string str("hello");
char fmt[] = "%d";
paddle::string::format_string_append(str, fmt, 10);
EXPECT_EQ(str, "hello10");
}
TEST(StringHelper, JoinStrings) {
std::vector<std::string> v;
v.push_back("hello");
v.push_back("world");
std::string result = paddle::string::join_strings(v, ' ');
EXPECT_EQ(result, "hello world");
result = paddle::string::join_strings(v, '\n');
EXPECT_EQ(result, "hello\nworld");
result = paddle::string::join_strings(v, ',');
EXPECT_EQ(result, "hello,world");
result = paddle::string::join_strings(v, " new ");
EXPECT_EQ(result, "hello new world");
}
|
fix format_string_append test cast,test=develop (#34753)
|
fix format_string_append test cast,test=develop (#34753)
|
C++
|
apache-2.0
|
PaddlePaddle/Paddle,luotao1/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,luotao1/Paddle,luotao1/Paddle,luotao1/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle
|
e7a5a4c4c88d7744a967b6b562909405c8f6a7da
|
src/util/regx/RangeTokenMap.cpp
|
src/util/regx/RangeTokenMap.cpp
|
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.2 2001/05/11 13:26:45 tng
* Copyright update.
*
* Revision 1.1 2001/05/03 18:17:40 knoaman
* Some design changes:
* o Changed the TokenFactory from a single static instance, to a
* normal class. Each RegularExpression object will have its own
* instance of TokenFactory, and that instance will be passed to
* other classes that need to use a TokenFactory to create Token
* objects (with the exception of RangeTokenMap).
* o Added a new class RangeTokenMap to map a the different ranges
* in a given category to a specific RangeFactory object. In the old
* design RangeFactory had dual functionality (act as a Map, and as
* a factory for creating RangeToken(s)). The RangeTokenMap will
* have its own copy of the TokenFactory. There will be only one
* instance of the RangeTokenMap class, and that instance will be
* lazily deleted when XPlatformUtils::Terminate is called.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/regx/RangeTokenMap.hpp>
#include <util/regx/RangeToken.hpp>
#include <util/regx/RegxDefs.hpp>
#include <util/regx/TokenFactory.hpp>
#include <util/regx/RangeFactory.hpp>
#include <util/PlatformUtils.hpp>
#include <util/XMLDeleterFor.hpp>
#include <util/XMLExceptMsgs.hpp>
// ---------------------------------------------------------------------------
// Static member data initialization
// ---------------------------------------------------------------------------
RangeTokenMap* RangeTokenMap::fInstance = 0;
// ---------------------------------------------------------------------------
// RangeTokenElemMap: Constructors and Destructor
// ---------------------------------------------------------------------------
RangeTokenElemMap::RangeTokenElemMap(unsigned int categoryId) :
fCategoryId(categoryId)
, fRange(0)
, fNRange(0)
{
}
RangeTokenElemMap::~RangeTokenElemMap()
{
}
// ---------------------------------------------------------------------------
// RangeTokenMap: Constructors and Destructor
// ---------------------------------------------------------------------------
RangeTokenMap::RangeTokenMap() :
fRegistryInitialized(0)
, fTokenRegistry(0)
, fRangeMap(0)
, fCategories(0)
, fTokenFactory(0) {
}
RangeTokenMap::~RangeTokenMap() {
delete fTokenRegistry;
fTokenRegistry = 0;
delete fRangeMap;
fRangeMap = 0;
delete fCategories;
fCategories = 0;
delete fInstance;
fInstance = 0;
delete fTokenFactory;
fTokenFactory = 0;
}
// ---------------------------------------------------------------------------
// RangeTokenMap: Getter methods
// ---------------------------------------------------------------------------
RangeToken* RangeTokenMap::getRange(const XMLCh* const keyword,
const bool complement) {
if (fTokenRegistry == 0 || fRangeMap == 0 || fCategories == 0)
return 0;
if (!fTokenRegistry->containsKey(keyword))
return 0;
RangeTokenElemMap* elemMap = 0;
// Use a faux scope to synchronize while we do this
{
XMLMutexLock lockInit(&fMutex);
elemMap = fTokenRegistry->get(keyword);
RangeToken* rangeTok = 0;
if (elemMap->getRangeToken() == 0) {
unsigned int categId = elemMap->getCategoryId();
const XMLCh* categName = fCategories->getValueForId(categId);
RangeFactory* rangeFactory = fRangeMap->get(categName);
if (rangeFactory == 0)
return 0;
rangeFactory->buildRanges();
}
if (complement && ((rangeTok = elemMap->getRangeToken()) != 0)) {
elemMap->setRangeToken((RangeToken*)
RangeToken::complementRanges(rangeTok, fTokenFactory),
complement);
}
}
return (elemMap == 0) ? 0 : elemMap->getRangeToken(complement);
}
// ---------------------------------------------------------------------------
// RangeTokenMap: Putter methods
// ---------------------------------------------------------------------------
void RangeTokenMap::addCategory(const XMLCh* const categoryName) {
if (fCategories)
fCategories->addOrFind(categoryName);
}
void RangeTokenMap::addRangeMap(const XMLCh* const categoryName,
RangeFactory* const rangeFactory) {
if (fRangeMap)
fRangeMap->put((void*)categoryName, rangeFactory);
}
void RangeTokenMap::addKeywordMap(const XMLCh* const keyword,
const XMLCh* const categoryName) {
if (fCategories == 0 || fTokenRegistry == 0)
return;
unsigned int categId = fCategories->getId(categoryName);
if (categId == 0) {
ThrowXML1(RuntimeException, XMLExcepts::Regex_InvalidCategoryName, categoryName);
}
if (fTokenRegistry->containsKey(keyword)) {
RangeTokenElemMap* elemMap = fTokenRegistry->get(keyword);
if (elemMap->getCategoryId() != categId)
elemMap->setCategoryId(categId);
return;
}
fTokenRegistry->put((void*) keyword, new RangeTokenElemMap(categId));
}
// ---------------------------------------------------------------------------
// RangeTokenMap: Setter methods
// ---------------------------------------------------------------------------
void RangeTokenMap::setRangeToken(const XMLCh* const keyword,
RangeToken* const tok,const bool complement) {
if (fTokenRegistry == 0)
return;
if (fTokenRegistry->containsKey(keyword)) {
fTokenRegistry->get(keyword)->setRangeToken(tok, complement);
}
else {
ThrowXML1(RuntimeException, XMLExcepts::Regex_KeywordNotFound, keyword);
}
}
// ---------------------------------------------------------------------------
// RangeTokenMap: Initialization methods
// ---------------------------------------------------------------------------
void RangeTokenMap::initializeRegistry() {
XMLMutexLock lockInit(&fMutex);
if (fRegistryInitialized)
return;
fTokenFactory = new TokenFactory();
fTokenRegistry = new RefHashTableOf<RangeTokenElemMap>(109);
fRangeMap = new RefHashTableOf<RangeFactory>(29);
fCategories = new XMLStringPool();
fRegistryInitialized = true;
}
// ---------------------------------------------------------------------------
// RangeTokenMap: Instance methods
// ---------------------------------------------------------------------------
RangeTokenMap* RangeTokenMap::instance() {
if (!fInstance) {
fInstance = new RangeTokenMap();
XMLPlatformUtils::registerLazyData
(
new XMLDeleterFor<RangeTokenMap>(fInstance)
);
}
return (fInstance);
}
/**
* End of file RangeTokenMap.cpp
*/
|
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.3 2001/07/16 21:28:25 knoaman
* fix bug - no delete for the static instance in destructor.
*
* Revision 1.2 2001/05/11 13:26:45 tng
* Copyright update.
*
* Revision 1.1 2001/05/03 18:17:40 knoaman
* Some design changes:
* o Changed the TokenFactory from a single static instance, to a
* normal class. Each RegularExpression object will have its own
* instance of TokenFactory, and that instance will be passed to
* other classes that need to use a TokenFactory to create Token
* objects (with the exception of RangeTokenMap).
* o Added a new class RangeTokenMap to map a the different ranges
* in a given category to a specific RangeFactory object. In the old
* design RangeFactory had dual functionality (act as a Map, and as
* a factory for creating RangeToken(s)). The RangeTokenMap will
* have its own copy of the TokenFactory. There will be only one
* instance of the RangeTokenMap class, and that instance will be
* lazily deleted when XPlatformUtils::Terminate is called.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/regx/RangeTokenMap.hpp>
#include <util/regx/RangeToken.hpp>
#include <util/regx/RegxDefs.hpp>
#include <util/regx/TokenFactory.hpp>
#include <util/regx/RangeFactory.hpp>
#include <util/PlatformUtils.hpp>
#include <util/XMLDeleterFor.hpp>
#include <util/XMLExceptMsgs.hpp>
// ---------------------------------------------------------------------------
// Static member data initialization
// ---------------------------------------------------------------------------
RangeTokenMap* RangeTokenMap::fInstance = 0;
// ---------------------------------------------------------------------------
// RangeTokenElemMap: Constructors and Destructor
// ---------------------------------------------------------------------------
RangeTokenElemMap::RangeTokenElemMap(unsigned int categoryId) :
fCategoryId(categoryId)
, fRange(0)
, fNRange(0)
{
}
RangeTokenElemMap::~RangeTokenElemMap()
{
}
// ---------------------------------------------------------------------------
// RangeTokenMap: Constructors and Destructor
// ---------------------------------------------------------------------------
RangeTokenMap::RangeTokenMap() :
fRegistryInitialized(0)
, fTokenRegistry(0)
, fRangeMap(0)
, fCategories(0)
, fTokenFactory(0) {
}
RangeTokenMap::~RangeTokenMap() {
delete fTokenRegistry;
fTokenRegistry = 0;
delete fRangeMap;
fRangeMap = 0;
delete fCategories;
fCategories = 0;
delete fTokenFactory;
fTokenFactory = 0;
fInstance = 0;
}
// ---------------------------------------------------------------------------
// RangeTokenMap: Getter methods
// ---------------------------------------------------------------------------
RangeToken* RangeTokenMap::getRange(const XMLCh* const keyword,
const bool complement) {
if (fTokenRegistry == 0 || fRangeMap == 0 || fCategories == 0)
return 0;
if (!fTokenRegistry->containsKey(keyword))
return 0;
RangeTokenElemMap* elemMap = 0;
// Use a faux scope to synchronize while we do this
{
XMLMutexLock lockInit(&fMutex);
elemMap = fTokenRegistry->get(keyword);
RangeToken* rangeTok = 0;
if (elemMap->getRangeToken() == 0) {
unsigned int categId = elemMap->getCategoryId();
const XMLCh* categName = fCategories->getValueForId(categId);
RangeFactory* rangeFactory = fRangeMap->get(categName);
if (rangeFactory == 0)
return 0;
rangeFactory->buildRanges();
}
if (complement && ((rangeTok = elemMap->getRangeToken()) != 0)) {
elemMap->setRangeToken((RangeToken*)
RangeToken::complementRanges(rangeTok, fTokenFactory),
complement);
}
}
return (elemMap == 0) ? 0 : elemMap->getRangeToken(complement);
}
// ---------------------------------------------------------------------------
// RangeTokenMap: Putter methods
// ---------------------------------------------------------------------------
void RangeTokenMap::addCategory(const XMLCh* const categoryName) {
if (fCategories)
fCategories->addOrFind(categoryName);
}
void RangeTokenMap::addRangeMap(const XMLCh* const categoryName,
RangeFactory* const rangeFactory) {
if (fRangeMap)
fRangeMap->put((void*)categoryName, rangeFactory);
}
void RangeTokenMap::addKeywordMap(const XMLCh* const keyword,
const XMLCh* const categoryName) {
if (fCategories == 0 || fTokenRegistry == 0)
return;
unsigned int categId = fCategories->getId(categoryName);
if (categId == 0) {
ThrowXML1(RuntimeException, XMLExcepts::Regex_InvalidCategoryName, categoryName);
}
if (fTokenRegistry->containsKey(keyword)) {
RangeTokenElemMap* elemMap = fTokenRegistry->get(keyword);
if (elemMap->getCategoryId() != categId)
elemMap->setCategoryId(categId);
return;
}
fTokenRegistry->put((void*) keyword, new RangeTokenElemMap(categId));
}
// ---------------------------------------------------------------------------
// RangeTokenMap: Setter methods
// ---------------------------------------------------------------------------
void RangeTokenMap::setRangeToken(const XMLCh* const keyword,
RangeToken* const tok,const bool complement) {
if (fTokenRegistry == 0)
return;
if (fTokenRegistry->containsKey(keyword)) {
fTokenRegistry->get(keyword)->setRangeToken(tok, complement);
}
else {
ThrowXML1(RuntimeException, XMLExcepts::Regex_KeywordNotFound, keyword);
}
}
// ---------------------------------------------------------------------------
// RangeTokenMap: Initialization methods
// ---------------------------------------------------------------------------
void RangeTokenMap::initializeRegistry() {
XMLMutexLock lockInit(&fMutex);
if (fRegistryInitialized)
return;
fTokenFactory = new TokenFactory();
fTokenRegistry = new RefHashTableOf<RangeTokenElemMap>(109);
fRangeMap = new RefHashTableOf<RangeFactory>(29);
fCategories = new XMLStringPool();
fRegistryInitialized = true;
}
// ---------------------------------------------------------------------------
// RangeTokenMap: Instance methods
// ---------------------------------------------------------------------------
RangeTokenMap* RangeTokenMap::instance() {
if (!fInstance) {
fInstance = new RangeTokenMap();
XMLPlatformUtils::registerLazyData
(
new XMLDeleterFor<RangeTokenMap>(fInstance)
);
}
return (fInstance);
}
/**
* End of file RangeTokenMap.cpp
*/
|
fix bug - no delete for the static instance in destructor.
|
fix bug - no delete for the static instance in destructor.
git-svn-id: 3ec853389310512053d525963cab269c063bb453@172882 13f79535-47bb-0310-9956-ffa450edef68
|
C++
|
apache-2.0
|
AaronNGray/xerces,AaronNGray/xerces,AaronNGray/xerces,AaronNGray/xerces
|
d6a28e8e834d8f3c9f71a811c7efec6b2a0d9621
|
source/Plugins/Platform/MacOSX/PlatformRemoteAppleBridge.cpp
|
source/Plugins/Platform/MacOSX/PlatformRemoteAppleBridge.cpp
|
//===-- PlatformRemoteAppleBridge.cpp -------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// C Includes
// C++ Includes
#include <string>
#include <vector>
// Other libraries and framework includes
// Project includes
#include "PlatformRemoteAppleBridge.h"
#include "lldb/Breakpoint/BreakpointLocation.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleList.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Host/Host.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/ArchSpec.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/StreamString.h"
using namespace lldb;
using namespace lldb_private;
//------------------------------------------------------------------
/// Default Constructor
//------------------------------------------------------------------
PlatformRemoteAppleBridge::PlatformRemoteAppleBridge()
: PlatformRemoteDarwinDevice () {}
//------------------------------------------------------------------
// Static Variables
//------------------------------------------------------------------
static uint32_t g_initialize_count = 0;
//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
void PlatformRemoteAppleBridge::Initialize() {
PlatformDarwin::Initialize();
if (g_initialize_count++ == 0) {
PluginManager::RegisterPlugin(PlatformRemoteAppleBridge::GetPluginNameStatic(),
PlatformRemoteAppleBridge::GetDescriptionStatic(),
PlatformRemoteAppleBridge::CreateInstance);
}
}
void PlatformRemoteAppleBridge::Terminate() {
if (g_initialize_count > 0) {
if (--g_initialize_count == 0) {
PluginManager::UnregisterPlugin(PlatformRemoteAppleBridge::CreateInstance);
}
}
PlatformDarwin::Terminate();
}
PlatformSP PlatformRemoteAppleBridge::CreateInstance(bool force,
const ArchSpec *arch) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
if (log) {
const char *arch_name;
if (arch && arch->GetArchitectureName())
arch_name = arch->GetArchitectureName();
else
arch_name = "<null>";
const char *triple_cstr =
arch ? arch->GetTriple().getTriple().c_str() : "<null>";
log->Printf("PlatformRemoteAppleBridge::%s(force=%s, arch={%s,%s})",
__FUNCTION__, force ? "true" : "false", arch_name, triple_cstr);
}
bool create = force;
if (!create && arch && arch->IsValid()) {
switch (arch->GetMachine()) {
case llvm::Triple::aarch64: {
const llvm::Triple &triple = arch->GetTriple();
llvm::Triple::VendorType vendor = triple.getVendor();
switch (vendor) {
case llvm::Triple::Apple:
create = true;
break;
#if defined(__APPLE__)
// Only accept "unknown" for the vendor if the host is Apple and
// it "unknown" wasn't specified (it was just returned because it
// was NOT specified)
case llvm::Triple::UnknownArch:
create = !arch->TripleVendorWasSpecified();
break;
#endif
default:
break;
}
if (create) {
switch (triple.getOS()) {
// FIXMEJSM case llvm::Triple::BridgeOS:
break;
default:
create = false;
break;
}
}
} break;
default:
break;
}
}
if (create) {
if (log)
log->Printf("PlatformRemoteAppleBridge::%s() creating platform",
__FUNCTION__);
return lldb::PlatformSP(new PlatformRemoteAppleBridge());
}
if (log)
log->Printf("PlatformRemoteAppleBridge::%s() aborting creation of platform",
__FUNCTION__);
return lldb::PlatformSP();
}
lldb_private::ConstString PlatformRemoteAppleBridge::GetPluginNameStatic() {
static ConstString g_name("remote-bridgeos");
return g_name;
}
const char *PlatformRemoteAppleBridge::GetDescriptionStatic() {
return "Remote BridgeOS platform plug-in.";
}
bool PlatformRemoteAppleBridge::GetSupportedArchitectureAtIndex(uint32_t idx,
ArchSpec &arch) {
ArchSpec system_arch(GetSystemArchitecture());
const ArchSpec::Core system_core = system_arch.GetCore();
switch (system_core) {
default:
switch (idx) {
case 0:
arch.SetTriple("arm64-apple-bridgeos");
return true;
default:
break;
}
break;
case ArchSpec::eCore_arm_arm64:
switch (idx) {
case 0:
arch.SetTriple("arm64-apple-bridgeos");
return true;
default:
break;
}
break;
}
arch.Clear();
return false;
}
void PlatformRemoteAppleBridge::GetDeviceSupportDirectoryNames (std::vector<std::string> &dirnames)
{
dirnames.clear();
dirnames.push_back("BridgeOS DeviceSupport");
}
std::string PlatformRemoteAppleBridge::GetPlatformName ()
{
return "BridgeOS.platform";
}
|
//===-- PlatformRemoteAppleBridge.cpp -------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// C Includes
// C++ Includes
#include <string>
#include <vector>
// Other libraries and framework includes
// Project includes
#include "PlatformRemoteAppleBridge.h"
#include "lldb/Breakpoint/BreakpointLocation.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleList.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Host/Host.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/ArchSpec.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/StreamString.h"
using namespace lldb;
using namespace lldb_private;
//------------------------------------------------------------------
/// Default Constructor
//------------------------------------------------------------------
PlatformRemoteAppleBridge::PlatformRemoteAppleBridge()
: PlatformRemoteDarwinDevice () {}
//------------------------------------------------------------------
// Static Variables
//------------------------------------------------------------------
static uint32_t g_initialize_count = 0;
//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
void PlatformRemoteAppleBridge::Initialize() {
PlatformDarwin::Initialize();
if (g_initialize_count++ == 0) {
PluginManager::RegisterPlugin(PlatformRemoteAppleBridge::GetPluginNameStatic(),
PlatformRemoteAppleBridge::GetDescriptionStatic(),
PlatformRemoteAppleBridge::CreateInstance);
}
}
void PlatformRemoteAppleBridge::Terminate() {
if (g_initialize_count > 0) {
if (--g_initialize_count == 0) {
PluginManager::UnregisterPlugin(PlatformRemoteAppleBridge::CreateInstance);
}
}
PlatformDarwin::Terminate();
}
PlatformSP PlatformRemoteAppleBridge::CreateInstance(bool force,
const ArchSpec *arch) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
if (log) {
const char *arch_name;
if (arch && arch->GetArchitectureName())
arch_name = arch->GetArchitectureName();
else
arch_name = "<null>";
const char *triple_cstr =
arch ? arch->GetTriple().getTriple().c_str() : "<null>";
log->Printf("PlatformRemoteAppleBridge::%s(force=%s, arch={%s,%s})",
__FUNCTION__, force ? "true" : "false", arch_name, triple_cstr);
}
bool create = force;
if (!create && arch && arch->IsValid()) {
switch (arch->GetMachine()) {
case llvm::Triple::aarch64: {
const llvm::Triple &triple = arch->GetTriple();
llvm::Triple::VendorType vendor = triple.getVendor();
switch (vendor) {
case llvm::Triple::Apple:
create = true;
break;
#if defined(__APPLE__)
// Only accept "unknown" for the vendor if the host is Apple and
// it "unknown" wasn't specified (it was just returned because it
// was NOT specified)
case llvm::Triple::UnknownArch:
create = !arch->TripleVendorWasSpecified();
break;
#endif
default:
break;
}
if (create) {
switch (triple.getOS()) {
// NEED_BRIDGEOS_TRIPLE case llvm::Triple::BridgeOS:
break;
default:
create = false;
break;
}
}
} break;
default:
break;
}
}
if (create) {
if (log)
log->Printf("PlatformRemoteAppleBridge::%s() creating platform",
__FUNCTION__);
return lldb::PlatformSP(new PlatformRemoteAppleBridge());
}
if (log)
log->Printf("PlatformRemoteAppleBridge::%s() aborting creation of platform",
__FUNCTION__);
return lldb::PlatformSP();
}
lldb_private::ConstString PlatformRemoteAppleBridge::GetPluginNameStatic() {
static ConstString g_name("remote-bridgeos");
return g_name;
}
const char *PlatformRemoteAppleBridge::GetDescriptionStatic() {
return "Remote BridgeOS platform plug-in.";
}
bool PlatformRemoteAppleBridge::GetSupportedArchitectureAtIndex(uint32_t idx,
ArchSpec &arch) {
ArchSpec system_arch(GetSystemArchitecture());
const ArchSpec::Core system_core = system_arch.GetCore();
switch (system_core) {
default:
switch (idx) {
case 0:
arch.SetTriple("arm64-apple-bridgeos");
return true;
default:
break;
}
break;
case ArchSpec::eCore_arm_arm64:
switch (idx) {
case 0:
arch.SetTriple("arm64-apple-bridgeos");
return true;
default:
break;
}
break;
}
arch.Clear();
return false;
}
void PlatformRemoteAppleBridge::GetDeviceSupportDirectoryNames (std::vector<std::string> &dirnames)
{
dirnames.clear();
dirnames.push_back("BridgeOS DeviceSupport");
}
std::string PlatformRemoteAppleBridge::GetPlatformName ()
{
return "BridgeOS.platform";
}
|
Fix this comment so it is consistent with all the others.
|
Fix this comment so it is consistent with all the others.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@344277 91177308-0d34-0410-b5e6-96231b3b80d8
(cherry picked from commit 35cb2802cfef8329ea5bc5fdd0a11b6f7c709d3b)
|
C++
|
apache-2.0
|
apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb
|
0b7e1474a5ff84fbf9cb446aaa2da4180a16db13
|
src/v4l2/v4l2_property_impl.cpp
|
src/v4l2/v4l2_property_impl.cpp
|
/*
* Copyright 2021 The Imaging Source Europe GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "v4l2_property_impl.h"
#include "V4L2PropertyBackend.h"
#include "logging.h"
#include "v4l2_genicam_mapping.h"
#include <memory>
namespace tcam::property
{
V4L2PropertyIntegerImpl::V4L2PropertyIntegerImpl(struct v4l2_queryctrl* queryctrl,
struct v4l2_ext_control* ctrl,
std::shared_ptr<V4L2PropertyBackend> backend,
const tcam::v4l2::v4l2_genicam_mapping* mapping)
{
m_min = queryctrl->minimum;
m_max = queryctrl->maximum;
m_step = queryctrl->step;
if (m_step == 0)
{
m_step = 1;
}
m_default = ctrl->value;
m_name = (char*)queryctrl->name;
if (mapping)
{
if (!mapping->gen_name.empty())
{
m_name = mapping->gen_name;
}
}
m_v4l2_id = queryctrl->id;
m_cam = backend;
}
int64_t V4L2PropertyIntegerImpl::get_value() const
{
int64_t value = 0;
if (auto ptr = m_cam.lock())
{
ptr->read_control(m_v4l2_id, value);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot retrieve value.");
return -1;
}
return value;
}
bool V4L2PropertyIntegerImpl::set_value(int64_t new_value)
{
if (!valid_value(new_value))
{
return false;
}
if (auto ptr = m_cam.lock())
{
ptr->write_control(m_v4l2_id, new_value);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot write value.");
return false;
}
return true;
}
bool V4L2PropertyIntegerImpl::valid_value(int64_t val)
{
if (val % get_step() != 0)
{
return false;
}
if (get_min() > val || val > get_max())
{
return false;
}
return true;
}
V4L2PropertyDoubleImpl::V4L2PropertyDoubleImpl(struct v4l2_queryctrl* queryctrl,
struct v4l2_ext_control* ctrl,
std::shared_ptr<V4L2PropertyBackend> backend,
const tcam::v4l2::v4l2_genicam_mapping* mapping)
{
m_min = queryctrl->minimum;
m_max = queryctrl->maximum;
m_step = queryctrl->step;
m_default = ctrl->value;
m_name = (char*)queryctrl->name;
if (mapping)
{
if (!mapping->gen_name.empty())
{
m_name = mapping->gen_name;
}
}
m_v4l2_id = queryctrl->id;
m_cam = backend;
}
double V4L2PropertyDoubleImpl::get_value() const
{
int64_t value = 0;
if (auto ptr = m_cam.lock())
{
ptr->read_control(m_v4l2_id, value);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot retrieve value.");
return -1;
}
//SPDLOG_DEBUG("{}: Returning value: {}", m_name, value);
return value;
}
bool V4L2PropertyDoubleImpl::set_value(double new_value)
{
if (!valid_value(new_value))
{
return false;
}
if (auto ptr = m_cam.lock())
{
ptr->write_control(m_v4l2_id, new_value);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot write value.");
return false;
}
return false;
}
bool V4L2PropertyDoubleImpl::valid_value(double val)
{
if (get_min() > val || val > get_max())
{
return false;
}
return true;
}
V4L2PropertyBoolImpl::V4L2PropertyBoolImpl(struct v4l2_queryctrl* queryctrl,
struct v4l2_ext_control* ctrl,
std::shared_ptr<V4L2PropertyBackend> backend,
const tcam::v4l2::v4l2_genicam_mapping* mapping)
{
if (ctrl->value == 0)
{
m_default = false;
}
else
{
m_default = true;
}
m_name = (char*)queryctrl->name;
if (mapping)
{
if (!mapping->gen_name.empty())
{
m_name = mapping->gen_name;
}
}
m_v4l2_id = queryctrl->id;
m_cam = backend;
}
bool V4L2PropertyBoolImpl::get_value() const
{
int64_t value = 0;
if (auto ptr = m_cam.lock())
{
ptr->read_control(m_v4l2_id, value);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot retrieve value.");
return false;
}
//SPDLOG_DEBUG("{}: Returning value: {}", m_name, value);
if (value == 0)
{
return false;
}
return true;
}
bool V4L2PropertyBoolImpl::set_value(bool new_value)
{
int64_t val = 0;
if (new_value)
{
val = 1;
}
if (auto ptr = m_cam.lock())
{
ptr->write_control(m_v4l2_id, val);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot write value.");
return false;
}
return true;
}
V4L2PropertyCommandImpl::V4L2PropertyCommandImpl(struct v4l2_queryctrl* queryctrl,
struct v4l2_ext_control* /*ctrl*/,
std::shared_ptr<V4L2PropertyBackend> backend,
const tcam::v4l2::v4l2_genicam_mapping* mapping)
{
m_name = (char*)queryctrl->name;
if (mapping)
{
if (!mapping->gen_name.empty())
{
m_name = mapping->gen_name;
}
}
m_v4l2_id = queryctrl->id;
m_cam = backend;
}
bool V4L2PropertyCommandImpl::execute()
{
if (auto ptr = m_cam.lock())
{
ptr->write_control(m_v4l2_id, 1);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot write value.");
return false;
}
return true;
}
V4L2PropertyEnumImpl::V4L2PropertyEnumImpl(struct v4l2_queryctrl* queryctrl,
struct v4l2_ext_control* ctrl,
std::shared_ptr<V4L2PropertyBackend> backend,
const tcam::v4l2::v4l2_genicam_mapping* mapping)
{
m_cam = backend;
m_v4l2_id = queryctrl->id;
if (!mapping)
{
m_name = (char*)queryctrl->name;
if (auto ptr = m_cam.lock())
{
m_entries = ptr->get_menu_entries(m_v4l2_id, queryctrl->maximum);
}
else
{
SPDLOG_WARN("Unable to retrieve enum entries during proerty creation.");
}
}
else
{
if (!mapping->gen_name.empty())
{
m_name = mapping->gen_name;
}
else
{
m_name = (char*)queryctrl->name;
}
if (mapping->gen_enum_entries)
{
m_entries = mapping->gen_enum_entries.value();
}
else
{
if (auto ptr = m_cam.lock())
{
m_entries = ptr->get_menu_entries(m_v4l2_id, queryctrl->maximum);
}
else
{
SPDLOG_WARN("Unable to retrieve enum entries during proerty creation.");
}
}
}
m_default = m_entries.at(ctrl->value);
}
bool V4L2PropertyEnumImpl::valid_value(int value)
{
auto it = m_entries.find(value);
if (it == m_entries.end())
{
return false;
}
return true;
}
bool V4L2PropertyEnumImpl::set_value_str(const std::string& new_value)
{
for (auto it = m_entries.begin(); it != m_entries.end(); ++it)
{
if (it->second == new_value)
{
return set_value(it->first);
}
}
return false;
}
bool V4L2PropertyEnumImpl::set_value(int new_value)
{
if (!valid_value(new_value))
{
return false;
}
if (auto ptr = m_cam.lock())
{
if (ptr->write_control(m_v4l2_id, new_value) != 0)
{
SPDLOG_ERROR("Something went wrong while writing {}", m_name);
return false;
}
else
{
//SPDLOG_DEBUG("Wrote {} {}", m_name, new_value);
}
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot write value.");
return false;
}
return false;
}
std::string V4L2PropertyEnumImpl::get_value() const
{
int value = get_value_int();
// TODO: additional checks if key exists
return m_entries.at(value);
}
int V4L2PropertyEnumImpl::get_value_int() const
{
int64_t value = 0;
if (auto ptr = m_cam.lock())
{
ptr->read_control(m_v4l2_id, value);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot retrieve value.");
return -1;
}
return value;
}
std::vector<std::string> V4L2PropertyEnumImpl::get_entries() const
{
std::vector<std::string> v;
for (auto it = m_entries.begin(); it != m_entries.end(); ++it) { v.push_back(it->second); }
return v;
}
} // namespace tcam::property
|
/*
* Copyright 2021 The Imaging Source Europe GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "v4l2_property_impl.h"
#include "V4L2PropertyBackend.h"
#include "logging.h"
#include "v4l2_genicam_mapping.h"
#include <memory>
namespace tcam::property
{
V4L2PropertyIntegerImpl::V4L2PropertyIntegerImpl(struct v4l2_queryctrl* queryctrl,
struct v4l2_ext_control* ctrl,
std::shared_ptr<V4L2PropertyBackend> backend,
const tcam::v4l2::v4l2_genicam_mapping* mapping)
{
m_min = queryctrl->minimum;
m_max = queryctrl->maximum;
m_step = queryctrl->step;
if (m_step == 0)
{
m_step = 1;
}
m_default = ctrl->value;
m_name = (char*)queryctrl->name;
if (mapping)
{
if (!mapping->gen_name.empty())
{
m_name = mapping->gen_name;
}
}
m_v4l2_id = queryctrl->id;
m_cam = backend;
m_flags = (PropertyFlags::Available | PropertyFlags::Implemented);
}
int64_t V4L2PropertyIntegerImpl::get_value() const
{
int64_t value = 0;
if (auto ptr = m_cam.lock())
{
ptr->read_control(m_v4l2_id, value);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot retrieve value.");
return -1;
}
return value;
}
bool V4L2PropertyIntegerImpl::set_value(int64_t new_value)
{
if (!valid_value(new_value))
{
return false;
}
if (auto ptr = m_cam.lock())
{
ptr->write_control(m_v4l2_id, new_value);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot write value.");
return false;
}
return true;
}
bool V4L2PropertyIntegerImpl::valid_value(int64_t val)
{
if (val % get_step() != 0)
{
return false;
}
if (get_min() > val || val > get_max())
{
return false;
}
return true;
}
V4L2PropertyDoubleImpl::V4L2PropertyDoubleImpl(struct v4l2_queryctrl* queryctrl,
struct v4l2_ext_control* ctrl,
std::shared_ptr<V4L2PropertyBackend> backend,
const tcam::v4l2::v4l2_genicam_mapping* mapping)
{
m_min = queryctrl->minimum;
m_max = queryctrl->maximum;
m_step = queryctrl->step;
m_default = ctrl->value;
m_name = (char*)queryctrl->name;
if (mapping)
{
if (!mapping->gen_name.empty())
{
m_name = mapping->gen_name;
}
}
m_v4l2_id = queryctrl->id;
m_cam = backend;
m_flags = (PropertyFlags::Available | PropertyFlags::Implemented);
}
double V4L2PropertyDoubleImpl::get_value() const
{
int64_t value = 0;
if (auto ptr = m_cam.lock())
{
ptr->read_control(m_v4l2_id, value);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot retrieve value.");
return -1;
}
//SPDLOG_DEBUG("{}: Returning value: {}", m_name, value);
return value;
}
bool V4L2PropertyDoubleImpl::set_value(double new_value)
{
if (!valid_value(new_value))
{
return false;
}
if (auto ptr = m_cam.lock())
{
ptr->write_control(m_v4l2_id, new_value);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot write value.");
return false;
}
return false;
}
bool V4L2PropertyDoubleImpl::valid_value(double val)
{
if (get_min() > val || val > get_max())
{
return false;
}
return true;
}
V4L2PropertyBoolImpl::V4L2PropertyBoolImpl(struct v4l2_queryctrl* queryctrl,
struct v4l2_ext_control* ctrl,
std::shared_ptr<V4L2PropertyBackend> backend,
const tcam::v4l2::v4l2_genicam_mapping* mapping)
{
if (ctrl->value == 0)
{
m_default = false;
}
else
{
m_default = true;
}
m_name = (char*)queryctrl->name;
if (mapping)
{
if (!mapping->gen_name.empty())
{
m_name = mapping->gen_name;
}
}
m_v4l2_id = queryctrl->id;
m_cam = backend;
m_flags = (PropertyFlags::Available | PropertyFlags::Implemented);
}
bool V4L2PropertyBoolImpl::get_value() const
{
int64_t value = 0;
if (auto ptr = m_cam.lock())
{
ptr->read_control(m_v4l2_id, value);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot retrieve value.");
return false;
}
//SPDLOG_DEBUG("{}: Returning value: {}", m_name, value);
if (value == 0)
{
return false;
}
return true;
}
bool V4L2PropertyBoolImpl::set_value(bool new_value)
{
int64_t val = 0;
if (new_value)
{
val = 1;
}
if (auto ptr = m_cam.lock())
{
ptr->write_control(m_v4l2_id, val);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot write value.");
return false;
}
return true;
}
V4L2PropertyCommandImpl::V4L2PropertyCommandImpl(struct v4l2_queryctrl* queryctrl,
struct v4l2_ext_control* /*ctrl*/,
std::shared_ptr<V4L2PropertyBackend> backend,
const tcam::v4l2::v4l2_genicam_mapping* mapping)
{
m_name = (char*)queryctrl->name;
if (mapping)
{
if (!mapping->gen_name.empty())
{
m_name = mapping->gen_name;
}
}
m_v4l2_id = queryctrl->id;
m_cam = backend;
m_flags = (PropertyFlags::Available | PropertyFlags::Implemented);
}
bool V4L2PropertyCommandImpl::execute()
{
if (auto ptr = m_cam.lock())
{
ptr->write_control(m_v4l2_id, 1);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot write value.");
return false;
}
return true;
}
V4L2PropertyEnumImpl::V4L2PropertyEnumImpl(struct v4l2_queryctrl* queryctrl,
struct v4l2_ext_control* ctrl,
std::shared_ptr<V4L2PropertyBackend> backend,
const tcam::v4l2::v4l2_genicam_mapping* mapping)
{
m_cam = backend;
m_v4l2_id = queryctrl->id;
if (!mapping)
{
m_name = (char*)queryctrl->name;
if (auto ptr = m_cam.lock())
{
m_entries = ptr->get_menu_entries(m_v4l2_id, queryctrl->maximum);
}
else
{
SPDLOG_WARN("Unable to retrieve enum entries during proerty creation.");
}
}
else
{
if (!mapping->gen_name.empty())
{
m_name = mapping->gen_name;
}
else
{
m_name = (char*)queryctrl->name;
}
if (mapping->gen_enum_entries)
{
m_entries = mapping->gen_enum_entries.value();
}
else
{
if (auto ptr = m_cam.lock())
{
m_entries = ptr->get_menu_entries(m_v4l2_id, queryctrl->maximum);
}
else
{
SPDLOG_WARN("Unable to retrieve enum entries during proerty creation.");
}
}
}
m_flags = (PropertyFlags::Available | PropertyFlags::Implemented);
m_default = m_entries.at(ctrl->value);
}
bool V4L2PropertyEnumImpl::valid_value(int value)
{
auto it = m_entries.find(value);
if (it == m_entries.end())
{
return false;
}
return true;
}
bool V4L2PropertyEnumImpl::set_value_str(const std::string& new_value)
{
for (auto it = m_entries.begin(); it != m_entries.end(); ++it)
{
if (it->second == new_value)
{
return set_value(it->first);
}
}
return false;
}
bool V4L2PropertyEnumImpl::set_value(int new_value)
{
if (!valid_value(new_value))
{
return false;
}
if (auto ptr = m_cam.lock())
{
if (ptr->write_control(m_v4l2_id, new_value) != 0)
{
SPDLOG_ERROR("Something went wrong while writing {}", m_name);
return false;
}
else
{
//SPDLOG_DEBUG("Wrote {} {}", m_name, new_value);
}
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot write value.");
return false;
}
return false;
}
std::string V4L2PropertyEnumImpl::get_value() const
{
int value = get_value_int();
// TODO: additional checks if key exists
return m_entries.at(value);
}
int V4L2PropertyEnumImpl::get_value_int() const
{
int64_t value = 0;
if (auto ptr = m_cam.lock())
{
ptr->read_control(m_v4l2_id, value);
}
else
{
SPDLOG_ERROR("Unable to lock v4l2 device backend. Cannot retrieve value.");
return -1;
}
return value;
}
std::vector<std::string> V4L2PropertyEnumImpl::get_entries() const
{
std::vector<std::string> v;
for (auto it = m_entries.begin(); it != m_entries.end(); ++it) { v.push_back(it->second); }
return v;
}
} // namespace tcam::property
|
Add default flags to properties
|
v4l2: Add default flags to properties
|
C++
|
apache-2.0
|
TheImagingSource/tiscamera,TheImagingSource/tiscamera,TheImagingSource/tiscamera,TheImagingSource/tiscamera
|
5f59ea89b3d9f2a093ffd5fc1911bc70e2c4c39a
|
libsweep/src/protocol.cc
|
libsweep/src/protocol.cc
|
#include <chrono>
#include <thread>
#include "protocol.h"
namespace sweep {
namespace protocol {
typedef struct error {
const char* what; // always literal, do not deallocate
} error;
// Constructor hidden from users
static error_s error_construct(const char* what) {
SWEEP_ASSERT(what);
auto out = new error{what};
return out;
}
const char* error_message(error_s error) {
SWEEP_ASSERT(error);
return error->what;
}
void error_destruct(error_s error) {
SWEEP_ASSERT(error);
delete error;
}
static uint8_t checksum_response_header(response_header_s* v) {
SWEEP_ASSERT(v);
return ((v->cmdStatusByte1 + v->cmdStatusByte2) & 0x3F) + 0x30;
}
static uint8_t checksum_response_param(response_param_s* v) {
SWEEP_ASSERT(v);
return ((v->cmdStatusByte1 + v->cmdStatusByte2) & 0x3F) + 0x30;
}
static uint8_t checksum_response_scan_packet(response_scan_packet_s* v) {
SWEEP_ASSERT(v);
uint64_t checksum = 0;
checksum += v->sync_error;
checksum += v->angle & 0xff00;
checksum += v->angle & 0x00ff;
checksum += v->distance & 0xff00;
checksum += v->distance & 0x00ff;
checksum += v->signal_strength;
return checksum % 255;
}
void write_command(serial::device_s serial, const uint8_t cmd[2], error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(cmd);
SWEEP_ASSERT(error);
cmd_packet_s packet;
packet.cmdByte1 = cmd[0];
packet.cmdByte2 = cmd[1];
packet.cmdParamTerm = '\n';
// pause for 2ms, so the device is never bombarded with back to back commands
std::this_thread::sleep_for(std::chrono::milliseconds(2));
serial::error_s serialerror = nullptr;
serial::device_write(serial, &packet, sizeof(cmd_packet_s), &serialerror);
if (serialerror) {
*error = error_construct("unable to write command");
serial::error_destruct(serialerror);
return;
}
}
void write_command_with_arguments(serial::device_s serial, const uint8_t cmd[2], const uint8_t arg[2], error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(cmd);
SWEEP_ASSERT(arg);
SWEEP_ASSERT(error);
cmd_param_packet_s packet;
packet.cmdByte1 = cmd[0];
packet.cmdByte2 = cmd[1];
packet.cmdParamByte1 = arg[0];
packet.cmdParamByte2 = arg[1];
packet.cmdParamTerm = '\n';
serial::error_s serialerror = nullptr;
serial::device_write(serial, &packet, sizeof(cmd_param_packet_s), &serialerror);
if (serialerror) {
*error = error_construct("unable to write command with arguments");
serial::error_destruct(serialerror);
return;
}
}
void read_response_header(serial::device_s serial, const uint8_t cmd[2], response_header_s* header, error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(cmd);
SWEEP_ASSERT(header);
SWEEP_ASSERT(error);
serial::error_s serialerror = nullptr;
serial::device_read(serial, header, sizeof(response_header_s), &serialerror);
if (serialerror) {
*error = error_construct("unable to read response header");
serial::error_destruct(serialerror);
return;
}
uint8_t checksum = checksum_response_header(header);
if (checksum != header->cmdSum) {
*error = error_construct("invalid response header checksum");
return;
}
bool ok = header->cmdByte1 == cmd[0] && header->cmdByte2 == cmd[1];
if (!ok) {
*error = error_construct("invalid header response commands");
return;
}
}
void read_response_param(serial::device_s serial, const uint8_t cmd[2], response_param_s* param, error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(cmd);
SWEEP_ASSERT(param);
SWEEP_ASSERT(error);
serial::error_s serialerror = nullptr;
serial::device_read(serial, param, sizeof(response_param_s), &serialerror);
if (serialerror) {
*error = error_construct("unable to read response param header");
serial::error_destruct(serialerror);
return;
}
uint8_t checksum = checksum_response_param(param);
if (checksum != param->cmdSum) {
*error = error_construct("invalid response param header checksum");
return;
}
bool ok = param->cmdByte1 == cmd[0] && param->cmdByte2 == cmd[1];
if (!ok) {
*error = error_construct("invalid param response commands");
return;
}
}
void read_response_scan(serial::device_s serial, response_scan_packet_s* scan, error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(scan);
SWEEP_ASSERT(error);
serial::error_s serialerror = nullptr;
serial::device_read(serial, scan, sizeof(response_scan_packet_s), &serialerror);
if (serialerror) {
*error = error_construct("invalid response scan packet checksum");
serial::error_destruct(serialerror);
return;
}
uint8_t checksum = checksum_response_scan_packet(scan);
if (checksum != scan->checksum) {
*error = error_construct("invalid scan response commands");
return;
}
}
void read_response_info_motor_ready(serial::device_s serial, const uint8_t cmd[2], response_info_motor_ready_s* info,
error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(cmd);
SWEEP_ASSERT(info);
SWEEP_ASSERT(error);
serial::error_s serialerror = nullptr;
serial::device_read(serial, info, sizeof(response_info_motor_ready_s), &serialerror);
if (serialerror) {
*error = error_construct("unable to read response motor ready");
serial::error_destruct(serialerror);
return;
}
bool ok = info->cmdByte1 == cmd[0] && info->cmdByte2 == cmd[1];
if (!ok) {
*error = error_construct("invalid motor ready response commands");
return;
}
}
void read_response_info_motor_speed(serial::device_s serial, const uint8_t cmd[2], response_info_motor_speed_s* info,
error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(cmd);
SWEEP_ASSERT(info);
SWEEP_ASSERT(error);
serial::error_s serialerror = nullptr;
serial::device_read(serial, info, sizeof(response_info_motor_speed_s), &serialerror);
if (serialerror) {
*error = error_construct("unable to read response motor info");
serial::error_destruct(serialerror);
return;
}
bool ok = info->cmdByte1 == cmd[0] && info->cmdByte2 == cmd[1];
if (!ok) {
*error = error_construct("invalid motor info response commands");
return;
}
}
void read_response_info_sample_rate(sweep::serial::device_s serial, const uint8_t cmd[2], response_info_sample_rate_s* info,
error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(cmd);
SWEEP_ASSERT(info);
SWEEP_ASSERT(error);
serial::error_s serialerror = nullptr;
serial::device_read(serial, info, sizeof(response_info_sample_rate_s), &serialerror);
if (serialerror) {
*error = error_construct("unable to read response sample rate info");
serial::error_destruct(serialerror);
return;
}
bool ok = info->cmdByte1 == cmd[0] && info->cmdByte2 == cmd[1];
if (!ok) {
*error = error_construct("invalid sample rate info response commands");
return;
}
}
} // ns protocol
} // ns sweep
|
#include <chrono>
#include <thread>
#include "protocol.h"
namespace sweep {
namespace protocol {
typedef struct error {
const char* what; // always literal, do not deallocate
} error;
// Constructor hidden from users
static error_s error_construct(const char* what) {
SWEEP_ASSERT(what);
auto out = new error{what};
return out;
}
const char* error_message(error_s error) {
SWEEP_ASSERT(error);
return error->what;
}
void error_destruct(error_s error) {
SWEEP_ASSERT(error);
delete error;
}
static uint8_t checksum_response_header(const response_header_s& v) {
return ((v.cmdStatusByte1 + v.cmdStatusByte2) & 0x3F) + 0x30;
}
static uint8_t checksum_response_param(const response_param_s& v) {
return ((v.cmdStatusByte1 + v.cmdStatusByte2) & 0x3F) + 0x30;
}
static uint8_t checksum_response_scan_packet(const response_scan_packet_s& v) {
uint64_t checksum = 0;
checksum += v.sync_error;
checksum += v.angle & 0xff00;
checksum += v.angle & 0x00ff;
checksum += v.distance & 0xff00;
checksum += v.distance & 0x00ff;
checksum += v.signal_strength;
return checksum % 255;
}
void write_command(serial::device_s serial, const uint8_t cmd[2], error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(cmd);
SWEEP_ASSERT(error);
cmd_packet_s packet;
packet.cmdByte1 = cmd[0];
packet.cmdByte2 = cmd[1];
packet.cmdParamTerm = '\n';
// pause for 2ms, so the device is never bombarded with back to back commands
std::this_thread::sleep_for(std::chrono::milliseconds(2));
serial::error_s serialerror = nullptr;
serial::device_write(serial, &packet, sizeof(cmd_packet_s), &serialerror);
if (serialerror) {
*error = error_construct("unable to write command");
serial::error_destruct(serialerror);
return;
}
}
void write_command_with_arguments(serial::device_s serial, const uint8_t cmd[2], const uint8_t arg[2], error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(cmd);
SWEEP_ASSERT(arg);
SWEEP_ASSERT(error);
cmd_param_packet_s packet;
packet.cmdByte1 = cmd[0];
packet.cmdByte2 = cmd[1];
packet.cmdParamByte1 = arg[0];
packet.cmdParamByte2 = arg[1];
packet.cmdParamTerm = '\n';
serial::error_s serialerror = nullptr;
serial::device_write(serial, &packet, sizeof(cmd_param_packet_s), &serialerror);
if (serialerror) {
*error = error_construct("unable to write command with arguments");
serial::error_destruct(serialerror);
return;
}
}
void read_response_header(serial::device_s serial, const uint8_t cmd[2], response_header_s* header, error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(cmd);
SWEEP_ASSERT(header);
SWEEP_ASSERT(error);
serial::error_s serialerror = nullptr;
serial::device_read(serial, header, sizeof(response_header_s), &serialerror);
if (serialerror) {
*error = error_construct("unable to read response header");
serial::error_destruct(serialerror);
return;
}
uint8_t checksum = checksum_response_header(*header);
if (checksum != header->cmdSum) {
*error = error_construct("invalid response header checksum");
return;
}
bool ok = header->cmdByte1 == cmd[0] && header->cmdByte2 == cmd[1];
if (!ok) {
*error = error_construct("invalid header response commands");
return;
}
}
void read_response_param(serial::device_s serial, const uint8_t cmd[2], response_param_s* param, error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(cmd);
SWEEP_ASSERT(param);
SWEEP_ASSERT(error);
serial::error_s serialerror = nullptr;
serial::device_read(serial, param, sizeof(response_param_s), &serialerror);
if (serialerror) {
*error = error_construct("unable to read response param header");
serial::error_destruct(serialerror);
return;
}
uint8_t checksum = checksum_response_param(*param);
if (checksum != param->cmdSum) {
*error = error_construct("invalid response param header checksum");
return;
}
bool ok = param->cmdByte1 == cmd[0] && param->cmdByte2 == cmd[1];
if (!ok) {
*error = error_construct("invalid param response commands");
return;
}
}
void read_response_scan(serial::device_s serial, response_scan_packet_s* scan, error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(scan);
SWEEP_ASSERT(error);
serial::error_s serialerror = nullptr;
serial::device_read(serial, scan, sizeof(response_scan_packet_s), &serialerror);
if (serialerror) {
*error = error_construct("invalid response scan packet checksum");
serial::error_destruct(serialerror);
return;
}
uint8_t checksum = checksum_response_scan_packet(*scan);
if (checksum != scan->checksum) {
*error = error_construct("invalid scan response commands");
return;
}
}
void read_response_info_motor_ready(serial::device_s serial, const uint8_t cmd[2], response_info_motor_ready_s* info,
error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(cmd);
SWEEP_ASSERT(info);
SWEEP_ASSERT(error);
serial::error_s serialerror = nullptr;
serial::device_read(serial, info, sizeof(response_info_motor_ready_s), &serialerror);
if (serialerror) {
*error = error_construct("unable to read response motor ready");
serial::error_destruct(serialerror);
return;
}
bool ok = info->cmdByte1 == cmd[0] && info->cmdByte2 == cmd[1];
if (!ok) {
*error = error_construct("invalid motor ready response commands");
return;
}
}
void read_response_info_motor_speed(serial::device_s serial, const uint8_t cmd[2], response_info_motor_speed_s* info,
error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(cmd);
SWEEP_ASSERT(info);
SWEEP_ASSERT(error);
serial::error_s serialerror = nullptr;
serial::device_read(serial, info, sizeof(response_info_motor_speed_s), &serialerror);
if (serialerror) {
*error = error_construct("unable to read response motor info");
serial::error_destruct(serialerror);
return;
}
bool ok = info->cmdByte1 == cmd[0] && info->cmdByte2 == cmd[1];
if (!ok) {
*error = error_construct("invalid motor info response commands");
return;
}
}
void read_response_info_sample_rate(sweep::serial::device_s serial, const uint8_t cmd[2], response_info_sample_rate_s* info,
error_s* error) {
SWEEP_ASSERT(serial);
SWEEP_ASSERT(cmd);
SWEEP_ASSERT(info);
SWEEP_ASSERT(error);
serial::error_s serialerror = nullptr;
serial::device_read(serial, info, sizeof(response_info_sample_rate_s), &serialerror);
if (serialerror) {
*error = error_construct("unable to read response sample rate info");
serial::error_destruct(serialerror);
return;
}
bool ok = info->cmdByte1 == cmd[0] && info->cmdByte2 == cmd[1];
if (!ok) {
*error = error_construct("invalid sample rate info response commands");
return;
}
}
} // ns protocol
} // ns sweep
|
Replace pointer with reference
|
[libsweep/proto] Replace pointer with reference
|
C++
|
mit
|
PeterJohnson/sweep-sdk,scanse/sweep-sdk,PeterJohnson/sweep-sdk,scanse/sweep-sdk,PeterJohnson/sweep-sdk,scanse/sweep-sdk,PeterJohnson/sweep-sdk,PeterJohnson/sweep-sdk,PeterJohnson/sweep-sdk,scanse/sweep-sdk,scanse/sweep-sdk,PeterJohnson/sweep-sdk,scanse/sweep-sdk,scanse/sweep-sdk
|
1bb52903e40b5a4e5e4c5b875e16405c0b62ba60
|
src/taintEngine/taintEngine.cpp
|
src/taintEngine/taintEngine.cpp
|
#include "TaintEngine.h"
#include "Registers.h"
TaintEngine::TaintEngine()
{
/* Init all registers to not tainted */
this->taintedReg[ID_RAX] = (uint64_t)!TAINTED;
this->taintedReg[ID_RBX] = (uint64_t)!TAINTED;
this->taintedReg[ID_RCX] = (uint64_t)!TAINTED;
this->taintedReg[ID_RDX] = (uint64_t)!TAINTED;
this->taintedReg[ID_RDI] = (uint64_t)!TAINTED;
this->taintedReg[ID_RSI] = (uint64_t)!TAINTED;
this->taintedReg[ID_RBP] = (uint64_t)!TAINTED;
this->taintedReg[ID_RSP] = (uint64_t)!TAINTED;
this->taintedReg[ID_R8] = (uint64_t)!TAINTED;
this->taintedReg[ID_R9] = (uint64_t)!TAINTED;
this->taintedReg[ID_R10] = (uint64_t)!TAINTED;
this->taintedReg[ID_R11] = (uint64_t)!TAINTED;
this->taintedReg[ID_R12] = (uint64_t)!TAINTED;
this->taintedReg[ID_R13] = (uint64_t)!TAINTED;
this->taintedReg[ID_R14] = (uint64_t)!TAINTED;
this->taintedReg[ID_R15] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM0] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM1] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM2] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM3] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM4] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM5] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM6] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM7] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM8] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM9] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM10] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM11] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM12] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM13] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM14] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM15] = (uint64_t)!TAINTED;
}
void TaintEngine::init(const TaintEngine &other)
{
this->taintedReg[ID_RAX] = other.taintedReg[ID_RAX];
this->taintedReg[ID_RBX] = other.taintedReg[ID_RBX];
this->taintedReg[ID_RCX] = other.taintedReg[ID_RCX];
this->taintedReg[ID_RDX] = other.taintedReg[ID_RDX];
this->taintedReg[ID_RDI] = other.taintedReg[ID_RDI];
this->taintedReg[ID_RSI] = other.taintedReg[ID_RSI];
this->taintedReg[ID_RBP] = other.taintedReg[ID_RBP];
this->taintedReg[ID_RSP] = other.taintedReg[ID_RSP];
this->taintedReg[ID_R8] = other.taintedReg[ID_R8];
this->taintedReg[ID_R9] = other.taintedReg[ID_R9];
this->taintedReg[ID_R10] = other.taintedReg[ID_R10];
this->taintedReg[ID_R11] = other.taintedReg[ID_R11];
this->taintedReg[ID_R12] = other.taintedReg[ID_R12];
this->taintedReg[ID_R13] = other.taintedReg[ID_R13];
this->taintedReg[ID_R14] = other.taintedReg[ID_R14];
this->taintedReg[ID_R15] = other.taintedReg[ID_R15];
this->taintedReg[ID_XMM0] = other.taintedReg[ID_XMM0];
this->taintedReg[ID_XMM1] = other.taintedReg[ID_XMM1];
this->taintedReg[ID_XMM2] = other.taintedReg[ID_XMM2];
this->taintedReg[ID_XMM3] = other.taintedReg[ID_XMM3];
this->taintedReg[ID_XMM4] = other.taintedReg[ID_XMM4];
this->taintedReg[ID_XMM5] = other.taintedReg[ID_XMM5];
this->taintedReg[ID_XMM6] = other.taintedReg[ID_XMM6];
this->taintedReg[ID_XMM7] = other.taintedReg[ID_XMM7];
this->taintedReg[ID_XMM8] = other.taintedReg[ID_XMM8];
this->taintedReg[ID_XMM9] = other.taintedReg[ID_XMM9];
this->taintedReg[ID_XMM10] = other.taintedReg[ID_XMM10];
this->taintedReg[ID_XMM11] = other.taintedReg[ID_XMM11];
this->taintedReg[ID_XMM12] = other.taintedReg[ID_XMM12];
this->taintedReg[ID_XMM13] = other.taintedReg[ID_XMM13];
this->taintedReg[ID_XMM14] = other.taintedReg[ID_XMM14];
this->taintedReg[ID_XMM15] = other.taintedReg[ID_XMM15];
this->taintedAddresses = other.taintedAddresses;
}
TaintEngine::TaintEngine(const TaintEngine ©)
{
init(copy);
}
TaintEngine::~TaintEngine()
{
}
void TaintEngine::operator=(const TaintEngine &other)
{
init(other);
}
/* Returns true of false if the memory address is currently tainted */
bool TaintEngine::isMemoryTainted(uint64_t addr)
{
std::list<uint64_t>::iterator i;
for(i = this->taintedAddresses.begin(); i != this->taintedAddresses.end(); i++){
if (addr == *i)
return TAINTED;
}
return !TAINTED;
}
/* Returns true of false if the register is currently tainted */
bool TaintEngine::isRegTainted(uint64_t regID)
{
if (regID >= (sizeof(this->taintedReg) / sizeof(this->taintedReg[0])))
return false;
return this->taintedReg[regID];
}
/* Taint the register */
void TaintEngine::taintReg(uint64_t regID)
{
if (regID >= (sizeof(this->taintedReg) / sizeof(this->taintedReg[0])))
return ;
this->taintedReg[regID] = TAINTED;
}
/* Untaint the register */
void TaintEngine::untaintReg(uint64_t regID)
{
if (regID >= (sizeof(this->taintedReg) / sizeof(this->taintedReg[0])))
return ;
this->taintedReg[regID] = !TAINTED;
}
/* Taint the address */
void TaintEngine::taintAddress(uint64_t addr)
{
if (!this->isMemoryTainted(addr))
this->taintedAddresses.push_front(addr);
}
/* Untaint the address */
void TaintEngine::untaintAddress(uint64_t addr)
{
this->taintedAddresses.remove(addr);
}
/*
* Spread the taint in regDst if regSrc is tainted.
* Returns true if a spreading occurs otherwise returns false.
*/
bool TaintEngine::assignmentSpreadTaintRegReg(uint64_t regDst, uint64_t regSrc)
{
if (this->isRegTainted(regSrc)){
this->taintReg(regDst);
return TAINTED;
}
this->untaintReg(regDst);
return !TAINTED;
}
/*
* Untaint the regDst.
* Returns false.
*/
bool TaintEngine::assignmentSpreadTaintRegImm(uint64_t regDst)
{
this->untaintReg(regDst);
return !TAINTED;
}
/*
* Spread the taint in regDst if memSrc is tainted.
* Returns true if a spreading occurs otherwise returns false.
*/
bool TaintEngine::assignmentSpreadTaintRegMem(uint64_t regDst, uint64_t memSrc, uint32_t readSize)
{
for (uint64_t offset = 0; offset != readSize; offset++){
if (this->isMemoryTainted(memSrc+offset)){
this->taintReg(regDst);
return TAINTED;
}
}
this->untaintReg(regDst);
return !TAINTED;
}
/*
* Spread the taint in memDst if memSrc is tainted.
* Returns true if a spreading occurs otherwise returns false.
*/
bool TaintEngine::assignmentSpreadTaintMemMem(uint64_t memDst, uint64_t memSrc, uint32_t readSize)
{
bool isTainted = !TAINTED;
for (uint64_t offset = 0; offset != readSize; offset++){
if (this->isMemoryTainted(memSrc+offset)){
this->taintAddress(memDst+offset);
isTainted = TAINTED;
}
}
return isTainted;
}
/*
* Untaint the memDst.
* Returns false.
*/
bool TaintEngine::assignmentSpreadTaintMemImm(uint64_t memDst, uint32_t writeSize)
{
for (uint64_t offset = 0; offset != writeSize; offset++)
this->untaintAddress(memDst+offset);
return !TAINTED;
}
/*
* Spread the taint in memDst if regSrc is tainted.
* Returns true if a spreading occurs otherwise returns false.
*/
bool TaintEngine::assignmentSpreadTaintMemReg(uint64_t memDst, uint64_t regSrc, uint32_t writeSize)
{
if (this->isRegTainted(regSrc)){
for (uint64_t offset = 0; offset != writeSize; offset++)
this->taintAddress(memDst+offset);
return TAINTED;
}
this->untaintAddress(memDst);
return !TAINTED;
}
/*
* If the reg is tainted, we returns true to taint the SE.
*/
bool TaintEngine::aluSpreadTaintRegImm(uint64_t regDst)
{
return this->isRegTainted(regDst);
}
/*
* If the RegSrc is tainted we taint the regDst, otherwise
* we check if regDst is tainted and returns the status.
*/
bool TaintEngine::aluSpreadTaintRegReg(uint64_t regDst, uint64_t regSrc)
{
if (this->isRegTainted(regSrc)){
this->taintReg(regDst);
return TAINTED;
}
return this->isRegTainted(regDst);
}
/*
* If the Mem is tainted we taint the regDst, otherwise
* we check if regDst is tainted and returns the status.
*/
bool TaintEngine::aluSpreadTaintRegMem(uint64_t regDst, uint64_t memSrc, uint32_t readSize)
{
for (uint64_t offset = 0; offset < readSize; offset++){
if (this->isMemoryTainted(memSrc+offset)){
this->taintReg(regDst);
return TAINTED;
}
}
return this->isRegTainted(regDst);
}
bool TaintEngine::aluSpreadTaintMemImm(uint64_t memDst, uint32_t writeSize)
{
for (uint64_t offset = 0; offset < writeSize; offset++){
if (this->isMemoryTainted(memDst+offset)){
return TAINTED;
}
}
return !TAINTED;
}
bool TaintEngine::aluSpreadTaintMemReg(uint64_t memDst, uint64_t regSrc, uint32_t writeSize)
{
uint64_t offset;
if (this->isRegTainted(regSrc)){
for (offset = 0; offset != writeSize; offset++)
this->taintAddress(memDst+offset);
return TAINTED;
}
for (offset = 0; offset != writeSize; offset++){
if (this->isMemoryTainted(memDst+offset))
return TAINTED;
}
return !TAINTED;
}
|
#include "TaintEngine.h"
#include "Registers.h"
TaintEngine::TaintEngine()
{
/* Init all registers to not tainted */
this->taintedReg[ID_RAX] = (uint64_t)!TAINTED;
this->taintedReg[ID_RBX] = (uint64_t)!TAINTED;
this->taintedReg[ID_RCX] = (uint64_t)!TAINTED;
this->taintedReg[ID_RDX] = (uint64_t)!TAINTED;
this->taintedReg[ID_RDI] = (uint64_t)!TAINTED;
this->taintedReg[ID_RSI] = (uint64_t)!TAINTED;
this->taintedReg[ID_RBP] = (uint64_t)!TAINTED;
this->taintedReg[ID_RSP] = (uint64_t)!TAINTED;
this->taintedReg[ID_R8] = (uint64_t)!TAINTED;
this->taintedReg[ID_R9] = (uint64_t)!TAINTED;
this->taintedReg[ID_R10] = (uint64_t)!TAINTED;
this->taintedReg[ID_R11] = (uint64_t)!TAINTED;
this->taintedReg[ID_R12] = (uint64_t)!TAINTED;
this->taintedReg[ID_R13] = (uint64_t)!TAINTED;
this->taintedReg[ID_R14] = (uint64_t)!TAINTED;
this->taintedReg[ID_R15] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM0] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM1] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM2] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM3] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM4] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM5] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM6] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM7] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM8] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM9] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM10] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM11] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM12] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM13] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM14] = (uint64_t)!TAINTED;
this->taintedReg[ID_XMM15] = (uint64_t)!TAINTED;
}
void TaintEngine::init(const TaintEngine &other)
{
this->taintedReg[ID_RAX] = other.taintedReg[ID_RAX];
this->taintedReg[ID_RBX] = other.taintedReg[ID_RBX];
this->taintedReg[ID_RCX] = other.taintedReg[ID_RCX];
this->taintedReg[ID_RDX] = other.taintedReg[ID_RDX];
this->taintedReg[ID_RDI] = other.taintedReg[ID_RDI];
this->taintedReg[ID_RSI] = other.taintedReg[ID_RSI];
this->taintedReg[ID_RBP] = other.taintedReg[ID_RBP];
this->taintedReg[ID_RSP] = other.taintedReg[ID_RSP];
this->taintedReg[ID_R8] = other.taintedReg[ID_R8];
this->taintedReg[ID_R9] = other.taintedReg[ID_R9];
this->taintedReg[ID_R10] = other.taintedReg[ID_R10];
this->taintedReg[ID_R11] = other.taintedReg[ID_R11];
this->taintedReg[ID_R12] = other.taintedReg[ID_R12];
this->taintedReg[ID_R13] = other.taintedReg[ID_R13];
this->taintedReg[ID_R14] = other.taintedReg[ID_R14];
this->taintedReg[ID_R15] = other.taintedReg[ID_R15];
this->taintedReg[ID_XMM0] = other.taintedReg[ID_XMM0];
this->taintedReg[ID_XMM1] = other.taintedReg[ID_XMM1];
this->taintedReg[ID_XMM2] = other.taintedReg[ID_XMM2];
this->taintedReg[ID_XMM3] = other.taintedReg[ID_XMM3];
this->taintedReg[ID_XMM4] = other.taintedReg[ID_XMM4];
this->taintedReg[ID_XMM5] = other.taintedReg[ID_XMM5];
this->taintedReg[ID_XMM6] = other.taintedReg[ID_XMM6];
this->taintedReg[ID_XMM7] = other.taintedReg[ID_XMM7];
this->taintedReg[ID_XMM8] = other.taintedReg[ID_XMM8];
this->taintedReg[ID_XMM9] = other.taintedReg[ID_XMM9];
this->taintedReg[ID_XMM10] = other.taintedReg[ID_XMM10];
this->taintedReg[ID_XMM11] = other.taintedReg[ID_XMM11];
this->taintedReg[ID_XMM12] = other.taintedReg[ID_XMM12];
this->taintedReg[ID_XMM13] = other.taintedReg[ID_XMM13];
this->taintedReg[ID_XMM14] = other.taintedReg[ID_XMM14];
this->taintedReg[ID_XMM15] = other.taintedReg[ID_XMM15];
this->taintedAddresses = other.taintedAddresses;
}
TaintEngine::TaintEngine(const TaintEngine ©)
{
init(copy);
}
TaintEngine::~TaintEngine()
{
}
void TaintEngine::operator=(const TaintEngine &other)
{
init(other);
}
/* Returns true of false if the memory address is currently tainted */
bool TaintEngine::isMemoryTainted(uint64_t addr)
{
std::list<uint64_t>::iterator i;
for(i = this->taintedAddresses.begin(); i != this->taintedAddresses.end(); i++){
if (addr == *i)
return TAINTED;
}
return !TAINTED;
}
/* Returns true of false if the register is currently tainted */
bool TaintEngine::isRegTainted(uint64_t regID)
{
if (regID >= (sizeof(this->taintedReg) / sizeof(this->taintedReg[0])))
return !TAINTED;
return this->taintedReg[regID];
}
/* Taint the register */
void TaintEngine::taintReg(uint64_t regID)
{
if (regID >= (sizeof(this->taintedReg) / sizeof(this->taintedReg[0])))
return ;
this->taintedReg[regID] = TAINTED;
}
/* Untaint the register */
void TaintEngine::untaintReg(uint64_t regID)
{
if (regID >= (sizeof(this->taintedReg) / sizeof(this->taintedReg[0])))
return ;
this->taintedReg[regID] = !TAINTED;
}
/* Taint the address */
void TaintEngine::taintAddress(uint64_t addr)
{
if (!this->isMemoryTainted(addr))
this->taintedAddresses.push_front(addr);
}
/* Untaint the address */
void TaintEngine::untaintAddress(uint64_t addr)
{
this->taintedAddresses.remove(addr);
}
/*
* Spread the taint in regDst if regSrc is tainted.
* Returns true if a spreading occurs otherwise returns false.
*/
bool TaintEngine::assignmentSpreadTaintRegReg(uint64_t regDst, uint64_t regSrc)
{
if (this->isRegTainted(regSrc)){
this->taintReg(regDst);
return TAINTED;
}
this->untaintReg(regDst);
return !TAINTED;
}
/*
* Untaint the regDst.
* Returns false.
*/
bool TaintEngine::assignmentSpreadTaintRegImm(uint64_t regDst)
{
this->untaintReg(regDst);
return !TAINTED;
}
/*
* Spread the taint in regDst if memSrc is tainted.
* Returns true if a spreading occurs otherwise returns false.
*/
bool TaintEngine::assignmentSpreadTaintRegMem(uint64_t regDst, uint64_t memSrc, uint32_t readSize)
{
for (uint64_t offset = 0; offset != readSize; offset++){
if (this->isMemoryTainted(memSrc+offset)){
this->taintReg(regDst);
return TAINTED;
}
}
this->untaintReg(regDst);
return !TAINTED;
}
/*
* Spread the taint in memDst if memSrc is tainted.
* Returns true if a spreading occurs otherwise returns false.
*/
bool TaintEngine::assignmentSpreadTaintMemMem(uint64_t memDst, uint64_t memSrc, uint32_t readSize)
{
bool isTainted = !TAINTED;
for (uint64_t offset = 0; offset != readSize; offset++){
if (this->isMemoryTainted(memSrc+offset)){
this->taintAddress(memDst+offset);
isTainted = TAINTED;
}
}
return isTainted;
}
/*
* Untaint the memDst.
* Returns false.
*/
bool TaintEngine::assignmentSpreadTaintMemImm(uint64_t memDst, uint32_t writeSize)
{
for (uint64_t offset = 0; offset != writeSize; offset++)
this->untaintAddress(memDst+offset);
return !TAINTED;
}
/*
* Spread the taint in memDst if regSrc is tainted.
* Returns true if a spreading occurs otherwise returns false.
*/
bool TaintEngine::assignmentSpreadTaintMemReg(uint64_t memDst, uint64_t regSrc, uint32_t writeSize)
{
if (this->isRegTainted(regSrc)){
for (uint64_t offset = 0; offset != writeSize; offset++)
this->taintAddress(memDst+offset);
return TAINTED;
}
this->untaintAddress(memDst);
return !TAINTED;
}
/*
* If the reg is tainted, we returns true to taint the SE.
*/
bool TaintEngine::aluSpreadTaintRegImm(uint64_t regDst)
{
return this->isRegTainted(regDst);
}
/*
* If the RegSrc is tainted we taint the regDst, otherwise
* we check if regDst is tainted and returns the status.
*/
bool TaintEngine::aluSpreadTaintRegReg(uint64_t regDst, uint64_t regSrc)
{
if (this->isRegTainted(regSrc)){
this->taintReg(regDst);
return TAINTED;
}
return this->isRegTainted(regDst);
}
/*
* If the Mem is tainted we taint the regDst, otherwise
* we check if regDst is tainted and returns the status.
*/
bool TaintEngine::aluSpreadTaintRegMem(uint64_t regDst, uint64_t memSrc, uint32_t readSize)
{
for (uint64_t offset = 0; offset < readSize; offset++){
if (this->isMemoryTainted(memSrc+offset)){
this->taintReg(regDst);
return TAINTED;
}
}
return this->isRegTainted(regDst);
}
bool TaintEngine::aluSpreadTaintMemImm(uint64_t memDst, uint32_t writeSize)
{
for (uint64_t offset = 0; offset < writeSize; offset++){
if (this->isMemoryTainted(memDst+offset)){
return TAINTED;
}
}
return !TAINTED;
}
bool TaintEngine::aluSpreadTaintMemReg(uint64_t memDst, uint64_t regSrc, uint32_t writeSize)
{
uint64_t offset;
if (this->isRegTainted(regSrc)){
for (offset = 0; offset != writeSize; offset++)
this->taintAddress(memDst+offset);
return TAINTED;
}
for (offset = 0; offset != writeSize; offset++){
if (this->isMemoryTainted(memDst+offset))
return TAINTED;
}
return !TAINTED;
}
|
Use define instead of hard constant
|
Use define instead of hard constant
|
C++
|
apache-2.0
|
JonathanSalwan/Triton,JonathanSalwan/Triton,JonathanSalwan/Triton,JonathanSalwan/Triton,JonathanSalwan/Triton
|
5be4466fd7fae5a77e6c9b19421d812178992249
|
hardware/arduino/sam/libraries/SPI/SPI.cpp
|
hardware/arduino/sam/libraries/SPI/SPI.cpp
|
/*
* Copyright (c) 2010 by Cristian Maglie <[email protected]>
* Copyright (c) 2014 by Paul Stoffregen <[email protected]> (Transaction API)
* SPI Master library for arduino.
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of either the GNU General Public License version 2
* or the GNU Lesser General Public License version 2.1, both as
* published by the Free Software Foundation.
*/
#include "SPI.h"
SPIClass::SPIClass(Spi *_spi, uint32_t _id, void(*_initCb)(void)) :
spi(_spi), id(_id), initCb(_initCb), initialized(false)
{
// Empty
}
void SPIClass::begin() {
init();
// NPCS control is left to the user
// Default speed set to 4Mhz
setClockDivider(BOARD_SPI_DEFAULT_SS, 21);
setDataMode(BOARD_SPI_DEFAULT_SS, SPI_MODE0);
setBitOrder(BOARD_SPI_DEFAULT_SS, MSBFIRST);
}
void SPIClass::begin(uint8_t _pin) {
init();
uint32_t spiPin = BOARD_PIN_TO_SPI_PIN(_pin);
PIO_Configure(
g_APinDescription[spiPin].pPort,
g_APinDescription[spiPin].ulPinType,
g_APinDescription[spiPin].ulPin,
g_APinDescription[spiPin].ulPinConfiguration);
// Default speed set to 4Mhz
setClockDivider(_pin, 21);
setDataMode(_pin, SPI_MODE0);
setBitOrder(_pin, MSBFIRST);
}
void SPIClass::init() {
if (initialized)
return;
interruptMode = 0;
interruptSave = 0;
interruptMask[0] = 0;
interruptMask[1] = 0;
interruptMask[2] = 0;
interruptMask[3] = 0;
initCb();
SPI_Configure(spi, id, SPI_MR_MSTR | SPI_MR_PS | SPI_MR_MODFDIS);
SPI_Enable(spi);
initialized = true;
}
#ifndef interruptsStatus
#define interruptsStatus() __interruptsStatus()
static inline unsigned char __interruptsStatus(void) __attribute__((always_inline, unused));
static inline unsigned char __interruptsStatus(void) {
unsigned int primask, faultmask;
asm volatile ("mrs %0, primask" : "=r" (primask));
if (primask) return 0;
asm volatile ("mrs %0, faultmask" : "=r" (faultmask));
if (faultmask) return 0;
return 1;
}
#endif
void SPIClass::usingInterrupt(uint8_t interruptNumber)
{
uint8_t irestore;
irestore = interruptsStatus();
noInterrupts();
if (interruptMode < 16) {
if (interruptNumber > NUM_DIGITAL_PINS) {
interruptMode = 16;
} else {
Pio *pio = g_APinDescription[interruptNumber].pPort;
uint32_t mask = g_APinDescription[interruptNumber].ulPin;
if (pio == PIOA) {
interruptMode |= 1;
interruptMask[0] |= mask;
} else if (pio == PIOB) {
interruptMode |= 2;
interruptMask[1] |= mask;
} else if (pio == PIOC) {
interruptMode |= 4;
interruptMask[2] |= mask;
} else if (pio == PIOD) {
interruptMode |= 8;
interruptMask[3] |= mask;
} else {
interruptMode = 16;
}
}
}
if (irestore) interrupts();
}
void SPIClass::beginTransaction(uint8_t pin, SPISettings settings)
{
uint8_t mode = interruptMode;
if (mode > 0) {
if (mode < 16) {
if (mode & 1) PIOA->PIO_IDR = interruptMask[0];
if (mode & 2) PIOB->PIO_IDR = interruptMask[1];
if (mode & 4) PIOC->PIO_IDR = interruptMask[2];
if (mode & 8) PIOD->PIO_IDR = interruptMask[3];
} else {
interruptSave = interruptsStatus();
noInterrupts();
}
}
uint32_t ch = BOARD_PIN_TO_SPI_CHANNEL(pin);
bitOrder[ch] = settings.border;
SPI_ConfigureNPCS(spi, ch, settings.config);
//setBitOrder(pin, settings.border);
//setDataMode(pin, settings.datamode);
//setClockDivider(pin, settings.clockdiv);
}
void SPIClass::endTransaction(void)
{
uint8_t mode = interruptMode;
if (mode > 0) {
if (mode < 16) {
if (mode & 1) PIOA->PIO_IER = interruptMask[0];
if (mode & 2) PIOB->PIO_IER = interruptMask[1];
if (mode & 4) PIOC->PIO_IER = interruptMask[2];
if (mode & 8) PIOD->PIO_IER = interruptMask[3];
} else {
if (interruptSave) interrupts();
}
}
}
void SPIClass::end(uint8_t _pin) {
uint32_t spiPin = BOARD_PIN_TO_SPI_PIN(_pin);
// Setting the pin as INPUT will disconnect it from SPI peripheral
pinMode(spiPin, INPUT);
}
void SPIClass::end() {
SPI_Disable(spi);
initialized = false;
}
void SPIClass::setBitOrder(uint8_t _pin, BitOrder _bitOrder) {
uint32_t ch = BOARD_PIN_TO_SPI_CHANNEL(_pin);
bitOrder[ch] = _bitOrder;
}
void SPIClass::setDataMode(uint8_t _pin, uint8_t _mode) {
uint32_t ch = BOARD_PIN_TO_SPI_CHANNEL(_pin);
mode[ch] = _mode | SPI_CSR_CSAAT;
// SPI_CSR_DLYBCT(1) keeps CS enabled for 32 MCLK after a completed
// transfer. Some device needs that for working properly.
SPI_ConfigureNPCS(spi, ch, mode[ch] | SPI_CSR_SCBR(divider[ch]) | SPI_CSR_DLYBCT(1));
}
void SPIClass::setClockDivider(uint8_t _pin, uint8_t _divider) {
uint32_t ch = BOARD_PIN_TO_SPI_CHANNEL(_pin);
divider[ch] = _divider;
// SPI_CSR_DLYBCT(1) keeps CS enabled for 32 MCLK after a completed
// transfer. Some device needs that for working properly.
SPI_ConfigureNPCS(spi, ch, mode[ch] | SPI_CSR_SCBR(divider[ch]) | SPI_CSR_DLYBCT(1));
}
byte SPIClass::transfer(byte _pin, uint8_t _data, SPITransferMode _mode) {
uint32_t ch = BOARD_PIN_TO_SPI_CHANNEL(_pin);
// Reverse bit order
if (bitOrder[ch] == LSBFIRST)
_data = __REV(__RBIT(_data));
uint32_t d = _data | SPI_PCS(ch);
if (_mode == SPI_LAST)
d |= SPI_TDR_LASTXFER;
// SPI_Write(spi, _channel, _data);
while ((spi->SPI_SR & SPI_SR_TDRE) == 0)
;
spi->SPI_TDR = d;
// return SPI_Read(spi);
while ((spi->SPI_SR & SPI_SR_RDRF) == 0)
;
d = spi->SPI_RDR;
// Reverse bit order
if (bitOrder[ch] == LSBFIRST)
d = __REV(__RBIT(d));
return d & 0xFF;
}
uint16_t SPIClass::transfer16(byte _pin, uint16_t _data, SPITransferMode _mode) {
union { uint16_t val; struct { uint8_t lsb; uint8_t msb; }; } t;
uint32_t ch = BOARD_PIN_TO_SPI_CHANNEL(_pin);
t.val = _data;
if (bitOrder[ch] == LSBFIRST) {
t.lsb = transfer(_pin, t.lsb, _mode);
t.msb = transfer(_pin, t.msb, _mode);
} else {
t.msb = transfer(_pin, t.msb, _mode);
t.lsb = transfer(_pin, t.lsb, _mode);
}
return t.val;
}
void SPIClass::transfer(byte _pin, void *_buf, size_t _count, SPITransferMode _mode) {
if (_count == 0)
return;
uint8_t *buffer = (uint8_t *)_buf;
if (_count == 1) {
*buffer = transfer(_pin, *buffer, _mode);
return;
}
uint32_t ch = BOARD_PIN_TO_SPI_CHANNEL(_pin);
bool reverse = (bitOrder[ch] == LSBFIRST);
// Send the first byte
uint32_t d = *buffer;
if (reverse)
d = __REV(__RBIT(d));
while ((spi->SPI_SR & SPI_SR_TDRE) == 0)
;
spi->SPI_TDR = d | SPI_PCS(ch);
while (_count > 1) {
// Prepare next byte
d = *(buffer+1);
if (reverse)
d = __REV(__RBIT(d));
if (_count == 2 && _mode == SPI_LAST)
d |= SPI_TDR_LASTXFER;
// Read transferred byte and send next one straight away
while ((spi->SPI_SR & SPI_SR_RDRF) == 0)
;
uint8_t r = spi->SPI_RDR;
spi->SPI_TDR = d | SPI_PCS(ch);
// Save read byte
if (reverse)
r = __REV(__RBIT(r));
*buffer = r;
buffer++;
_count--;
}
// Receive the last transferred byte
while ((spi->SPI_SR & SPI_SR_RDRF) == 0)
;
uint8_t r = spi->SPI_RDR;
if (reverse)
r = __REV(__RBIT(r));
*buffer = r;
}
void SPIClass::attachInterrupt(void) {
// Should be enableInterrupt()
}
void SPIClass::detachInterrupt(void) {
// Should be disableInterrupt()
}
#if SPI_INTERFACES_COUNT > 0
static void SPI_0_Init(void) {
PIO_Configure(
g_APinDescription[PIN_SPI_MOSI].pPort,
g_APinDescription[PIN_SPI_MOSI].ulPinType,
g_APinDescription[PIN_SPI_MOSI].ulPin,
g_APinDescription[PIN_SPI_MOSI].ulPinConfiguration);
PIO_Configure(
g_APinDescription[PIN_SPI_MISO].pPort,
g_APinDescription[PIN_SPI_MISO].ulPinType,
g_APinDescription[PIN_SPI_MISO].ulPin,
g_APinDescription[PIN_SPI_MISO].ulPinConfiguration);
PIO_Configure(
g_APinDescription[PIN_SPI_SCK].pPort,
g_APinDescription[PIN_SPI_SCK].ulPinType,
g_APinDescription[PIN_SPI_SCK].ulPin,
g_APinDescription[PIN_SPI_SCK].ulPinConfiguration);
}
SPIClass SPI(SPI_INTERFACE, SPI_INTERFACE_ID, SPI_0_Init);
#endif
|
/*
* Copyright (c) 2010 by Cristian Maglie <[email protected]>
* Copyright (c) 2014 by Paul Stoffregen <[email protected]> (Transaction API)
* SPI Master library for arduino.
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of either the GNU General Public License version 2
* or the GNU Lesser General Public License version 2.1, both as
* published by the Free Software Foundation.
*/
#include "SPI.h"
SPIClass::SPIClass(Spi *_spi, uint32_t _id, void(*_initCb)(void)) :
spi(_spi), id(_id), initCb(_initCb), initialized(false)
{
// Empty
}
void SPIClass::begin() {
init();
// NPCS control is left to the user
// Default speed set to 4Mhz
setClockDivider(BOARD_SPI_DEFAULT_SS, 21);
setDataMode(BOARD_SPI_DEFAULT_SS, SPI_MODE0);
setBitOrder(BOARD_SPI_DEFAULT_SS, MSBFIRST);
}
void SPIClass::begin(uint8_t _pin) {
init();
uint32_t spiPin = BOARD_PIN_TO_SPI_PIN(_pin);
PIO_Configure(
g_APinDescription[spiPin].pPort,
g_APinDescription[spiPin].ulPinType,
g_APinDescription[spiPin].ulPin,
g_APinDescription[spiPin].ulPinConfiguration);
// Default speed set to 4Mhz
setClockDivider(_pin, 21);
setDataMode(_pin, SPI_MODE0);
setBitOrder(_pin, MSBFIRST);
}
void SPIClass::init() {
if (initialized)
return;
interruptMode = 0;
interruptSave = 0;
interruptMask[0] = 0;
interruptMask[1] = 0;
interruptMask[2] = 0;
interruptMask[3] = 0;
initCb();
SPI_Configure(spi, id, SPI_MR_MSTR | SPI_MR_PS | SPI_MR_MODFDIS);
SPI_Enable(spi);
initialized = true;
}
#ifndef interruptsStatus
#define interruptsStatus() __interruptsStatus()
static inline unsigned char __interruptsStatus(void) __attribute__((always_inline, unused));
static inline unsigned char __interruptsStatus(void) {
unsigned int primask, faultmask;
asm volatile ("mrs %0, primask" : "=r" (primask));
if (primask) return 0;
asm volatile ("mrs %0, faultmask" : "=r" (faultmask));
if (faultmask) return 0;
return 1;
}
#endif
void SPIClass::usingInterrupt(uint8_t interruptNumber)
{
uint8_t irestore;
irestore = interruptsStatus();
noInterrupts();
if (interruptMode < 16) {
if (interruptNumber > NUM_DIGITAL_PINS) {
interruptMode = 16;
} else {
Pio *pio = g_APinDescription[interruptNumber].pPort;
uint32_t mask = g_APinDescription[interruptNumber].ulPin;
if (pio == PIOA) {
interruptMode |= 1;
interruptMask[0] |= mask;
} else if (pio == PIOB) {
interruptMode |= 2;
interruptMask[1] |= mask;
} else if (pio == PIOC) {
interruptMode |= 4;
interruptMask[2] |= mask;
} else if (pio == PIOD) {
interruptMode |= 8;
interruptMask[3] |= mask;
} else {
interruptMode = 16;
}
}
}
if (irestore) interrupts();
}
void SPIClass::beginTransaction(uint8_t pin, SPISettings settings)
{
uint8_t mode = interruptMode;
if (mode > 0) {
if (mode < 16) {
if (mode & 1) PIOA->PIO_IDR = interruptMask[0];
if (mode & 2) PIOB->PIO_IDR = interruptMask[1];
if (mode & 4) PIOC->PIO_IDR = interruptMask[2];
if (mode & 8) PIOD->PIO_IDR = interruptMask[3];
} else {
interruptSave = interruptsStatus();
noInterrupts();
}
}
uint32_t ch = BOARD_PIN_TO_SPI_CHANNEL(pin);
bitOrder[ch] = settings.border;
SPI_ConfigureNPCS(spi, ch, settings.config);
//setBitOrder(pin, settings.border);
//setDataMode(pin, settings.datamode);
//setClockDivider(pin, settings.clockdiv);
}
void SPIClass::endTransaction(void)
{
uint8_t mode = interruptMode;
if (mode > 0) {
if (mode < 16) {
if (mode & 1) PIOA->PIO_IER = interruptMask[0];
if (mode & 2) PIOB->PIO_IER = interruptMask[1];
if (mode & 4) PIOC->PIO_IER = interruptMask[2];
if (mode & 8) PIOD->PIO_IER = interruptMask[3];
} else {
if (interruptSave) interrupts();
}
}
}
void SPIClass::end(uint8_t _pin) {
uint32_t spiPin = BOARD_PIN_TO_SPI_PIN(_pin);
// Setting the pin as INPUT will disconnect it from SPI peripheral
pinMode(spiPin, INPUT);
}
void SPIClass::end() {
SPI_Disable(spi);
initialized = false;
}
void SPIClass::setBitOrder(uint8_t _pin, BitOrder _bitOrder) {
uint32_t ch = BOARD_PIN_TO_SPI_CHANNEL(_pin);
bitOrder[ch] = _bitOrder;
}
void SPIClass::setDataMode(uint8_t _pin, uint8_t _mode) {
uint32_t ch = BOARD_PIN_TO_SPI_CHANNEL(_pin);
mode[ch] = _mode | SPI_CSR_CSAAT;
// SPI_CSR_DLYBCT(1) keeps CS enabled for 32 MCLK after a completed
// transfer. Some device needs that for working properly.
SPI_ConfigureNPCS(spi, ch, mode[ch] | SPI_CSR_SCBR(divider[ch]) | SPI_CSR_DLYBCT(1));
}
void SPIClass::setClockDivider(uint8_t _pin, uint8_t _divider) {
uint32_t ch = BOARD_PIN_TO_SPI_CHANNEL(_pin);
divider[ch] = _divider;
// SPI_CSR_DLYBCT(1) keeps CS enabled for 32 MCLK after a completed
// transfer. Some device needs that for working properly.
SPI_ConfigureNPCS(spi, ch, mode[ch] | SPI_CSR_SCBR(divider[ch]) | SPI_CSR_DLYBCT(1));
}
byte SPIClass::transfer(byte _pin, uint8_t _data, SPITransferMode _mode) {
uint32_t ch = BOARD_PIN_TO_SPI_CHANNEL(_pin);
// Reverse bit order
if (bitOrder[ch] == LSBFIRST)
_data = __REV(__RBIT(_data));
uint32_t d = _data | SPI_PCS(ch);
if (_mode == SPI_LAST)
d |= SPI_TDR_LASTXFER;
// SPI_Write(spi, _channel, _data);
while ((spi->SPI_SR & SPI_SR_TDRE) == 0)
;
spi->SPI_TDR = d;
// return SPI_Read(spi);
while ((spi->SPI_SR & SPI_SR_RDRF) == 0)
;
d = spi->SPI_RDR;
// Reverse bit order
if (bitOrder[ch] == LSBFIRST)
d = __REV(__RBIT(d));
return d & 0xFF;
}
uint16_t SPIClass::transfer16(byte _pin, uint16_t _data, SPITransferMode _mode) {
union { uint16_t val; struct { uint8_t lsb; uint8_t msb; }; } t;
uint32_t ch = BOARD_PIN_TO_SPI_CHANNEL(_pin);
t.val = _data;
if (bitOrder[ch] == LSBFIRST) {
t.lsb = transfer(_pin, t.lsb, SPI_CONTINUE);
t.msb = transfer(_pin, t.msb, _mode);
} else {
t.msb = transfer(_pin, t.msb, SPI_CONTINUE);
t.lsb = transfer(_pin, t.lsb, _mode);
}
return t.val;
}
void SPIClass::transfer(byte _pin, void *_buf, size_t _count, SPITransferMode _mode) {
if (_count == 0)
return;
uint8_t *buffer = (uint8_t *)_buf;
if (_count == 1) {
*buffer = transfer(_pin, *buffer, _mode);
return;
}
uint32_t ch = BOARD_PIN_TO_SPI_CHANNEL(_pin);
bool reverse = (bitOrder[ch] == LSBFIRST);
// Send the first byte
uint32_t d = *buffer;
if (reverse)
d = __REV(__RBIT(d));
while ((spi->SPI_SR & SPI_SR_TDRE) == 0)
;
spi->SPI_TDR = d | SPI_PCS(ch);
while (_count > 1) {
// Prepare next byte
d = *(buffer+1);
if (reverse)
d = __REV(__RBIT(d));
if (_count == 2 && _mode == SPI_LAST)
d |= SPI_TDR_LASTXFER;
// Read transferred byte and send next one straight away
while ((spi->SPI_SR & SPI_SR_RDRF) == 0)
;
uint8_t r = spi->SPI_RDR;
spi->SPI_TDR = d | SPI_PCS(ch);
// Save read byte
if (reverse)
r = __REV(__RBIT(r));
*buffer = r;
buffer++;
_count--;
}
// Receive the last transferred byte
while ((spi->SPI_SR & SPI_SR_RDRF) == 0)
;
uint8_t r = spi->SPI_RDR;
if (reverse)
r = __REV(__RBIT(r));
*buffer = r;
}
void SPIClass::attachInterrupt(void) {
// Should be enableInterrupt()
}
void SPIClass::detachInterrupt(void) {
// Should be disableInterrupt()
}
#if SPI_INTERFACES_COUNT > 0
static void SPI_0_Init(void) {
PIO_Configure(
g_APinDescription[PIN_SPI_MOSI].pPort,
g_APinDescription[PIN_SPI_MOSI].ulPinType,
g_APinDescription[PIN_SPI_MOSI].ulPin,
g_APinDescription[PIN_SPI_MOSI].ulPinConfiguration);
PIO_Configure(
g_APinDescription[PIN_SPI_MISO].pPort,
g_APinDescription[PIN_SPI_MISO].ulPinType,
g_APinDescription[PIN_SPI_MISO].ulPin,
g_APinDescription[PIN_SPI_MISO].ulPinConfiguration);
PIO_Configure(
g_APinDescription[PIN_SPI_SCK].pPort,
g_APinDescription[PIN_SPI_SCK].ulPinType,
g_APinDescription[PIN_SPI_SCK].ulPin,
g_APinDescription[PIN_SPI_SCK].ulPinConfiguration);
}
SPIClass SPI(SPI_INTERFACE, SPI_INTERFACE_ID, SPI_0_Init);
#endif
|
Set mode to SPI_CONTINUE for first byte transfer in SPI.transfer16(...)
|
Set mode to SPI_CONTINUE for first byte transfer in SPI.transfer16(...)
Update to #4081
|
C++
|
lgpl-2.1
|
tbowmo/Arduino,niggor/Arduino_cc,PaoloP74/Arduino,tbowmo/Arduino,me-no-dev/Arduino-1,vbextreme/Arduino,nandojve/Arduino,stevemayhew/Arduino,nandojve/Arduino,Chris--A/Arduino,eggfly/arduino,eggfly/arduino,majenkotech/Arduino,eggfly/arduino,stevemayhew/Arduino,PaoloP74/Arduino,nandojve/Arduino,bsmr-arduino/Arduino,byran/Arduino,stickbreaker/Arduino,me-no-dev/Arduino-1,nandojve/Arduino,majenkotech/Arduino,niggor/Arduino_cc,NicoHood/Arduino,me-no-dev/Arduino-1,nandojve/Arduino,byran/Arduino,xxxajk/Arduino-1,stevemayhew/Arduino,NicoHood/Arduino,me-no-dev/Arduino-1,me-no-dev/Arduino-1,PaoloP74/Arduino,stickbreaker/Arduino,NicoHood/Arduino,PaoloP74/Arduino,niggor/Arduino_cc,Chris--A/Arduino,stickbreaker/Arduino,Chris--A/Arduino,bsmr-arduino/Arduino,tbowmo/Arduino,bsmr-arduino/Arduino,majenkotech/Arduino,xxxajk/Arduino-1,eggfly/arduino,Chris--A/Arduino,vbextreme/Arduino,NicoHood/Arduino,byran/Arduino,bsmr-arduino/Arduino,tbowmo/Arduino,me-no-dev/Arduino-1,bsmr-arduino/Arduino,majenkotech/Arduino,eggfly/arduino,eggfly/arduino,stickbreaker/Arduino,xxxajk/Arduino-1,byran/Arduino,nandojve/Arduino,niggor/Arduino_cc,stickbreaker/Arduino,stevemayhew/Arduino,vbextreme/Arduino,Chris--A/Arduino,vbextreme/Arduino,PaoloP74/Arduino,niggor/Arduino_cc,xxxajk/Arduino-1,bsmr-arduino/Arduino,PaoloP74/Arduino,eggfly/arduino,byran/Arduino,majenkotech/Arduino,Chris--A/Arduino,vbextreme/Arduino,tbowmo/Arduino,byran/Arduino,vbextreme/Arduino,me-no-dev/Arduino-1,xxxajk/Arduino-1,bsmr-arduino/Arduino,niggor/Arduino_cc,NicoHood/Arduino,niggor/Arduino_cc,majenkotech/Arduino,PaoloP74/Arduino,byran/Arduino,stevemayhew/Arduino,Chris--A/Arduino,majenkotech/Arduino,nandojve/Arduino,niggor/Arduino_cc,tbowmo/Arduino,Chris--A/Arduino,nandojve/Arduino,niggor/Arduino_cc,eggfly/arduino,stevemayhew/Arduino,stevemayhew/Arduino,xxxajk/Arduino-1,stickbreaker/Arduino,stevemayhew/Arduino,bsmr-arduino/Arduino,stickbreaker/Arduino,NicoHood/Arduino,NicoHood/Arduino,vbextreme/Arduino,vbextreme/Arduino,xxxajk/Arduino-1,tbowmo/Arduino,NicoHood/Arduino,me-no-dev/Arduino-1,PaoloP74/Arduino,xxxajk/Arduino-1,tbowmo/Arduino,byran/Arduino
|
8d8d17209417fadfd9d0a21be609ad79253441b6
|
compiler/AST/CollapseBlocks.cpp
|
compiler/AST/CollapseBlocks.cpp
|
/*
* Copyright 2004-2014 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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.
*/
/*
This transformation is designed to collapse nested Block Statements e.g.
{
var x = 10;
x = 20;
{
var y = 0;
{
var z = 20;
foo(x, y, z);
}
}
}
can be flattened to
{
var x = 10;
x = 20;
var y = 0;
var z = 20;
foo(x, y, z);
}
so long as name resolution has been completed.
This is achieved by walking the body of a given BlockStmt and
a) Recursively apply Collapse to each expr in the body
b) If the expr is a BlockStmt, then copy its body in to the
outer body and remove the depleted BlockStmt.
The actual implementation shuffles the input body into a temporary
Alist and then copies the elements back while applying the transformation.
NOAKES 2014/11/12
Currently WhileDo/DoWhile/ForLoop *are* BlockStmts and so those
cases look a little odd for now. I am currently working to
decouple these nodes from BlockStmt.
*/
#include "CollapseBlocks.h"
#include "WhileDoStmt.h"
#include "DoWhileStmt.h"
#include "CForLoop.h"
#include "ForLoop.h"
#include "alist.h"
#include "stmt.h"
CollapseBlocks::CollapseBlocks()
{
}
CollapseBlocks::~CollapseBlocks()
{
}
bool CollapseBlocks::enterBlockStmt(BlockStmt* node)
{
AList shuffle;
// Transfer all of the expressions in to a temporary Alist
for_alist(expr, node->body)
{
expr->remove();
shuffle.insertAtTail(expr);
}
// Copy them back in to the body with recursive collapsing
for_alist(expr, shuffle)
{
BlockStmt* stmt = toBlockStmt(expr);
// Apply collapse recursively to the expression
expr->accept(this);
expr->remove();
// If the expr is a BlockStmt, collapse during the copy
if (stmt != 0 && stmt->blockInfoGet() == 0)
{
for_alist(subItem, stmt->body)
{
subItem->remove();
node->body.insertAtTail(subItem);
}
}
else
{
node->body.insertAtTail(expr);
}
}
removeDeadIterResumeGotos();
// Do not recurse
return false;
}
// The c for loop primitive is of the form:
// __primitive("C for loop", {inits}, {test}, {incrs})
//
// For zippered iterators the inits and incrs can be composed of multiple
// (essentially scopeless) block statements next to each other. We want to
// collapse those into a single block (otherwise codegen would be a nightmare.)
//
bool CollapseBlocks::enterCForLoop(CForLoop* node)
{
CallExpr* call = node->blockInfoGet();
// Handle the init/test/incr fields specially
if (call != 0 && call->isPrimitive(PRIM_BLOCK_C_FOR_LOOP))
{
for_alist(cForExprs, call->argList)
{
if (BlockStmt* block = toBlockStmt(cForExprs))
enterBlockStmt(block);
}
}
// Now simply forward to handle the body
return enterBlockStmt(node);
}
bool CollapseBlocks::enterForLoop(ForLoop* node)
{
CallExpr* call = node->blockInfoGet();
// Handle the init/test/incr fields specially
if (call != 0 && call->isPrimitive(PRIM_BLOCK_C_FOR_LOOP))
{
for_alist(cForExprs, call->argList)
{
if (BlockStmt* block = toBlockStmt(cForExprs))
enterBlockStmt(block);
}
}
// Now simply forward to handle the body
return enterBlockStmt(node);
}
// 2014/11/12 Noakes: For now simply act like a BlockStmt
bool CollapseBlocks::enterWhileDoStmt(WhileDoStmt* node)
{
return enterBlockStmt(node);
}
// 2014/11/12 Noakes: For now simply act like a BlockStmt
bool CollapseBlocks::enterDoWhileStmt(DoWhileStmt* node)
{
return enterBlockStmt(node);
}
// Recurse into the consequent and alternative
// These are generally BlockStmts
bool CollapseBlocks::enterCondStmt(CondStmt* node)
{
return true;
}
/************************************ | *************************************
* *
* The remaining definitions are simple "default do nothing" defintions *
* *
************************************* | ************************************/
bool CollapseBlocks::enterAggrType(AggregateType* node)
{
return false;
}
void CollapseBlocks::exitAggrType(AggregateType* node)
{
}
bool CollapseBlocks::enterEnumType(EnumType* node)
{
return false;
}
void CollapseBlocks::exitEnumType(EnumType* node)
{
}
void CollapseBlocks::visitPrimType(PrimitiveType* node)
{
}
bool CollapseBlocks::enterArgSym(ArgSymbol* node)
{
return false;
}
void CollapseBlocks::exitArgSym(ArgSymbol* node)
{
}
void CollapseBlocks::visitEnumSym(EnumSymbol* node)
{
}
bool CollapseBlocks::enterFnSym(FnSymbol* node)
{
return false;
}
void CollapseBlocks::exitFnSym(FnSymbol* node)
{
}
void CollapseBlocks::visitLabelSym(LabelSymbol* node)
{
}
bool CollapseBlocks::enterModSym(ModuleSymbol* node)
{
return false;
}
void CollapseBlocks::exitModSym(ModuleSymbol* node)
{
}
bool CollapseBlocks::enterTypeSym(TypeSymbol* node)
{
return false;
}
void CollapseBlocks::exitTypeSym(TypeSymbol* node)
{
}
void CollapseBlocks::visitVarSym(VarSymbol* node)
{
}
bool CollapseBlocks::enterCallExpr(CallExpr* node)
{
return false;
}
void CollapseBlocks::exitCallExpr(CallExpr* node)
{
}
bool CollapseBlocks::enterDefExpr(DefExpr* node)
{
return false;
}
void CollapseBlocks::exitDefExpr(DefExpr* node)
{
}
bool CollapseBlocks::enterNamedExpr(NamedExpr* node)
{
return false;
}
void CollapseBlocks::exitNamedExpr(NamedExpr* node)
{
}
void CollapseBlocks::visitSymExpr(SymExpr* node)
{
}
void CollapseBlocks::visitUsymExpr(UnresolvedSymExpr* node)
{
}
void CollapseBlocks::exitBlockStmt(BlockStmt* node)
{
}
void CollapseBlocks::exitWhileDoStmt(WhileDoStmt* node)
{
}
void CollapseBlocks::exitDoWhileStmt(DoWhileStmt* node)
{
}
void CollapseBlocks::exitCForLoop(CForLoop* node)
{
}
void CollapseBlocks::exitForLoop(ForLoop* node)
{
}
void CollapseBlocks::exitCondStmt(CondStmt* node)
{
}
void CollapseBlocks::visitEblockStmt(ExternBlockStmt* node)
{
}
bool CollapseBlocks::enterGotoStmt(GotoStmt* node)
{
return false;
}
void CollapseBlocks::exitGotoStmt(GotoStmt* node)
{
}
|
/*
* Copyright 2004-2014 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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.
*/
/*
This transformation is designed to collapse nested Block Statements e.g.
{
var x = 10;
x = 20;
{
var y = 0;
{
var z = 20;
foo(x, y, z);
}
}
}
can be flattened to
{
var x = 10;
x = 20;
var y = 0;
var z = 20;
foo(x, y, z);
}
so long as name resolution has been completed.
This is achieved by walking the body of a given BlockStmt and
a) Recursively apply Collapse to each expr in the body
b) If the expr is a BlockStmt, then copy its body in to the
outer body and remove the depleted BlockStmt.
The actual implementation shuffles the input body into a temporary
Alist and then copies the elements back while applying the transformation.
NOAKES 2014/11/12
Currently WhileDo/DoWhile/ForLoop *are* BlockStmts and so those
cases look a little odd for now. I am currently working to
decouple these nodes from BlockStmt.
*/
#include "CollapseBlocks.h"
#include "WhileDoStmt.h"
#include "DoWhileStmt.h"
#include "CForLoop.h"
#include "ForLoop.h"
#include "alist.h"
#include "stmt.h"
CollapseBlocks::CollapseBlocks()
{
}
CollapseBlocks::~CollapseBlocks()
{
}
bool CollapseBlocks::enterBlockStmt(BlockStmt* node)
{
AList shuffle;
// Transfer all of the expressions in to a temporary Alist
for_alist(expr, node->body)
{
expr->remove();
shuffle.insertAtTail(expr);
}
// Copy them back in to the body with recursive collapsing
for_alist(expr, shuffle)
{
BlockStmt* stmt = toBlockStmt(expr);
// Apply collapse recursively to the expression
expr->accept(this);
expr->remove();
// If the expr is a BlockStmt, collapse during the copy
if (stmt != 0 && stmt->blockInfoGet() == 0)
{
for_alist(subItem, stmt->body)
{
subItem->remove();
node->body.insertAtTail(subItem);
}
}
else
{
node->body.insertAtTail(expr);
}
}
removeDeadIterResumeGotos();
// Do not recurse
return false;
}
// The c for loop primitive is of the form:
// __primitive("C for loop", {inits}, {test}, {incrs})
//
// For zippered iterators the inits and incrs can be composed of multiple
// (essentially scopeless) block statements next to each other. We want to
// collapse those into a single block (otherwise codegen would be a nightmare.)
//
bool CollapseBlocks::enterCForLoop(CForLoop* node)
{
CallExpr* call = node->blockInfoGet();
// Handle the init/test/incr fields specially
for_alist(cForExprs, call->argList)
{
if (BlockStmt* block = toBlockStmt(cForExprs))
enterBlockStmt(block);
}
// Now simply forward to handle the body
return enterBlockStmt(node);
}
bool CollapseBlocks::enterForLoop(ForLoop* node)
{
return enterBlockStmt(node);
}
// 2014/11/12 Noakes: For now simply act like a BlockStmt
bool CollapseBlocks::enterWhileDoStmt(WhileDoStmt* node)
{
return enterBlockStmt(node);
}
// 2014/11/12 Noakes: For now simply act like a BlockStmt
bool CollapseBlocks::enterDoWhileStmt(DoWhileStmt* node)
{
return enterBlockStmt(node);
}
// Recurse into the consequent and alternative
// These are generally BlockStmts
bool CollapseBlocks::enterCondStmt(CondStmt* node)
{
return true;
}
/************************************ | *************************************
* *
* The remaining definitions are simple "default do nothing" defintions *
* *
************************************* | ************************************/
bool CollapseBlocks::enterAggrType(AggregateType* node)
{
return false;
}
void CollapseBlocks::exitAggrType(AggregateType* node)
{
}
bool CollapseBlocks::enterEnumType(EnumType* node)
{
return false;
}
void CollapseBlocks::exitEnumType(EnumType* node)
{
}
void CollapseBlocks::visitPrimType(PrimitiveType* node)
{
}
bool CollapseBlocks::enterArgSym(ArgSymbol* node)
{
return false;
}
void CollapseBlocks::exitArgSym(ArgSymbol* node)
{
}
void CollapseBlocks::visitEnumSym(EnumSymbol* node)
{
}
bool CollapseBlocks::enterFnSym(FnSymbol* node)
{
return false;
}
void CollapseBlocks::exitFnSym(FnSymbol* node)
{
}
void CollapseBlocks::visitLabelSym(LabelSymbol* node)
{
}
bool CollapseBlocks::enterModSym(ModuleSymbol* node)
{
return false;
}
void CollapseBlocks::exitModSym(ModuleSymbol* node)
{
}
bool CollapseBlocks::enterTypeSym(TypeSymbol* node)
{
return false;
}
void CollapseBlocks::exitTypeSym(TypeSymbol* node)
{
}
void CollapseBlocks::visitVarSym(VarSymbol* node)
{
}
bool CollapseBlocks::enterCallExpr(CallExpr* node)
{
return false;
}
void CollapseBlocks::exitCallExpr(CallExpr* node)
{
}
bool CollapseBlocks::enterDefExpr(DefExpr* node)
{
return false;
}
void CollapseBlocks::exitDefExpr(DefExpr* node)
{
}
bool CollapseBlocks::enterNamedExpr(NamedExpr* node)
{
return false;
}
void CollapseBlocks::exitNamedExpr(NamedExpr* node)
{
}
void CollapseBlocks::visitSymExpr(SymExpr* node)
{
}
void CollapseBlocks::visitUsymExpr(UnresolvedSymExpr* node)
{
}
void CollapseBlocks::exitBlockStmt(BlockStmt* node)
{
}
void CollapseBlocks::exitWhileDoStmt(WhileDoStmt* node)
{
}
void CollapseBlocks::exitDoWhileStmt(DoWhileStmt* node)
{
}
void CollapseBlocks::exitCForLoop(CForLoop* node)
{
}
void CollapseBlocks::exitForLoop(ForLoop* node)
{
}
void CollapseBlocks::exitCondStmt(CondStmt* node)
{
}
void CollapseBlocks::visitEblockStmt(ExternBlockStmt* node)
{
}
bool CollapseBlocks::enterGotoStmt(GotoStmt* node)
{
return false;
}
void CollapseBlocks::exitGotoStmt(GotoStmt* node)
{
}
|
Update CollapseBlocks on ForLoop and CForLoop to remove the extra check on the blockInfo
|
Update CollapseBlocks on ForLoop and CForLoop to remove the extra check on the blockInfo
|
C++
|
apache-2.0
|
chizarlicious/chapel,chizarlicious/chapel,hildeth/chapel,CoryMcCartan/chapel,hildeth/chapel,chizarlicious/chapel,chizarlicious/chapel,CoryMcCartan/chapel,hildeth/chapel,hildeth/chapel,CoryMcCartan/chapel,CoryMcCartan/chapel,hildeth/chapel,CoryMcCartan/chapel,CoryMcCartan/chapel,hildeth/chapel,hildeth/chapel,CoryMcCartan/chapel,chizarlicious/chapel,chizarlicious/chapel,chizarlicious/chapel
|
cb0ad8874a75947c44a226f449749616741151e4
|
src/usr/errl/errlentry_consts.H
|
src/usr/errl/errlentry_consts.H
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/errl/errlentry_consts.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2018 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef ERRLENTRY_CONSTS_H
#define ERRLENTRY_CONSTS_H
#include <errl/errludcallout.H>
#include <hwas/common/hwasCallout.H>
#include <hwas/common/deconfigGard.H>
using namespace HWAS;
namespace ERRORLOG
{
struct epubProcToSub_t
{
epubProcedureID xProc;
epubSubSystem_t xSubSys;
};
// Procedure to subsystem table.
const epubProcToSub_t PROCEDURE_TO_SUBSYS_TABLE[] =
{
{ EPUB_PRC_FIND_DECONFIGURED_PART , EPUB_CEC_HDW_SUBSYS },
{ EPUB_PRC_SP_CODE , EPUB_FIRMWARE_SP },
{ EPUB_PRC_PHYP_CODE , EPUB_FIRMWARE_PHYP },
{ EPUB_PRC_ALL_PROCS , EPUB_PROCESSOR_SUBSYS },
{ EPUB_PRC_ALL_MEMCRDS , EPUB_MEMORY_SUBSYS },
{ EPUB_PRC_INVALID_PART , EPUB_CEC_HDW_SUBSYS },
{ EPUB_PRC_LVL_SUPP , EPUB_MISC_SUBSYS },
{ EPUB_PRC_PROCPATH , EPUB_CEC_HDW_SUBSYS },
{ EPUB_PRC_NO_VPD_FOR_FRU , EPUB_CEC_HDW_VPD_INTF },
{ EPUB_PRC_MEMORY_PLUGGING_ERROR , EPUB_MEMORY_SUBSYS },
{ EPUB_PRC_FSI_PATH , EPUB_CEC_HDW_SUBSYS },
{ EPUB_PRC_PROC_AB_BUS , EPUB_PROCESSOR_BUS_CTL },
{ EPUB_PRC_PROC_XYZ_BUS , EPUB_PROCESSOR_BUS_CTL },
{ EPUB_PRC_MEMBUS_ERROR , EPUB_MEMORY_SUBSYS },
{ EPUB_PRC_EIBUS_ERROR , EPUB_CEC_HDW_SUBSYS },
{ EPUB_PRC_MEMORY_UE , EPUB_MEMORY_SUBSYS },
{ EPUB_PRC_POWER_ERROR , EPUB_POWER_SUBSYS },
{ EPUB_PRC_PERFORMANCE_DEGRADED , EPUB_MISC_SUBSYS },
{ EPUB_PRC_HB_CODE , EPUB_FIRMWARE_HOSTBOOT },
{ EPUB_PRC_TOD_CLOCK_ERR , EPUB_CEC_HDW_SUBSYS },
{ EPUB_PRC_COOLING_SYSTEM_ERR , EPUB_MISC_SUBSYS },
{ EPUB_PRC_FW_VERIFICATION_ERR , EPUB_FIRMWARE_SUBSYS },
{ EPUB_PRC_GPU_ISOLATION_PROCEDURE, EPUB_CEC_HDW_SUBSYS },
};
struct epubTargetTypeToSub_t
{
TARGETING::TYPE xType;
epubSubSystem_t xSubSys;
};
// Target type to subsystem table.
const epubTargetTypeToSub_t TARGET_TO_SUBSYS_TABLE[] =
{
// This list must be kept sorted by TYPE
{ TARGETING::TYPE_NODE , EPUB_CEC_HDW_SUBSYS },
{ TARGETING::TYPE_DIMM , EPUB_MEMORY_DIMM },
{ TARGETING::TYPE_MEMBUF , EPUB_MEMORY_SUBSYS },
{ TARGETING::TYPE_PROC , EPUB_PROCESSOR_SUBSYS },
{ TARGETING::TYPE_EX , EPUB_PROCESSOR_UNIT },
{ TARGETING::TYPE_CORE , EPUB_PROCESSOR_UNIT },
{ TARGETING::TYPE_L4 , EPUB_MEMORY_SUBSYS },
{ TARGETING::TYPE_MCS , EPUB_MEMORY_CONTROLLER },
{ TARGETING::TYPE_MBA , EPUB_MEMORY_CONTROLLER },
{ TARGETING::TYPE_XBUS , EPUB_PROCESSOR_BUS_CTL },
{ TARGETING::TYPE_ABUS , EPUB_PROCESSOR_SUBSYS },
{ TARGETING::TYPE_NX , EPUB_PROCESSOR_SUBSYS },
{ TARGETING::TYPE_CAPP , EPUB_PROCESSOR_SUBSYS },
{ TARGETING::TYPE_EQ , EPUB_PROCESSOR_SUBSYS },
{ TARGETING::TYPE_MCA , EPUB_MEMORY_CONTROLLER },
{ TARGETING::TYPE_MCBIST , EPUB_MEMORY_CONTROLLER },
{ TARGETING::TYPE_MI , EPUB_MEMORY_CONTROLLER },
{ TARGETING::TYPE_DMI , EPUB_MEMORY_SUBSYS },
{ TARGETING::TYPE_OBUS , EPUB_PROCESSOR_BUS_CTL },
{ TARGETING::TYPE_PEC , EPUB_IO_PHB },
{ TARGETING::TYPE_PHB , EPUB_IO_PHB },
{ TARGETING::TYPE_TPM , EPUB_CEC_HDW_SUBSYS },
};
struct epubBusTypeToSub_t
{
HWAS::busTypeEnum xType;
epubSubSystem_t xSubSys;
};
// Bus type to subsystem table
const epubBusTypeToSub_t BUS_TO_SUBSYS_TABLE[] =
{
{ HWAS::FSI_BUS_TYPE , EPUB_CEC_HDW_CHIP_INTF },
{ HWAS::DMI_BUS_TYPE , EPUB_MEMORY_BUS },
{ HWAS::A_BUS_TYPE , EPUB_PROCESSOR_BUS_CTL },
{ HWAS::X_BUS_TYPE , EPUB_PROCESSOR_BUS_CTL },
{ HWAS::I2C_BUS_TYPE , EPUB_CEC_HDW_I2C_DEVS },
{ HWAS::PSI_BUS_TYPE , EPUB_CEC_HDW_SP_PHYP_INTF },
{ HWAS::O_BUS_TYPE , EPUB_PROCESSOR_BUS_CTL },
};
struct epubClockTypeToSub_t
{
HWAS::clockTypeEnum xType;
epubSubSystem_t xSubSys;
};
// Clock type to subsystem table
const epubClockTypeToSub_t CLOCK_TO_SUBSYS_TABLE[] =
{
{ HWAS::TODCLK_TYPE , EPUB_CEC_HDW_TOD_HDW },
{ HWAS::MEMCLK_TYPE , EPUB_CEC_HDW_CLK_CTL },
{ HWAS::OSCREFCLK_TYPE , EPUB_CEC_HDW_CLK_CTL },
{ HWAS::OSCPCICLK_TYPE , EPUB_CEC_HDW_CLK_CTL },
};
struct epubPartTypeToSub_t
{
HWAS::partTypeEnum xType;
epubSubSystem_t xSubSys;
};
// PART type to subsystem table
const epubPartTypeToSub_t PART_TO_SUBSYS_TABLE[] =
{
{ HWAS::FLASH_CONTROLLER_PART_TYPE , EPUB_CEC_HDW_SUBSYS },
{ HWAS::PNOR_PART_TYPE , EPUB_CEC_HDW_SUBSYS },
{ HWAS::SBE_SEEPROM_PART_TYPE , EPUB_PROCESSOR_SUBSYS },
{ HWAS::VPD_PART_TYPE , EPUB_CEC_HDW_SUBSYS },
{ HWAS::LPC_SLAVE_PART_TYPE , EPUB_CEC_HDW_SUBSYS },
{ HWAS::GPIO_EXPANDER_PART_TYPE , EPUB_MEMORY_SUBSYS },
{ HWAS::SPIVID_SLAVE_PART_TYPE , EPUB_POWER_SUBSYS },
};
struct epubSensorTypeToSub_t
{
HWAS::sensorTypeEnum xType;
epubSubSystem_t xSubSys;
};
struct epubSensorTypeToSub_t SENSOR_TO_SUBSYS_TABLE[] =
{
{ HWAS::GPU_FUNC_SENSOR , EPUB_IO_SUBSYS },
{ HWAS::GPU_TEMPERATURE_SENSOR , EPUB_IO_SUBSYS },
{ HWAS::GPU_MEMORY_TEMP_SENSOR , EPUB_IO_SUBSYS },
};
} //end namespace
#endif //#ifndef ERRLENTRY_CONSTS_H
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/errl/errlentry_consts.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2018 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef ERRLENTRY_CONSTS_H
#define ERRLENTRY_CONSTS_H
#include <errl/errludcallout.H>
#include <hwas/common/hwasCallout.H>
#include <hwas/common/deconfigGard.H>
using namespace HWAS;
namespace ERRORLOG
{
struct epubProcToSub_t
{
epubProcedureID xProc;
epubSubSystem_t xSubSys;
};
// Procedure to subsystem table.
const epubProcToSub_t PROCEDURE_TO_SUBSYS_TABLE[] =
{
{ EPUB_PRC_FIND_DECONFIGURED_PART , EPUB_CEC_HDW_SUBSYS },
{ EPUB_PRC_SP_CODE , EPUB_FIRMWARE_SP },
{ EPUB_PRC_PHYP_CODE , EPUB_FIRMWARE_PHYP },
{ EPUB_PRC_ALL_PROCS , EPUB_PROCESSOR_SUBSYS },
{ EPUB_PRC_ALL_MEMCRDS , EPUB_MEMORY_SUBSYS },
{ EPUB_PRC_INVALID_PART , EPUB_CEC_HDW_SUBSYS },
{ EPUB_PRC_LVL_SUPP , EPUB_MISC_SUBSYS },
{ EPUB_PRC_PROCPATH , EPUB_CEC_HDW_SUBSYS },
{ EPUB_PRC_NO_VPD_FOR_FRU , EPUB_CEC_HDW_VPD_INTF },
{ EPUB_PRC_MEMORY_PLUGGING_ERROR , EPUB_MEMORY_SUBSYS },
{ EPUB_PRC_FSI_PATH , EPUB_CEC_HDW_SUBSYS },
{ EPUB_PRC_PROC_AB_BUS , EPUB_PROCESSOR_BUS_CTL },
{ EPUB_PRC_PROC_XYZ_BUS , EPUB_PROCESSOR_BUS_CTL },
{ EPUB_PRC_MEMBUS_ERROR , EPUB_MEMORY_SUBSYS },
{ EPUB_PRC_EIBUS_ERROR , EPUB_CEC_HDW_SUBSYS },
{ EPUB_PRC_MEMORY_UE , EPUB_MEMORY_SUBSYS },
{ EPUB_PRC_POWER_ERROR , EPUB_POWER_SUBSYS },
{ EPUB_PRC_PERFORMANCE_DEGRADED , EPUB_MISC_SUBSYS },
{ EPUB_PRC_HB_CODE , EPUB_FIRMWARE_HOSTBOOT },
{ EPUB_PRC_TOD_CLOCK_ERR , EPUB_CEC_HDW_SUBSYS },
{ EPUB_PRC_COOLING_SYSTEM_ERR , EPUB_MISC_SUBSYS },
{ EPUB_PRC_FW_VERIFICATION_ERR , EPUB_FIRMWARE_SUBSYS },
{ EPUB_PRC_GPU_ISOLATION_PROCEDURE, EPUB_CEC_HDW_SUBSYS },
};
struct epubTargetTypeToSub_t
{
TARGETING::TYPE xType;
epubSubSystem_t xSubSys;
};
// Target type to subsystem table.
const epubTargetTypeToSub_t TARGET_TO_SUBSYS_TABLE[] =
{
// This list must be kept sorted by TYPE
{ TARGETING::TYPE_NODE , EPUB_CEC_HDW_SUBSYS },
{ TARGETING::TYPE_DIMM , EPUB_MEMORY_DIMM },
{ TARGETING::TYPE_MEMBUF , EPUB_MEMORY_SUBSYS },
{ TARGETING::TYPE_PROC , EPUB_PROCESSOR_SUBSYS },
{ TARGETING::TYPE_EX , EPUB_PROCESSOR_UNIT },
{ TARGETING::TYPE_CORE , EPUB_PROCESSOR_UNIT },
{ TARGETING::TYPE_L4 , EPUB_MEMORY_SUBSYS },
{ TARGETING::TYPE_MCS , EPUB_MEMORY_SUBSYS },
{ TARGETING::TYPE_MBA , EPUB_MEMORY_SUBSYS },
{ TARGETING::TYPE_XBUS , EPUB_PROCESSOR_BUS_CTL },
{ TARGETING::TYPE_ABUS , EPUB_PROCESSOR_SUBSYS },
{ TARGETING::TYPE_NX , EPUB_PROCESSOR_SUBSYS },
{ TARGETING::TYPE_CAPP , EPUB_PROCESSOR_SUBSYS },
{ TARGETING::TYPE_EQ , EPUB_PROCESSOR_SUBSYS },
{ TARGETING::TYPE_MCA , EPUB_MEMORY_SUBSYS },
{ TARGETING::TYPE_MCBIST , EPUB_MEMORY_SUBSYS },
{ TARGETING::TYPE_MI , EPUB_MEMORY_SUBSYS },
{ TARGETING::TYPE_DMI , EPUB_MEMORY_SUBSYS },
{ TARGETING::TYPE_OBUS , EPUB_PROCESSOR_BUS_CTL },
{ TARGETING::TYPE_PEC , EPUB_IO_PHB },
{ TARGETING::TYPE_PHB , EPUB_IO_PHB },
{ TARGETING::TYPE_TPM , EPUB_CEC_HDW_SUBSYS },
};
struct epubBusTypeToSub_t
{
HWAS::busTypeEnum xType;
epubSubSystem_t xSubSys;
};
// Bus type to subsystem table
const epubBusTypeToSub_t BUS_TO_SUBSYS_TABLE[] =
{
{ HWAS::FSI_BUS_TYPE , EPUB_CEC_HDW_CHIP_INTF },
{ HWAS::DMI_BUS_TYPE , EPUB_MEMORY_BUS },
{ HWAS::A_BUS_TYPE , EPUB_PROCESSOR_BUS_CTL },
{ HWAS::X_BUS_TYPE , EPUB_PROCESSOR_BUS_CTL },
{ HWAS::I2C_BUS_TYPE , EPUB_CEC_HDW_I2C_DEVS },
{ HWAS::PSI_BUS_TYPE , EPUB_CEC_HDW_SP_PHYP_INTF },
{ HWAS::O_BUS_TYPE , EPUB_PROCESSOR_BUS_CTL },
};
struct epubClockTypeToSub_t
{
HWAS::clockTypeEnum xType;
epubSubSystem_t xSubSys;
};
// Clock type to subsystem table
const epubClockTypeToSub_t CLOCK_TO_SUBSYS_TABLE[] =
{
{ HWAS::TODCLK_TYPE , EPUB_CEC_HDW_TOD_HDW },
{ HWAS::MEMCLK_TYPE , EPUB_CEC_HDW_CLK_CTL },
{ HWAS::OSCREFCLK_TYPE , EPUB_CEC_HDW_CLK_CTL },
{ HWAS::OSCPCICLK_TYPE , EPUB_CEC_HDW_CLK_CTL },
};
struct epubPartTypeToSub_t
{
HWAS::partTypeEnum xType;
epubSubSystem_t xSubSys;
};
// PART type to subsystem table
const epubPartTypeToSub_t PART_TO_SUBSYS_TABLE[] =
{
{ HWAS::FLASH_CONTROLLER_PART_TYPE , EPUB_CEC_HDW_SUBSYS },
{ HWAS::PNOR_PART_TYPE , EPUB_CEC_HDW_SUBSYS },
{ HWAS::SBE_SEEPROM_PART_TYPE , EPUB_PROCESSOR_SUBSYS },
{ HWAS::VPD_PART_TYPE , EPUB_CEC_HDW_SUBSYS },
{ HWAS::LPC_SLAVE_PART_TYPE , EPUB_CEC_HDW_SUBSYS },
{ HWAS::GPIO_EXPANDER_PART_TYPE , EPUB_MEMORY_SUBSYS },
{ HWAS::SPIVID_SLAVE_PART_TYPE , EPUB_POWER_SUBSYS },
};
struct epubSensorTypeToSub_t
{
HWAS::sensorTypeEnum xType;
epubSubSystem_t xSubSys;
};
struct epubSensorTypeToSub_t SENSOR_TO_SUBSYS_TABLE[] =
{
{ HWAS::GPU_FUNC_SENSOR , EPUB_IO_SUBSYS },
{ HWAS::GPU_TEMPERATURE_SENSOR , EPUB_IO_SUBSYS },
{ HWAS::GPU_MEMORY_TEMP_SENSOR , EPUB_IO_SUBSYS },
};
} //end namespace
#endif //#ifndef ERRLENTRY_CONSTS_H
|
Modify subsys translation for memory targets
|
Modify subsys translation for memory targets
Changed the PEL subsys translation for all memory related targets
to be MEMORY_SUBSYSTEM.
Change-Id: Ic07a82f7d3479c16c1953ebc1d85fa90e25f2f30
CQ: SW429168
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/60278
Tested-by: Jenkins Server <[email protected]>
Tested-by: Jenkins OP Build CI <[email protected]>
Tested-by: Jenkins OP HW <[email protected]>
Tested-by: FSP CI Jenkins <[email protected]>
Reviewed-by: Daniel M. Crowell <[email protected]>
|
C++
|
apache-2.0
|
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
|
df3158ac6142eb44f1febc9e056663a1d674ac28
|
src/vistk/pipeline/pipeline.cxx
|
src/vistk/pipeline/pipeline.cxx
|
/*ckwg +5
* Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "pipeline.h"
#include "pipeline_exception.h"
#include "edge.h"
#include <boost/foreach.hpp>
#include <set>
/**
* \file pipeline.cxx
*
* \brief Implementation of the base class for \link pipeline pipelines\endlink.
*/
namespace vistk
{
class pipeline::priv
{
public:
priv();
~priv();
typedef std::map<process::name_t, process_t> process_map_t;
typedef std::pair<process::port_addr_t, process::port_addr_t> connection_t;
typedef std::vector<connection_t> connections_t;
typedef std::map<size_t, edge_t> edge_map_t;
typedef std::map<process::port_t, process::port_addrs_t> input_port_mapping_t;
typedef std::map<process::port_t, process::port_addr_t> output_port_mapping_t;
typedef std::pair<input_port_mapping_t, output_port_mapping_t> port_mapping_t;
typedef std::map<process::name_t, port_mapping_t> group_t;
connections_t connections;
process_map_t process_map;
edge_map_t edge_map;
group_t groups;
};
pipeline
::pipeline(config_t const& /*config*/)
{
d = boost::shared_ptr<priv>(new priv);
}
pipeline
::~pipeline()
{
}
void
pipeline
::add_process(process_t process)
{
if (!process)
{
throw null_process_addition();
}
process::name_t const name = process->name();
priv::process_map_t::const_iterator proc_it = d->process_map.find(name);
if (proc_it != d->process_map.end())
{
throw duplicate_process_name(name);
}
priv::group_t::const_iterator group_it = d->groups.find(name);
if (group_it != d->groups.end())
{
throw duplicate_process_name(name);
}
d->process_map[name] = process;
}
void
pipeline
::add_group(process::name_t const& name)
{
priv::process_map_t::const_iterator proc_it = d->process_map.find(name);
if (proc_it != d->process_map.end())
{
throw duplicate_process_name(name);
}
priv::group_t::const_iterator group_it = d->groups.find(name);
if (group_it != d->groups.end())
{
throw duplicate_process_name(name);
}
d->groups[name] = priv::port_mapping_t();
}
void
pipeline
::connect(process::name_t const& upstream_process,
process::port_t const& upstream_port,
process::name_t const& downstream_process,
process::port_t const& downstream_port)
{
/// \todo Check if up or downstream is a group.
config_t edge_config = config::empty_config();
edge_t e = edge_t(new edge(edge_config));
process::port_addr_t const up_port = process::port_addr_t(upstream_process, upstream_port);
process::port_addr_t const down_port = process::port_addr_t(downstream_process, downstream_port);
priv::connection_t const conn = priv::connection_t(up_port, down_port);
priv::process_map_t::iterator const up_it = d->process_map.find(upstream_process);
priv::process_map_t::iterator const down_it = d->process_map.find(downstream_process);
if (up_it == d->process_map.end())
{
throw no_such_process(upstream_process);
}
if (down_it == d->process_map.end())
{
throw no_such_process(downstream_process);
}
up_it->second->connect_output_port(upstream_port, e);
down_it->second->connect_input_port(downstream_port, e);
d->edge_map[d->connections.size()] = e;
d->connections.push_back(conn);
}
void
pipeline
::map_input_port(process::name_t const& group,
process::port_t const& port,
process::name_t const& mapped_process,
process::port_t const& mapped_port)
{
priv::group_t::iterator const group_it = d->groups.find(group);
if (group_it == d->groups.end())
{
throw no_such_group(group);
}
priv::process_map_t::iterator const proc_it = d->process_map.find(mapped_process);
if (proc_it == d->process_map.end())
{
throw no_such_process(mapped_process);
}
priv::input_port_mapping_t& mapping = group_it->second.first;
mapping[port].push_back(process::port_addr_t(mapped_process, mapped_port));
}
void
pipeline
::map_output_port(process::name_t const& group,
process::port_t const& port,
process::name_t const& mapped_process,
process::port_t const& mapped_port)
{
priv::group_t::iterator const group_it = d->groups.find(group);
if (group_it == d->groups.end())
{
throw no_such_group(group);
}
priv::process_map_t::iterator const proc_it = d->process_map.find(mapped_process);
if (proc_it == d->process_map.end())
{
throw no_such_process(mapped_process);
}
priv::output_port_mapping_t& mapping = group_it->second.second;
priv::output_port_mapping_t::const_iterator const port_it = mapping.find(port);
if (port_it != mapping.end())
{
throw group_output_already_mapped(group, port, port_it->second.first, port_it->second.second, mapped_process, mapped_port);
}
mapping[port] = process::port_addr_t(mapped_process, mapped_port);
}
void
pipeline
::setup_pipeline()
{
/// \todo Check for disconnected pipelines.
/// \todo Check for types of connections.
}
process::names_t
pipeline
::process_names() const
{
process::names_t names;
BOOST_FOREACH (priv::process_map_t::value_type const& process_index, d->process_map)
{
names.push_back(process_index.first);
}
return names;
}
process_t
pipeline
::process_by_name(process::name_t const& name) const
{
priv::process_map_t::const_iterator i = d->process_map.find(name);
if (i == d->process_map.end())
{
throw no_such_process(name);
}
return i->second;
}
processes_t
pipeline
::upstream_for_process(process::name_t const& name) const
{
std::set<process::name_t> process_names;
BOOST_FOREACH (priv::connection_t const& connection, d->connections)
{
if (connection.second.first == name)
{
process::name_t const& upstream_name = connection.first.first;
process_names.insert(upstream_name);
}
}
processes_t processes;
BOOST_FOREACH (process::name_t const& process_name, process_names)
{
priv::process_map_t::const_iterator i = d->process_map.find(process_name);
processes.push_back(i->second);
}
return processes;
}
processes_t
pipeline
::downstream_for_process(process::name_t const& name) const
{
std::set<process::name_t> process_names;
BOOST_FOREACH (priv::connection_t const& connection, d->connections)
{
if (connection.first.first == name)
{
process::name_t const& downstream_name = connection.second.first;
process_names.insert(downstream_name);
}
}
processes_t processes;
BOOST_FOREACH (process::name_t const& process_name, process_names)
{
priv::process_map_t::const_iterator i = d->process_map.find(process_name);
processes.push_back(i->second);
}
return processes;
}
processes_t
pipeline
::downstream_for_port(process::name_t const& name, process::port_t const& port) const
{
std::set<process::name_t> process_names;
BOOST_FOREACH (priv::connection_t const& connection, d->connections)
{
if ((connection.first.first == name) &&
(connection.first.second == port))
{
process::name_t const& downstream_name = connection.second.first;
process_names.insert(downstream_name);
}
}
processes_t processes;
BOOST_FOREACH (process::name_t const& process_name, process_names)
{
priv::process_map_t::const_iterator i = d->process_map.find(process_name);
processes.push_back(i->second);
}
return processes;
}
process::port_addrs_t
pipeline
::receivers_for_port(process::name_t const& name, process::port_t const& port) const
{
process::port_addrs_t port_addrs;
BOOST_FOREACH (priv::connection_t const& connection, d->connections)
{
if ((connection.first.first == name) &&
(connection.first.second == port))
{
process::port_addr_t const& downstream_addr = connection.second;
port_addrs.push_back(downstream_addr);
}
}
return port_addrs;
}
edges_t
pipeline
::input_edges_for_process(process::name_t const& name) const
{
edges_t edges;
BOOST_FOREACH (priv::edge_map_t::value_type const& edge_index, d->edge_map)
{
if (d->connections[edge_index.first].second.first == name)
{
edges.push_back(edge_index.second);
}
}
return edges;
}
edges_t
pipeline
::output_edges_for_process(process::name_t const& name) const
{
edges_t edges;
BOOST_FOREACH (priv::edge_map_t::value_type const& edge_index, d->edge_map)
{
if (d->connections[edge_index.first].first.first == name)
{
edges.push_back(edge_index.second);
}
}
return edges;
}
edges_t
pipeline
::output_edges_for_port(process::name_t const& name, process::port_t const& port) const
{
edges_t edges;
BOOST_FOREACH (priv::edge_map_t::value_type const& edge_index, d->edge_map)
{
if ((d->connections[edge_index.first].first.first == name) &&
(d->connections[edge_index.first].first.second == port))
{
edges.push_back(edge_index.second);
}
}
return edges;
}
process::names_t
pipeline
::groups() const
{
process::names_t names;
BOOST_FOREACH (priv::group_t::value_type const& group, d->groups)
{
process::name_t const& name = group.first;
names.push_back(name);
}
return names;
}
process::ports_t
pipeline
::input_ports_for_group(process::name_t const& name) const
{
process::ports_t ports;
priv::group_t::const_iterator const group_it = d->groups.find(name);
if (group_it == d->groups.end())
{
throw no_such_group(name);
}
priv::input_port_mapping_t const& mapping = group_it->second.first;
BOOST_FOREACH (priv::input_port_mapping_t::value_type const& port_it, mapping)
{
process::port_t const& port = port_it.first;
ports.push_back(port);
}
return ports;
}
process::ports_t
pipeline
::output_ports_for_group(process::name_t const& name) const
{
process::ports_t ports;
priv::group_t::const_iterator const group_it = d->groups.find(name);
if (group_it == d->groups.end())
{
throw no_such_group(name);
}
priv::output_port_mapping_t const& mapping = group_it->second.second;
BOOST_FOREACH (priv::output_port_mapping_t::value_type const& port_it, mapping)
{
process::port_t const& port = port_it.first;
ports.push_back(port);
}
return ports;
}
process::port_addrs_t
pipeline
::mapped_group_input_ports(process::name_t const& name, process::port_t const& port) const
{
priv::group_t::const_iterator const group_it = d->groups.find(name);
if (group_it == d->groups.end())
{
throw no_such_group(name);
}
priv::input_port_mapping_t const& mapping = group_it->second.first;
priv::input_port_mapping_t::const_iterator const mapping_it = mapping.find(port);
if (mapping_it == mapping.end())
{
throw no_such_group_port(name, port);
}
return mapping_it->second;
}
process::port_addr_t
pipeline
::mapped_group_output_ports(process::name_t const& name, process::port_t const& port) const
{
priv::group_t::const_iterator const group_it = d->groups.find(name);
if (group_it == d->groups.end())
{
throw no_such_group(name);
}
priv::output_port_mapping_t const& mapping = group_it->second.second;
priv::output_port_mapping_t::const_iterator const mapping_it = mapping.find(port);
if (mapping_it == mapping.end())
{
throw no_such_group_port(name, port);
}
return mapping_it->second;
}
pipeline::priv
::priv()
{
}
pipeline::priv
::~priv()
{
}
} // end namespace vistk
|
/*ckwg +5
* Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "pipeline.h"
#include "pipeline_exception.h"
#include "edge.h"
#include <boost/foreach.hpp>
#include <set>
/**
* \file pipeline.cxx
*
* \brief Implementation of the base class for \link pipeline pipelines\endlink.
*/
namespace vistk
{
class pipeline::priv
{
public:
priv();
~priv();
typedef std::map<process::name_t, process_t> process_map_t;
typedef std::pair<process::port_addr_t, process::port_addr_t> connection_t;
typedef std::vector<connection_t> connections_t;
typedef std::map<size_t, edge_t> edge_map_t;
typedef std::map<process::port_t, process::port_addrs_t> input_port_mapping_t;
typedef std::map<process::port_t, process::port_addr_t> output_port_mapping_t;
typedef std::pair<input_port_mapping_t, output_port_mapping_t> port_mapping_t;
typedef std::map<process::name_t, port_mapping_t> group_t;
connections_t connections;
process_map_t process_map;
edge_map_t edge_map;
group_t groups;
};
pipeline
::pipeline(config_t const& /*config*/)
{
d = boost::shared_ptr<priv>(new priv);
}
pipeline
::~pipeline()
{
}
void
pipeline
::add_process(process_t process)
{
if (!process)
{
throw null_process_addition();
}
process::name_t const name = process->name();
priv::process_map_t::const_iterator proc_it = d->process_map.find(name);
if (proc_it != d->process_map.end())
{
throw duplicate_process_name(name);
}
priv::group_t::const_iterator group_it = d->groups.find(name);
if (group_it != d->groups.end())
{
throw duplicate_process_name(name);
}
d->process_map[name] = process;
}
void
pipeline
::add_group(process::name_t const& name)
{
priv::process_map_t::const_iterator proc_it = d->process_map.find(name);
if (proc_it != d->process_map.end())
{
throw duplicate_process_name(name);
}
priv::group_t::const_iterator group_it = d->groups.find(name);
if (group_it != d->groups.end())
{
throw duplicate_process_name(name);
}
d->groups[name] = priv::port_mapping_t();
}
void
pipeline
::connect(process::name_t const& upstream_process,
process::port_t const& upstream_port,
process::name_t const& downstream_process,
process::port_t const& downstream_port)
{
priv::group_t::const_iterator const up_group_it = d->groups.find(upstream_process);
if (up_group_it != d->groups.end())
{
priv::output_port_mapping_t const& mapping = up_group_it->second.second;
priv::output_port_mapping_t::const_iterator const mapping_it = mapping.find(upstream_port);
if (mapping_it != mapping.end())
{
connect(mapping_it->second.first, mapping_it->second.second,
downstream_process, downstream_port);
return;
}
}
priv::group_t::const_iterator const down_group_it = d->groups.find(upstream_process);
if (down_group_it != d->groups.end())
{
priv::input_port_mapping_t const& mapping = down_group_it->second.first;
priv::input_port_mapping_t::const_iterator const mapping_it = mapping.find(downstream_port);
if (mapping_it != mapping.end())
{
BOOST_FOREACH (process::port_addr_t const& port_addr, mapping_it->second)
{
connect(upstream_process, upstream_port,
port_addr.first, port_addr.second);
}
return;
}
}
config_t edge_config = config::empty_config();
edge_t e = edge_t(new edge(edge_config));
process::port_addr_t const up_port = process::port_addr_t(upstream_process, upstream_port);
process::port_addr_t const down_port = process::port_addr_t(downstream_process, downstream_port);
priv::connection_t const conn = priv::connection_t(up_port, down_port);
priv::process_map_t::iterator const up_it = d->process_map.find(upstream_process);
priv::process_map_t::iterator const down_it = d->process_map.find(downstream_process);
if (up_it == d->process_map.end())
{
throw no_such_process(upstream_process);
}
if (down_it == d->process_map.end())
{
throw no_such_process(downstream_process);
}
up_it->second->connect_output_port(upstream_port, e);
down_it->second->connect_input_port(downstream_port, e);
d->edge_map[d->connections.size()] = e;
d->connections.push_back(conn);
}
void
pipeline
::map_input_port(process::name_t const& group,
process::port_t const& port,
process::name_t const& mapped_process,
process::port_t const& mapped_port)
{
priv::group_t::iterator const group_it = d->groups.find(group);
if (group_it == d->groups.end())
{
throw no_such_group(group);
}
priv::process_map_t::iterator const proc_it = d->process_map.find(mapped_process);
if (proc_it == d->process_map.end())
{
throw no_such_process(mapped_process);
}
priv::input_port_mapping_t& mapping = group_it->second.first;
mapping[port].push_back(process::port_addr_t(mapped_process, mapped_port));
}
void
pipeline
::map_output_port(process::name_t const& group,
process::port_t const& port,
process::name_t const& mapped_process,
process::port_t const& mapped_port)
{
priv::group_t::iterator const group_it = d->groups.find(group);
if (group_it == d->groups.end())
{
throw no_such_group(group);
}
priv::process_map_t::iterator const proc_it = d->process_map.find(mapped_process);
if (proc_it == d->process_map.end())
{
throw no_such_process(mapped_process);
}
priv::output_port_mapping_t& mapping = group_it->second.second;
priv::output_port_mapping_t::const_iterator const port_it = mapping.find(port);
if (port_it != mapping.end())
{
throw group_output_already_mapped(group, port, port_it->second.first, port_it->second.second, mapped_process, mapped_port);
}
mapping[port] = process::port_addr_t(mapped_process, mapped_port);
}
void
pipeline
::setup_pipeline()
{
/// \todo Check for disconnected pipelines.
/// \todo Check for types of connections.
}
process::names_t
pipeline
::process_names() const
{
process::names_t names;
BOOST_FOREACH (priv::process_map_t::value_type const& process_index, d->process_map)
{
names.push_back(process_index.first);
}
return names;
}
process_t
pipeline
::process_by_name(process::name_t const& name) const
{
priv::process_map_t::const_iterator i = d->process_map.find(name);
if (i == d->process_map.end())
{
throw no_such_process(name);
}
return i->second;
}
processes_t
pipeline
::upstream_for_process(process::name_t const& name) const
{
std::set<process::name_t> process_names;
BOOST_FOREACH (priv::connection_t const& connection, d->connections)
{
if (connection.second.first == name)
{
process::name_t const& upstream_name = connection.first.first;
process_names.insert(upstream_name);
}
}
processes_t processes;
BOOST_FOREACH (process::name_t const& process_name, process_names)
{
priv::process_map_t::const_iterator i = d->process_map.find(process_name);
processes.push_back(i->second);
}
return processes;
}
processes_t
pipeline
::downstream_for_process(process::name_t const& name) const
{
std::set<process::name_t> process_names;
BOOST_FOREACH (priv::connection_t const& connection, d->connections)
{
if (connection.first.first == name)
{
process::name_t const& downstream_name = connection.second.first;
process_names.insert(downstream_name);
}
}
processes_t processes;
BOOST_FOREACH (process::name_t const& process_name, process_names)
{
priv::process_map_t::const_iterator i = d->process_map.find(process_name);
processes.push_back(i->second);
}
return processes;
}
processes_t
pipeline
::downstream_for_port(process::name_t const& name, process::port_t const& port) const
{
std::set<process::name_t> process_names;
BOOST_FOREACH (priv::connection_t const& connection, d->connections)
{
if ((connection.first.first == name) &&
(connection.first.second == port))
{
process::name_t const& downstream_name = connection.second.first;
process_names.insert(downstream_name);
}
}
processes_t processes;
BOOST_FOREACH (process::name_t const& process_name, process_names)
{
priv::process_map_t::const_iterator i = d->process_map.find(process_name);
processes.push_back(i->second);
}
return processes;
}
process::port_addrs_t
pipeline
::receivers_for_port(process::name_t const& name, process::port_t const& port) const
{
process::port_addrs_t port_addrs;
BOOST_FOREACH (priv::connection_t const& connection, d->connections)
{
if ((connection.first.first == name) &&
(connection.first.second == port))
{
process::port_addr_t const& downstream_addr = connection.second;
port_addrs.push_back(downstream_addr);
}
}
return port_addrs;
}
edges_t
pipeline
::input_edges_for_process(process::name_t const& name) const
{
edges_t edges;
BOOST_FOREACH (priv::edge_map_t::value_type const& edge_index, d->edge_map)
{
if (d->connections[edge_index.first].second.first == name)
{
edges.push_back(edge_index.second);
}
}
return edges;
}
edges_t
pipeline
::output_edges_for_process(process::name_t const& name) const
{
edges_t edges;
BOOST_FOREACH (priv::edge_map_t::value_type const& edge_index, d->edge_map)
{
if (d->connections[edge_index.first].first.first == name)
{
edges.push_back(edge_index.second);
}
}
return edges;
}
edges_t
pipeline
::output_edges_for_port(process::name_t const& name, process::port_t const& port) const
{
edges_t edges;
BOOST_FOREACH (priv::edge_map_t::value_type const& edge_index, d->edge_map)
{
if ((d->connections[edge_index.first].first.first == name) &&
(d->connections[edge_index.first].first.second == port))
{
edges.push_back(edge_index.second);
}
}
return edges;
}
process::names_t
pipeline
::groups() const
{
process::names_t names;
BOOST_FOREACH (priv::group_t::value_type const& group, d->groups)
{
process::name_t const& name = group.first;
names.push_back(name);
}
return names;
}
process::ports_t
pipeline
::input_ports_for_group(process::name_t const& name) const
{
process::ports_t ports;
priv::group_t::const_iterator const group_it = d->groups.find(name);
if (group_it == d->groups.end())
{
throw no_such_group(name);
}
priv::input_port_mapping_t const& mapping = group_it->second.first;
BOOST_FOREACH (priv::input_port_mapping_t::value_type const& port_it, mapping)
{
process::port_t const& port = port_it.first;
ports.push_back(port);
}
return ports;
}
process::ports_t
pipeline
::output_ports_for_group(process::name_t const& name) const
{
process::ports_t ports;
priv::group_t::const_iterator const group_it = d->groups.find(name);
if (group_it == d->groups.end())
{
throw no_such_group(name);
}
priv::output_port_mapping_t const& mapping = group_it->second.second;
BOOST_FOREACH (priv::output_port_mapping_t::value_type const& port_it, mapping)
{
process::port_t const& port = port_it.first;
ports.push_back(port);
}
return ports;
}
process::port_addrs_t
pipeline
::mapped_group_input_ports(process::name_t const& name, process::port_t const& port) const
{
priv::group_t::const_iterator const group_it = d->groups.find(name);
if (group_it == d->groups.end())
{
throw no_such_group(name);
}
priv::input_port_mapping_t const& mapping = group_it->second.first;
priv::input_port_mapping_t::const_iterator const mapping_it = mapping.find(port);
if (mapping_it == mapping.end())
{
throw no_such_group_port(name, port);
}
return mapping_it->second;
}
process::port_addr_t
pipeline
::mapped_group_output_ports(process::name_t const& name, process::port_t const& port) const
{
priv::group_t::const_iterator const group_it = d->groups.find(name);
if (group_it == d->groups.end())
{
throw no_such_group(name);
}
priv::output_port_mapping_t const& mapping = group_it->second.second;
priv::output_port_mapping_t::const_iterator const mapping_it = mapping.find(port);
if (mapping_it == mapping.end())
{
throw no_such_group_port(name, port);
}
return mapping_it->second;
}
pipeline::priv
::priv()
{
}
pipeline::priv
::~priv()
{
}
} // end namespace vistk
|
Handle connections to mapped ports
|
Handle connections to mapped ports
|
C++
|
bsd-3-clause
|
linus-sherrill/sprokit,Kitware/sprokit,mathstuf/sprokit,Kitware/sprokit,mathstuf/sprokit,linus-sherrill/sprokit,mathstuf/sprokit,Kitware/sprokit,mathstuf/sprokit,Kitware/sprokit,linus-sherrill/sprokit,linus-sherrill/sprokit
|
d3c3bba6d07c97cfc1499a6bda73337584943971
|
src/gallium/drivers/nouveau/codegen/nv50_ir_lowering_gm107.cpp
|
src/gallium/drivers/nouveau/codegen/nv50_ir_lowering_gm107.cpp
|
/*
* Copyright 2011 Christoph Bumiller
* 2014 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "codegen/nv50_ir.h"
#include "codegen/nv50_ir_build_util.h"
#include "codegen/nv50_ir_target_nvc0.h"
#include "codegen/nv50_ir_lowering_gm107.h"
#include <limits>
namespace nv50_ir {
#define QOP_ADD 0
#define QOP_SUBR 1
#define QOP_SUB 2
#define QOP_MOV2 3
// UL UR LL LR
#define QUADOP(q, r, s, t) \
((QOP_##q << 6) | (QOP_##r << 4) | \
(QOP_##s << 2) | (QOP_##t << 0))
bool
GM107LoweringPass::handleManualTXD(TexInstruction *i)
{
static const uint8_t qOps[4][2] =
{
{ QUADOP(MOV2, ADD, MOV2, ADD), QUADOP(MOV2, MOV2, ADD, ADD) }, // l0
{ QUADOP(SUBR, MOV2, SUBR, MOV2), QUADOP(MOV2, MOV2, ADD, ADD) }, // l1
{ QUADOP(MOV2, ADD, MOV2, ADD), QUADOP(SUBR, SUBR, MOV2, MOV2) }, // l2
{ QUADOP(SUBR, MOV2, SUBR, MOV2), QUADOP(SUBR, SUBR, MOV2, MOV2) }, // l3
};
Value *def[4][4];
Value *crd[3];
Value *tmp;
Instruction *tex, *add;
Value *zero = bld.loadImm(bld.getSSA(), 0);
int l, c;
const int dim = i->tex.target.getDim();
i->op = OP_TEX; // no need to clone dPdx/dPdy later
for (c = 0; c < dim; ++c)
crd[c] = bld.getScratch();
tmp = bld.getScratch();
for (l = 0; l < 4; ++l) {
// mov coordinates from lane l to all lanes
bld.mkOp(OP_QUADON, TYPE_NONE, NULL);
for (c = 0; c < dim; ++c) {
bld.mkOp2(OP_SHFL, TYPE_F32, crd[c], i->getSrc(c), bld.mkImm(l));
add = bld.mkOp2(OP_QUADOP, TYPE_F32, crd[c], crd[c], zero);
add->subOp = 0x00;
add->lanes = 1; /* abused for .ndv */
}
// add dPdx from lane l to lanes dx
for (c = 0; c < dim; ++c) {
bld.mkOp2(OP_SHFL, TYPE_F32, tmp, i->dPdx[c].get(), bld.mkImm(l));
add = bld.mkOp2(OP_QUADOP, TYPE_F32, crd[c], tmp, crd[c]);
add->subOp = qOps[l][0];
add->lanes = 1; /* abused for .ndv */
}
// add dPdy from lane l to lanes dy
for (c = 0; c < dim; ++c) {
bld.mkOp2(OP_SHFL, TYPE_F32, tmp, i->dPdy[c].get(), bld.mkImm(l));
add = bld.mkOp2(OP_QUADOP, TYPE_F32, crd[c], tmp, crd[c]);
add->subOp = qOps[l][1];
add->lanes = 1; /* abused for .ndv */
}
// texture
bld.insert(tex = cloneForward(func, i));
for (c = 0; c < dim; ++c)
tex->setSrc(c, crd[c]);
bld.mkOp(OP_QUADPOP, TYPE_NONE, NULL);
// save results
for (c = 0; i->defExists(c); ++c) {
Instruction *mov;
def[c][l] = bld.getSSA();
mov = bld.mkMov(def[c][l], tex->getDef(c));
mov->fixed = 1;
mov->lanes = 1 << l;
}
}
for (c = 0; i->defExists(c); ++c) {
Instruction *u = bld.mkOp(OP_UNION, TYPE_U32, i->getDef(c));
for (l = 0; l < 4; ++l)
u->setSrc(l, def[c][l]);
}
i->bb->remove(i);
return true;
}
bool
GM107LoweringPass::handleDFDX(Instruction *insn)
{
Instruction *shfl;
int qop = 0, xid = 0;
switch (insn->op) {
case OP_DFDX:
qop = QUADOP(SUB, SUBR, SUB, SUBR);
xid = 1;
break;
case OP_DFDY:
qop = QUADOP(SUB, SUB, SUBR, SUBR);
xid = 2;
break;
default:
assert(!"invalid dfdx opcode");
break;
}
shfl = bld.mkOp2(OP_SHFL, TYPE_F32, bld.getScratch(),
insn->getSrc(0), bld.mkImm(xid));
shfl->subOp = NV50_IR_SUBOP_SHFL_BFLY;
insn->op = OP_QUADOP;
insn->subOp = qop;
insn->lanes = 0; /* abused for !.ndv */
insn->setSrc(1, insn->getSrc(0));
insn->setSrc(0, shfl->getDef(0));
return true;
}
bool
GM107LoweringPass::handlePFETCH(Instruction *i)
{
Value *tmp0 = bld.getScratch();
Value *tmp1 = bld.getScratch();
Value *tmp2 = bld.getScratch();
bld.mkOp1(OP_RDSV, TYPE_U32, tmp0, bld.mkSysVal(SV_INVOCATION_INFO, 0));
bld.mkOp2(OP_SHR , TYPE_U32, tmp1, tmp0, bld.mkImm(16));
bld.mkOp2(OP_AND , TYPE_U32, tmp0, tmp0, bld.mkImm(0xff));
bld.mkOp2(OP_AND , TYPE_U32, tmp1, tmp1, bld.mkImm(0xff));
bld.mkOp1(OP_MOV , TYPE_U32, tmp2, bld.mkImm(i->getSrc(0)->reg.data.u32));
bld.mkOp3(OP_MAD , TYPE_U32, tmp0, tmp0, tmp1, tmp2);
i->setSrc(0, tmp0);
i->setSrc(1, NULL);
return true;
}
bool
GM107LoweringPass::handlePOPCNT(Instruction *i)
{
Value *tmp = bld.mkOp2v(OP_AND, i->sType, bld.getScratch(),
i->getSrc(0), i->getSrc(1));
i->setSrc(0, tmp);
i->setSrc(1, NULL);
return TRUE;
}
//
// - add quadop dance for texturing
// - put FP outputs in GPRs
// - convert instruction sequences
//
bool
GM107LoweringPass::visit(Instruction *i)
{
bld.setPosition(i, false);
if (i->cc != CC_ALWAYS)
checkPredicate(i);
switch (i->op) {
case OP_TEX:
case OP_TXB:
case OP_TXL:
case OP_TXF:
case OP_TXG:
return handleTEX(i->asTex());
case OP_TXD:
return handleTXD(i->asTex());
case OP_TXLQ:
return handleTXLQ(i->asTex());
case OP_TXQ:
return handleTXQ(i->asTex());
case OP_EX2:
bld.mkOp1(OP_PREEX2, TYPE_F32, i->getDef(0), i->getSrc(0));
i->setSrc(0, i->getDef(0));
break;
case OP_POW:
return handlePOW(i);
case OP_DIV:
return handleDIV(i);
case OP_MOD:
return handleMOD(i);
case OP_SQRT:
return handleSQRT(i);
case OP_EXPORT:
return handleEXPORT(i);
case OP_PFETCH:
return handlePFETCH(i);
case OP_EMIT:
case OP_RESTART:
return handleOUT(i);
case OP_RDSV:
return handleRDSV(i);
case OP_WRSV:
return handleWRSV(i);
case OP_LOAD:
if (i->src(0).getFile() == FILE_SHADER_INPUT) {
if (prog->getType() == Program::TYPE_COMPUTE) {
i->getSrc(0)->reg.file = FILE_MEMORY_CONST;
i->getSrc(0)->reg.fileIndex = 0;
} else
if (prog->getType() == Program::TYPE_GEOMETRY &&
i->src(0).isIndirect(0)) {
// XXX: this assumes vec4 units
Value *ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
i->getIndirect(0, 0), bld.mkImm(4));
i->setIndirect(0, 0, ptr);
} else {
i->op = OP_VFETCH;
assert(prog->getType() != Program::TYPE_FRAGMENT); // INTERP
}
}
break;
case OP_ATOM:
{
const bool cctl = i->src(0).getFile() == FILE_MEMORY_GLOBAL;
handleATOM(i);
handleCasExch(i, cctl);
}
break;
case OP_SULDB:
case OP_SULDP:
case OP_SUSTB:
case OP_SUSTP:
case OP_SUREDB:
case OP_SUREDP:
handleSurfaceOpNVE4(i->asTex());
break;
case OP_DFDX:
case OP_DFDY:
handleDFDX(i);
break;
case OP_POPCNT:
handlePOPCNT(i);
break;
default:
break;
}
return true;
}
} // namespace nv50_ir
|
/*
* Copyright 2011 Christoph Bumiller
* 2014 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "codegen/nv50_ir.h"
#include "codegen/nv50_ir_build_util.h"
#include "codegen/nv50_ir_target_nvc0.h"
#include "codegen/nv50_ir_lowering_gm107.h"
#include <limits>
namespace nv50_ir {
#define QOP_ADD 0
#define QOP_SUBR 1
#define QOP_SUB 2
#define QOP_MOV2 3
// UL UR LL LR
#define QUADOP(q, r, s, t) \
((QOP_##q << 6) | (QOP_##r << 4) | \
(QOP_##s << 2) | (QOP_##t << 0))
bool
GM107LoweringPass::handleManualTXD(TexInstruction *i)
{
static const uint8_t qOps[4][2] =
{
{ QUADOP(MOV2, ADD, MOV2, ADD), QUADOP(MOV2, MOV2, ADD, ADD) }, // l0
{ QUADOP(SUBR, MOV2, SUBR, MOV2), QUADOP(MOV2, MOV2, ADD, ADD) }, // l1
{ QUADOP(MOV2, ADD, MOV2, ADD), QUADOP(SUBR, SUBR, MOV2, MOV2) }, // l2
{ QUADOP(SUBR, MOV2, SUBR, MOV2), QUADOP(SUBR, SUBR, MOV2, MOV2) }, // l3
};
Value *def[4][4];
Value *crd[3];
Value *tmp;
Instruction *tex, *add;
Value *zero = bld.loadImm(bld.getSSA(), 0);
int l, c;
const int dim = i->tex.target.getDim();
const int array = i->tex.target.isArray();
i->op = OP_TEX; // no need to clone dPdx/dPdy later
for (c = 0; c < dim; ++c)
crd[c] = bld.getScratch();
tmp = bld.getScratch();
for (l = 0; l < 4; ++l) {
// mov coordinates from lane l to all lanes
bld.mkOp(OP_QUADON, TYPE_NONE, NULL);
for (c = 0; c < dim; ++c) {
bld.mkOp2(OP_SHFL, TYPE_F32, crd[c], i->getSrc(c + array), bld.mkImm(l));
add = bld.mkOp2(OP_QUADOP, TYPE_F32, crd[c], crd[c], zero);
add->subOp = 0x00;
add->lanes = 1; /* abused for .ndv */
}
// add dPdx from lane l to lanes dx
for (c = 0; c < dim; ++c) {
bld.mkOp2(OP_SHFL, TYPE_F32, tmp, i->dPdx[c].get(), bld.mkImm(l));
add = bld.mkOp2(OP_QUADOP, TYPE_F32, crd[c], tmp, crd[c]);
add->subOp = qOps[l][0];
add->lanes = 1; /* abused for .ndv */
}
// add dPdy from lane l to lanes dy
for (c = 0; c < dim; ++c) {
bld.mkOp2(OP_SHFL, TYPE_F32, tmp, i->dPdy[c].get(), bld.mkImm(l));
add = bld.mkOp2(OP_QUADOP, TYPE_F32, crd[c], tmp, crd[c]);
add->subOp = qOps[l][1];
add->lanes = 1; /* abused for .ndv */
}
// texture
bld.insert(tex = cloneForward(func, i));
for (c = 0; c < dim; ++c)
tex->setSrc(c + array, crd[c]);
bld.mkOp(OP_QUADPOP, TYPE_NONE, NULL);
// save results
for (c = 0; i->defExists(c); ++c) {
Instruction *mov;
def[c][l] = bld.getSSA();
mov = bld.mkMov(def[c][l], tex->getDef(c));
mov->fixed = 1;
mov->lanes = 1 << l;
}
}
for (c = 0; i->defExists(c); ++c) {
Instruction *u = bld.mkOp(OP_UNION, TYPE_U32, i->getDef(c));
for (l = 0; l < 4; ++l)
u->setSrc(l, def[c][l]);
}
i->bb->remove(i);
return true;
}
bool
GM107LoweringPass::handleDFDX(Instruction *insn)
{
Instruction *shfl;
int qop = 0, xid = 0;
switch (insn->op) {
case OP_DFDX:
qop = QUADOP(SUB, SUBR, SUB, SUBR);
xid = 1;
break;
case OP_DFDY:
qop = QUADOP(SUB, SUB, SUBR, SUBR);
xid = 2;
break;
default:
assert(!"invalid dfdx opcode");
break;
}
shfl = bld.mkOp2(OP_SHFL, TYPE_F32, bld.getScratch(),
insn->getSrc(0), bld.mkImm(xid));
shfl->subOp = NV50_IR_SUBOP_SHFL_BFLY;
insn->op = OP_QUADOP;
insn->subOp = qop;
insn->lanes = 0; /* abused for !.ndv */
insn->setSrc(1, insn->getSrc(0));
insn->setSrc(0, shfl->getDef(0));
return true;
}
bool
GM107LoweringPass::handlePFETCH(Instruction *i)
{
Value *tmp0 = bld.getScratch();
Value *tmp1 = bld.getScratch();
Value *tmp2 = bld.getScratch();
bld.mkOp1(OP_RDSV, TYPE_U32, tmp0, bld.mkSysVal(SV_INVOCATION_INFO, 0));
bld.mkOp2(OP_SHR , TYPE_U32, tmp1, tmp0, bld.mkImm(16));
bld.mkOp2(OP_AND , TYPE_U32, tmp0, tmp0, bld.mkImm(0xff));
bld.mkOp2(OP_AND , TYPE_U32, tmp1, tmp1, bld.mkImm(0xff));
bld.mkOp1(OP_MOV , TYPE_U32, tmp2, bld.mkImm(i->getSrc(0)->reg.data.u32));
bld.mkOp3(OP_MAD , TYPE_U32, tmp0, tmp0, tmp1, tmp2);
i->setSrc(0, tmp0);
i->setSrc(1, NULL);
return true;
}
bool
GM107LoweringPass::handlePOPCNT(Instruction *i)
{
Value *tmp = bld.mkOp2v(OP_AND, i->sType, bld.getScratch(),
i->getSrc(0), i->getSrc(1));
i->setSrc(0, tmp);
i->setSrc(1, NULL);
return TRUE;
}
//
// - add quadop dance for texturing
// - put FP outputs in GPRs
// - convert instruction sequences
//
bool
GM107LoweringPass::visit(Instruction *i)
{
bld.setPosition(i, false);
if (i->cc != CC_ALWAYS)
checkPredicate(i);
switch (i->op) {
case OP_TEX:
case OP_TXB:
case OP_TXL:
case OP_TXF:
case OP_TXG:
return handleTEX(i->asTex());
case OP_TXD:
return handleTXD(i->asTex());
case OP_TXLQ:
return handleTXLQ(i->asTex());
case OP_TXQ:
return handleTXQ(i->asTex());
case OP_EX2:
bld.mkOp1(OP_PREEX2, TYPE_F32, i->getDef(0), i->getSrc(0));
i->setSrc(0, i->getDef(0));
break;
case OP_POW:
return handlePOW(i);
case OP_DIV:
return handleDIV(i);
case OP_MOD:
return handleMOD(i);
case OP_SQRT:
return handleSQRT(i);
case OP_EXPORT:
return handleEXPORT(i);
case OP_PFETCH:
return handlePFETCH(i);
case OP_EMIT:
case OP_RESTART:
return handleOUT(i);
case OP_RDSV:
return handleRDSV(i);
case OP_WRSV:
return handleWRSV(i);
case OP_LOAD:
if (i->src(0).getFile() == FILE_SHADER_INPUT) {
if (prog->getType() == Program::TYPE_COMPUTE) {
i->getSrc(0)->reg.file = FILE_MEMORY_CONST;
i->getSrc(0)->reg.fileIndex = 0;
} else
if (prog->getType() == Program::TYPE_GEOMETRY &&
i->src(0).isIndirect(0)) {
// XXX: this assumes vec4 units
Value *ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
i->getIndirect(0, 0), bld.mkImm(4));
i->setIndirect(0, 0, ptr);
} else {
i->op = OP_VFETCH;
assert(prog->getType() != Program::TYPE_FRAGMENT); // INTERP
}
}
break;
case OP_ATOM:
{
const bool cctl = i->src(0).getFile() == FILE_MEMORY_GLOBAL;
handleATOM(i);
handleCasExch(i, cctl);
}
break;
case OP_SULDB:
case OP_SULDP:
case OP_SUSTB:
case OP_SUSTP:
case OP_SUREDB:
case OP_SUREDP:
handleSurfaceOpNVE4(i->asTex());
break;
case OP_DFDX:
case OP_DFDY:
handleDFDX(i);
break;
case OP_POPCNT:
handlePOPCNT(i);
break;
default:
break;
}
return true;
}
} // namespace nv50_ir
|
fix manual TXD for array targets
|
gm107/ir: fix manual TXD for array targets
This parallels the fixes in commit afea9bae.
Signed-off-by: Ilia Mirkin <[email protected]>
Cc: "10.3" <[email protected]>
|
C++
|
mit
|
metora/MesaGLSLCompiler,dellis1972/glsl-optimizer,wolf96/glsl-optimizer,jbarczak/glsl-optimizer,tokyovigilante/glsl-optimizer,dellis1972/glsl-optimizer,mcanthony/glsl-optimizer,tokyovigilante/glsl-optimizer,zeux/glsl-optimizer,zeux/glsl-optimizer,zz85/glsl-optimizer,benaadams/glsl-optimizer,djreep81/glsl-optimizer,zz85/glsl-optimizer,zeux/glsl-optimizer,mcanthony/glsl-optimizer,mcanthony/glsl-optimizer,wolf96/glsl-optimizer,benaadams/glsl-optimizer,bkaradzic/glsl-optimizer,wolf96/glsl-optimizer,wolf96/glsl-optimizer,djreep81/glsl-optimizer,benaadams/glsl-optimizer,jbarczak/glsl-optimizer,djreep81/glsl-optimizer,dellis1972/glsl-optimizer,jbarczak/glsl-optimizer,benaadams/glsl-optimizer,zz85/glsl-optimizer,bkaradzic/glsl-optimizer,jbarczak/glsl-optimizer,metora/MesaGLSLCompiler,zz85/glsl-optimizer,zz85/glsl-optimizer,mcanthony/glsl-optimizer,djreep81/glsl-optimizer,tokyovigilante/glsl-optimizer,tokyovigilante/glsl-optimizer,zz85/glsl-optimizer,bkaradzic/glsl-optimizer,tokyovigilante/glsl-optimizer,benaadams/glsl-optimizer,bkaradzic/glsl-optimizer,zeux/glsl-optimizer,dellis1972/glsl-optimizer,metora/MesaGLSLCompiler,wolf96/glsl-optimizer,dellis1972/glsl-optimizer,djreep81/glsl-optimizer,benaadams/glsl-optimizer,zeux/glsl-optimizer,bkaradzic/glsl-optimizer,jbarczak/glsl-optimizer,mcanthony/glsl-optimizer
|
7688512fcb0bcf7428dee1ef32dac5520ee35c24
|
src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_mc.C
|
src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_mc.C
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_mc.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_draminit_mc.C
/// @brief Initialize the memory controller to take over the DRAM
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <p9_mss_draminit_mc.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCS;
extern "C"
{
///
/// @brief Initialize the MC now that DRAM is up
/// @param[in] i_target, the McBIST of the ports
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_draminit_mc( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
auto l_mca = i_target.getChildren<TARGET_TYPE_MCA>();
FAPI_INF("Start draminit MC");
// If we don't have any ports, lets go.
if (l_mca.size() == 0)
{
FAPI_INF("No ports? %s", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
// While we're doing the scominit in here, lets do it for all ports before we dump the MCS regs.
for (auto p : i_target.getChildren<TARGET_TYPE_MCA>())
{
mss::mc<TARGET_TYPE_MCS> l_mc;
// Don't do this yet - leverage the sim inits for the moment
#if 0
// All the scominit for this MCA
l_mc.scominit(p);
#endif
// Setup the MC port/dimm address translation registers
FAPI_TRY( l_mc.setup_xlate_map(p) );
}
for (auto p : l_mca)
{
// Setup the read_pointer_delay
// TK: Do we need to do this in general or is this a place holder until the
// init file gets here?
{
fapi2::buffer<uint64_t> l_data;
FAPI_TRY( mss::getScom(p, MCA_RECR, l_data) );
l_data.insertFromRight<MCA_RECR_MBSECCQ_READ_POINTER_DELAY, MCA_RECR_MBSECCQ_READ_POINTER_DELAY_LEN>(0x1);
FAPI_DBG("writing read pointer delay 0x%016lx %s", l_data, mss::c_str(p));
FAPI_TRY( mss::putScom(p, MCA_RECR, l_data) );
}
// Set the IML Complete bit MBSSQ(3) (SCOM Addr: 0x02011417) to indicate that IML has completed
// Can't find MBSSQ or the iml_complete bit - asked Steve. Gary VH created this bit as a scratch
// 'you are hre bit' and it was removed for Nimbus. Gary VH asked for it to be put back in. Not
// sure if that happened yet. BRS (2/16).
// Reset addr_mux_sel to “0” to allow the MCA to take control of the DDR interface over from CCS.
// (Note: this step must remain in this procedure to ensure that data path is placed into mainline
// mode prior to running memory diagnostics. This step maybe superfluous but not harmful.)
// Note: addr_mux_sel is set low in p9_mss_draminit(), however that might be a work-around so we
// set it low here kind of like belt-and-suspenders. BRS
FAPI_TRY( mss::change_addr_mux_sel(p, mss::LOW) );
// Re-enable port fails. Turned off in draminit_training
FAPI_TRY( mss::change_port_fail_disable(p, mss::OFF ) );
// Step Two.1: Check RCD protect time on RDIMM and LRDIMM
// Step Two.2: Enable address inversion on each MBA for ALL CARDS
// Start the refresh engines by setting MBAREF0Q(0) = “1”. Note that the remaining bits in
// MBAREF0Q should retain their initialization values.
FAPI_TRY( mss::change_refresh_enable(p, mss::HIGH) );
// Power management is handled in the init file. (or should be BRS)
// Enabling periodic calibration
FAPI_TRY( mss::enable_periodic_cal(p) );
// Step Six: Setup Control Bit ECC
FAPI_TRY( mss::enable_read_ecc(p) );
// At this point the DDR interface must be monitored for memory errors. Memory related FIRs should be unmasked.
// Cram a fast write, followed by a read in here for giggles
{
mss::mcbist::program<TARGET_TYPE_MCBIST> l_program;
uint64_t l_start = 0;
uint64_t l_end = 0;
uint64_t l_pattern = 0;
// Write
{
// Uses address register set 0
mss::mcbist::subtest_t<TARGET_TYPE_MCBIST> l_fw_subtest =
mss::mcbist::write_subtest<TARGET_TYPE_MCBIST>();
l_fw_subtest.enable_port(mss::pos(p));
// ECC mode off causes compares. Fixed mode data means it will
// compare to the data in the MCBFD#Q registers.
l_fw_subtest.change_ecc_mode(mss::OFF);
// HACK: We only need to worry about the DIMM in slot 0 right now
l_fw_subtest.enable_dimm(0);
l_program.iv_subtests.push_back(l_fw_subtest);
}
// Read
{
// Uses address register set 0
mss::mcbist::subtest_t<TARGET_TYPE_MCBIST> l_fr_subtest =
mss::mcbist::read_subtest<TARGET_TYPE_MCBIST>();
l_fr_subtest.enable_port(mss::pos(p));
// ECC mode off causes compares. Fixed mode data means it will
// compare to the data in the MCBFD#Q registers.
l_fr_subtest.change_ecc_mode(mss::OFF);
// HACK: We only need to worry about the DIMM in slot 0 right now
l_fr_subtest.enable_dimm(0);
l_program.iv_subtests.push_back(l_fr_subtest);
}
FAPI_TRY( mss::mcbist_start_addr(p, l_start) );
FAPI_TRY( mss::mcbist_end_addr(p, l_end) );
// TK: calculate proper polling based on address range
// Setup a nice pattern for writing
FAPI_TRY( mss::mcbist_write_data(i_target, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD0Q, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD1Q, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD2Q, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD3Q, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD4Q, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD5Q, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD6Q, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD7Q, l_pattern) );
// Sanity check - can't do much if end is before start.
// This is either a programming error or a mistake in attribute settings. So we'll just assert.
if (l_end < l_start)
{
FAPI_ERR("mcbist end address is less than mcbist starting address. s: 0x%x e: 0x%x", l_start, l_end);
fapi2::Assert(false);
}
// By default we're in maint address mode so we do a start + len and the 'BIST increments for us.
// By default, the write subtest uses the 0'th address start/end registers.
mss::mcbist::config_address_range0(i_target, l_start, l_end - l_start);
// Setup the polling based on a heuristic <cough>guess</cough>
// Looks like 20ns per address for a write/read program, and add a long number of polls
l_program.iv_poll.iv_initial_delay = (l_end - l_start) * 2 * mss::DELAY_10NS;
l_program.iv_poll.iv_initial_sim_delay =
mss::cycles_to_simcycles(mss::ns_to_cycles(i_target, l_program.iv_poll.iv_initial_delay));
l_program.iv_poll.iv_poll_count = 100;
// Just one port for now. Per Shelton we need to set this in maint adress mode
// even tho we specify the port/dimm in the subtest.
fapi2::buffer<uint8_t> l_port;
l_port.setBit(mss::pos(p));
l_program.select_ports(l_port >> 4);
// Kick it off, wait for a result
FAPI_TRY( mss::mcbist::execute(i_target, l_program) );
}
}
fapi_try_exit:
FAPI_INF("End draminit MC");
return fapi2::current_err;
}
}
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_mc.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_draminit_mc.C
/// @brief Initialize the memory controller to take over the DRAM
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <p9_mss_draminit_mc.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCS;
extern "C"
{
///
/// @brief Initialize the MC now that DRAM is up
/// @param[in] i_target, the McBIST of the ports
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_draminit_mc( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
auto l_mca = i_target.getChildren<TARGET_TYPE_MCA>();
FAPI_INF("Start draminit MC");
// If we don't have any ports, lets go.
if (l_mca.size() == 0)
{
FAPI_INF("No ports? %s", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
// While we're doing the scominit in here, lets do it for all ports before we dump the MCS regs.
for (auto p : i_target.getChildren<TARGET_TYPE_MCA>())
{
mss::mc<TARGET_TYPE_MCS> l_mc;
// Don't do this yet - leverage the sim inits for the moment
#if 0
// All the scominit for this MCA
l_mc.scominit(p);
#endif
// Setup the MC port/dimm address translation registers
FAPI_TRY( l_mc.setup_xlate_map(p) );
}
for (auto p : l_mca)
{
// Setup the read_pointer_delay
// TK: Do we need to do this in general or is this a place holder until the
// init file gets here?
{
fapi2::buffer<uint64_t> l_data;
FAPI_TRY( mss::getScom(p, MCA_RECR, l_data) );
l_data.insertFromRight<MCA_RECR_MBSECCQ_READ_POINTER_DELAY, MCA_RECR_MBSECCQ_READ_POINTER_DELAY_LEN>(0x1);
FAPI_DBG("writing read pointer delay 0x%016lx %s", l_data, mss::c_str(p));
FAPI_TRY( mss::putScom(p, MCA_RECR, l_data) );
}
// Set the IML Complete bit MBSSQ(3) (SCOM Addr: 0x02011417) to indicate that IML has completed
// Can't find MBSSQ or the iml_complete bit - asked Steve. Gary VH created this bit as a scratch
// 'you are hre bit' and it was removed for Nimbus. Gary VH asked for it to be put back in. Not
// sure if that happened yet. BRS (2/16).
// Reset addr_mux_sel to “0” to allow the MCA to take control of the DDR interface over from CCS.
// (Note: this step must remain in this procedure to ensure that data path is placed into mainline
// mode prior to running memory diagnostics. This step maybe superfluous but not harmful.)
// Note: addr_mux_sel is set low in p9_mss_draminit(), however that might be a work-around so we
// set it low here kind of like belt-and-suspenders. BRS
FAPI_TRY( mss::change_addr_mux_sel(p, mss::LOW) );
// Re-enable port fails. Turned off in draminit_training
FAPI_TRY( mss::change_port_fail_disable(p, mss::OFF ) );
// Step Two.1: Check RCD protect time on RDIMM and LRDIMM
// Step Two.2: Enable address inversion on each MBA for ALL CARDS
// Start the refresh engines by setting MBAREF0Q(0) = “1”. Note that the remaining bits in
// MBAREF0Q should retain their initialization values.
FAPI_TRY( mss::change_refresh_enable(p, mss::HIGH) );
// Power management is handled in the init file. (or should be BRS)
// Enabling periodic calibration
FAPI_TRY( mss::enable_periodic_cal(p) );
// Step Six: Setup Control Bit ECC
FAPI_TRY( mss::enable_read_ecc(p) );
// At this point the DDR interface must be monitored for memory errors. Memory related FIRs should be unmasked.
// Cram a fast write, followed by a read in here for giggles
{
mss::mcbist::program<TARGET_TYPE_MCBIST> l_program;
uint64_t l_start = 0;
uint64_t l_end = 0;
uint64_t l_pattern = 0;
// Write
{
// Uses address register set 0
mss::mcbist::subtest_t<TARGET_TYPE_MCBIST> l_fw_subtest =
mss::mcbist::write_subtest<TARGET_TYPE_MCBIST>();
l_fw_subtest.enable_port(mss::pos(p));
// Run in ECC mode
// HACK: We only need to worry about the DIMM in slot 0 right now
l_fw_subtest.enable_dimm(0);
l_program.iv_subtests.push_back(l_fw_subtest);
}
// Read
{
// Uses address register set 0
mss::mcbist::subtest_t<TARGET_TYPE_MCBIST> l_fr_subtest =
mss::mcbist::read_subtest<TARGET_TYPE_MCBIST>();
l_fr_subtest.enable_port(mss::pos(p));
// Run in ECC mode
// HACK: We only need to worry about the DIMM in slot 0 right now
l_fr_subtest.enable_dimm(0);
l_program.iv_subtests.push_back(l_fr_subtest);
}
FAPI_TRY( mss::mcbist_start_addr(p, l_start) );
FAPI_TRY( mss::mcbist_end_addr(p, l_end) );
// TK: calculate proper polling based on address range
// Setup a nice pattern for writing
FAPI_TRY( mss::mcbist_write_data(i_target, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD0Q, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD1Q, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD2Q, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD3Q, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD4Q, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD5Q, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD6Q, l_pattern) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD7Q, l_pattern) );
// Sanity check - can't do much if end is before start.
// This is either a programming error or a mistake in attribute settings. So we'll just assert.
if (l_end < l_start)
{
FAPI_ERR("mcbist end address is less than mcbist starting address. s: 0x%x e: 0x%x", l_start, l_end);
fapi2::Assert(false);
}
// By default we're in maint address mode so we do a start + len and the 'BIST increments for us.
// By default, the write subtest uses the 0'th address start/end registers.
mss::mcbist::config_address_range0(i_target, l_start, l_end - l_start);
// Setup the polling based on a heuristic <cough>guess</cough>
// Looks like 20ns per address for a write/read program, and add a long number of polls
l_program.iv_poll.iv_initial_delay = (l_end - l_start) * 2 * mss::DELAY_10NS;
l_program.iv_poll.iv_initial_sim_delay =
mss::cycles_to_simcycles(mss::ns_to_cycles(i_target, l_program.iv_poll.iv_initial_delay));
l_program.iv_poll.iv_poll_count = 100;
// Just one port for now. Per Shelton we need to set this in maint adress mode
// even tho we specify the port/dimm in the subtest.
fapi2::buffer<uint8_t> l_port;
l_port.setBit(mss::pos(p));
l_program.select_ports(l_port >> 4);
// Kick it off, wait for a result
FAPI_TRY( mss::mcbist::execute(i_target, l_program) );
}
}
fapi_try_exit:
FAPI_INF("End draminit MC");
return fapi2::current_err;
}
}
|
Change draminit_mc to run ECC mode not compare mode
|
Change draminit_mc to run ECC mode not compare mode
Change-Id: Iec5a1e72d7c08c2cf5b9b145501934cb15b13a4e
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/22852
Tested-by: Jenkins Server
Tested-by: Hostboot CI
Reviewed-by: Joseph J. McGill <[email protected]>
Reviewed-by: Louis Stermole <[email protected]>
Reviewed-by: Jennifer A. Stofer <[email protected]>
|
C++
|
apache-2.0
|
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
|
89fc8ebb7b6e496eafa5a3d70b442b87c005ba43
|
xchainer/array_to_device_test.cc
|
xchainer/array_to_device_test.cc
|
#include <cassert>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include <nonstd/optional.hpp>
#include "xchainer/array.h"
#include "xchainer/backend.h"
#include "xchainer/backward.h"
#include "xchainer/device.h"
#include "xchainer/error.h"
#include "xchainer/indexable_array.h"
#include "xchainer/indexer.h"
#include "xchainer/native_backend.h"
#include "xchainer/native_device.h"
#include "xchainer/testing/array.h"
#include "xchainer/testing/context_session.h"
#include "xchainer/testing/util.h"
namespace xchainer {
namespace {
// Test configuration class
class TestConfig {
public:
// backend <0> can transfer from backend <1> to backend <2>
using Key = std::tuple<int, int, int>;
TestConfig() {
set_.insert({
Key{0, 0, 0}, // backend0 can transfer with itself
Key{0, 0, 1}, // backend0 can transfer to backend1
Key{0, 2, 0}, // backend0 can transfer from backend2
// backend0 and backend3 are incompatible
});
}
// Returns true if the backend `who` can transfer data from backend `from` to backend `to`
bool CanTransfer(int who, int from, int to) { return set_.find(std::make_tuple(who, from, to)) != set_.end(); }
// Return the number of test backends
int num_backends() { return 4; }
private:
std::set<Key> set_;
};
// Instantiate the global test configuration
TestConfig g_config;
// Test backend class
class TestBackend : public NativeBackend {
public:
TestBackend(Context& context, int num) : NativeBackend(context), num_(num) {}
int num() const { return num_; }
std::string GetName() const override { return "backend" + std::to_string(num_); }
bool SupportsTransfer(Device& src_device, Device& dst_device) override {
int src_num = dynamic_cast<TestBackend&>(src_device.backend()).num();
int dst_num = dynamic_cast<TestBackend&>(dst_device.backend()).num();
return g_config.CanTransfer(num_, src_num, dst_num);
}
int GetDeviceCount() const override { return 1; }
std::unique_ptr<Device> CreateDevice(int index) override {
assert(index == 0);
return std::make_unique<NativeDevice>(*this, index);
}
private:
int num_;
};
// Test fixture for compatible transfer
class ArrayToDeviceCompatibleTest : public ::testing::TestWithParam<::testing::tuple<int, int, int>> {
protected:
void SetUp() override {
context_session_.emplace();
default_backend_num_ = ::testing::get<0>(GetParam());
src_backend_num_ = ::testing::get<1>(GetParam());
dst_backend_num_ = ::testing::get<2>(GetParam());
backends_.clear();
for (int i = 0; i < g_config.num_backends(); ++i) {
backends_.emplace_back(std::make_unique<TestBackend>(context_session_->context(), i));
}
// Set default backend (only if default_backend_num is non-negative)
if (default_backend_num_ >= 0) {
device_scope_ = std::make_unique<DeviceScope>(*GetDefaultDevicePtr());
}
}
void TearDown() override {
device_scope_.reset();
context_session_.reset();
backends_.clear();
}
Device* GetDefaultDevicePtr() {
if (default_backend_num_ < 0) {
return nullptr;
}
return &backends_[default_backend_num_]->GetDevice(0);
}
Device& GetSourceDevice() { return backends_[src_backend_num_]->GetDevice(0); }
Device& GetDestinationDevice() { return backends_[dst_backend_num_]->GetDevice(0); }
private:
nonstd::optional<testing::ContextSession> context_session_;
std::unique_ptr<DeviceScope> device_scope_;
std::vector<std::unique_ptr<TestBackend>> backends_;
int default_backend_num_{};
int src_backend_num_{};
int dst_backend_num_{};
};
void ExpectArraysEqual(const Array& expected, const Array& actual) {
EXPECT_EQ(expected.dtype(), actual.dtype());
EXPECT_EQ(expected.shape(), actual.shape());
VisitDtype(expected.dtype(), [&expected, &actual](auto pt) {
using T = typename decltype(pt)::type;
IndexableArray<const T> expected_iarray{expected};
IndexableArray<const T> actual_iarray{actual};
Indexer<> indexer{expected.shape()};
for (int64_t i = 0; i < indexer.total_size(); ++i) {
indexer.Set(i);
EXPECT_EQ(expected_iarray[indexer], actual_iarray[indexer]);
}
});
}
TEST_P(ArrayToDeviceCompatibleTest, ToDevice) {
Device& src_dev = GetSourceDevice();
Device& dst_dev = GetDestinationDevice();
Device& default_device = GetDefaultDevice();
// Allocate the source array
float data[] = {1.0f, 2.0f};
auto nop = [](void* p) {
(void)p; // unused
};
Array a = Array::FromBuffer({2, 1}, Dtype::kFloat32, std::shared_ptr<float>(data, nop), src_dev);
// Transfer
Array b = a.ToDevice(dst_dev);
EXPECT_EQ(&b.device(), &dst_dev) << "Array::ToDevice must allocate an array on the specified device.";
EXPECT_EQ(&a.device(), &src_dev) << "Array::ToDevice must not alter the device of the original array.";
if (&dst_dev == &src_dev) {
EXPECT_EQ(a.data().get(), b.data().get()) << "Array::ToDevice must return an alias in same-device transfer.";
}
EXPECT_EQ(&GetDefaultDevice(), &default_device) << "Array::ToDevice must not alter the default device.";
ExpectArraysEqual(a, b);
}
TEST_P(ArrayToDeviceCompatibleTest, ToDeviceNonContiguous) {
Device& src_dev = GetSourceDevice();
Device& dst_dev = GetDestinationDevice();
Device& default_device = GetDefaultDevice();
Array a = testing::MakeArray({2, 4}) //
.WithLinearData<int32_t>() //
.WithPadding(1) //
.WithDevice(src_dev);
// Transfer
Array b = a.ToDevice(dst_dev);
EXPECT_EQ(&b.device(), &dst_dev) << "Array::ToDevice must allocate an array on the specified device.";
EXPECT_EQ(&a.device(), &src_dev) << "Array::ToDevice must not alter the device of the original array.";
if (&dst_dev == &src_dev) {
EXPECT_EQ(a.data().get(), b.data().get()) << "Array::ToDevice must return an alias in same-device transfer.";
}
EXPECT_EQ(&GetDefaultDevice(), &default_device) << "Array::ToDevice must not alter the default device.";
ExpectArraysEqual(a, b);
}
INSTANTIATE_TEST_CASE_P(
BackendCombination,
ArrayToDeviceCompatibleTest,
::testing::Values(
std::make_tuple(-1, 0, 0), // transfer between same devices
std::make_tuple(-1, 0, 1), // transfer to 1
std::make_tuple(-1, 2, 0), // transfer from 2
std::make_tuple(2, 0, 1))); // checks default device does not change
// Test for incompatible transfer
TEST(ArrayToDeviceIncompatibleTest, ToDeviceIncompatible) {
testing::ContextSession context_session;
TestBackend src_backend{context_session.context(), 0}; // incompatible configuration
TestBackend dst_backend{context_session.context(), 3};
Device& src_dev = src_backend.GetDevice(0);
Device& dst_dev = dst_backend.GetDevice(0);
// Allocate the source array
float data[] = {1.0f, 2.0f};
auto nop = [](void* p) {
(void)p; // unused
};
Array a = Array::FromBuffer({2, 1}, Dtype::kFloat32, std::shared_ptr<float>(data, nop), src_dev);
// Transfer
EXPECT_THROW(a.ToDevice(dst_dev), XchainerError) << "Array::ToDevice must throw if incompatible device is given.";
}
TEST(ArrayToDeviceArithmeticTest, Arithmetic) {
testing::ContextSession context_session;
NativeBackend backend{context_session.context()};
XCHAINER_REQUIRE_DEVICE(backend, 3);
Device& dev0 = backend.GetDevice(0);
Device& dev1 = backend.GetDevice(1);
Device& dev2 = backend.GetDevice(2); // default device
DeviceScope device_scope{dev2};
// Allocate the source array
auto nop = [](void* p) {
(void)p; // unused
};
float data0[]{1.0f, 2.0f};
float data1[]{3.0f, 4.0f};
float data2[]{5.0f, 6.0f};
Shape shape{2, 1};
Array a0 = Array::FromBuffer(shape, Dtype::kFloat32, std::shared_ptr<float>(data0, nop), dev0);
Array a1 = Array::FromBuffer(shape, Dtype::kFloat32, std::shared_ptr<float>(data1, nop), dev0);
Array a2 = Array::FromBuffer(shape, Dtype::kFloat32, std::shared_ptr<float>(data2, nop), dev1);
a0.RequireGrad();
a1.RequireGrad();
a2.RequireGrad();
// Test preconditions
ASSERT_EQ(&dev0, &a0.device());
ASSERT_EQ(&dev0, &a1.device());
ASSERT_EQ(&dev1, &a2.device());
// Forward
Array b = a0 * a1;
Array b_dev1 = b.ToDevice(dev1);
Array c = b_dev1 + a2;
ASSERT_TRUE(c.IsGradRequired());
ASSERT_TRUE(b_dev1.IsGradRequired());
ASSERT_TRUE(b.IsGradRequired());
// Check forward correctness
EXPECT_EQ(&dev0, &b.device());
EXPECT_EQ(&dev1, &b_dev1.device());
EXPECT_EQ(&dev1, &c.device());
EXPECT_TRUE(c.IsGradRequired());
EXPECT_TRUE(b_dev1.IsGradRequired());
EXPECT_TRUE(b.IsGradRequired());
float datay[]{8.0f, 14.0f}; // d0 * d1 + d2
ExpectArraysEqual(c, Array::FromBuffer(shape, Dtype::kFloat32, std::shared_ptr<float>(datay, nop)));
// Backward
Backward(c);
// Check backward correctness
ASSERT_TRUE(a0.GetGrad().has_value());
ASSERT_TRUE(a1.GetGrad().has_value());
ASSERT_TRUE(a2.GetGrad().has_value());
ASSERT_TRUE(c.GetGrad().has_value());
EXPECT_EQ(&dev0, &a0.GetGrad()->device());
EXPECT_EQ(&dev0, &a1.GetGrad()->device());
EXPECT_EQ(&dev1, &a2.GetGrad()->device());
EXPECT_EQ(&dev1, &c.GetGrad()->device());
float data0_grad[]{3.0f, 4.0f};
float data1_grad[]{1.0f, 2.0f};
float data2_grad[]{1.0f, 1.0f};
ExpectArraysEqual(*a0.GetGrad(), Array::FromBuffer(shape, Dtype::kFloat32, std::shared_ptr<float>(data0_grad, nop)));
ExpectArraysEqual(*a1.GetGrad(), Array::FromBuffer(shape, Dtype::kFloat32, std::shared_ptr<float>(data1_grad, nop)));
ExpectArraysEqual(*a2.GetGrad(), Array::FromBuffer(shape, Dtype::kFloat32, std::shared_ptr<float>(data2_grad, nop)));
}
} // namespace
} // namespace xchainer
|
#include <cassert>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include <nonstd/optional.hpp>
#include "xchainer/array.h"
#include "xchainer/backend.h"
#include "xchainer/backward.h"
#include "xchainer/device.h"
#include "xchainer/error.h"
#include "xchainer/indexable_array.h"
#include "xchainer/indexer.h"
#include "xchainer/native_backend.h"
#include "xchainer/native_device.h"
#include "xchainer/testing/array.h"
#include "xchainer/testing/context_session.h"
#include "xchainer/testing/util.h"
namespace xchainer {
namespace {
// Test configuration class
class TestConfig {
public:
// backend <0> can transfer from backend <1> to backend <2>
using Key = std::tuple<int, int, int>;
TestConfig() {
set_.insert({
Key{0, 0, 0}, // backend0 can transfer with itself
Key{0, 0, 1}, // backend0 can transfer to backend1
Key{0, 2, 0}, // backend0 can transfer from backend2
// backend0 and backend3 are incompatible
});
}
// Returns true if the backend `who` can transfer data from backend `from` to backend `to`
bool CanTransfer(int who, int from, int to) { return set_.find(std::make_tuple(who, from, to)) != set_.end(); }
// Return the number of test backends
int num_backends() { return 4; }
private:
std::set<Key> set_;
};
// Instantiate the global test configuration
TestConfig g_config;
// Test backend class
class TestBackend : public NativeBackend {
public:
TestBackend(Context& context, int num) : NativeBackend(context), num_(num) {}
int num() const { return num_; }
std::string GetName() const override { return "backend" + std::to_string(num_); }
bool SupportsTransfer(Device& src_device, Device& dst_device) override {
int src_num = dynamic_cast<TestBackend&>(src_device.backend()).num();
int dst_num = dynamic_cast<TestBackend&>(dst_device.backend()).num();
return g_config.CanTransfer(num_, src_num, dst_num);
}
int GetDeviceCount() const override { return 1; }
std::unique_ptr<Device> CreateDevice(int index) override {
assert(index == 0);
return std::make_unique<NativeDevice>(*this, index);
}
private:
int num_;
};
// Test fixture for compatible transfer
class ArrayToDeviceCompatibleTest : public ::testing::TestWithParam<::testing::tuple<int, int, int>> {
protected:
void SetUp() override {
context_session_.emplace();
default_backend_num_ = ::testing::get<0>(GetParam());
src_backend_num_ = ::testing::get<1>(GetParam());
dst_backend_num_ = ::testing::get<2>(GetParam());
backends_.clear();
for (int i = 0; i < g_config.num_backends(); ++i) {
backends_.emplace_back(std::make_unique<TestBackend>(context_session_->context(), i));
}
// Set default backend (only if default_backend_num is non-negative)
if (default_backend_num_ >= 0) {
device_scope_ = std::make_unique<DeviceScope>(*GetDefaultDevicePtr());
}
}
void TearDown() override {
device_scope_.reset();
context_session_.reset();
backends_.clear();
}
Device* GetDefaultDevicePtr() {
if (default_backend_num_ < 0) {
return nullptr;
}
return &backends_[default_backend_num_]->GetDevice(0);
}
Device& GetSourceDevice() { return backends_[src_backend_num_]->GetDevice(0); }
Device& GetDestinationDevice() { return backends_[dst_backend_num_]->GetDevice(0); }
private:
nonstd::optional<testing::ContextSession> context_session_;
std::unique_ptr<DeviceScope> device_scope_;
std::vector<std::unique_ptr<TestBackend>> backends_;
int default_backend_num_{};
int src_backend_num_{};
int dst_backend_num_{};
};
void ExpectArraysEqual(const Array& expected, const Array& actual) {
EXPECT_EQ(expected.dtype(), actual.dtype());
EXPECT_EQ(expected.shape(), actual.shape());
VisitDtype(expected.dtype(), [&expected, &actual](auto pt) {
using T = typename decltype(pt)::type;
IndexableArray<const T> expected_iarray{expected};
IndexableArray<const T> actual_iarray{actual};
Indexer<> indexer{expected.shape()};
for (int64_t i = 0; i < indexer.total_size(); ++i) {
indexer.Set(i);
EXPECT_EQ(expected_iarray[indexer], actual_iarray[indexer]);
}
});
}
TEST_P(ArrayToDeviceCompatibleTest, ToDevice) {
Device& src_dev = GetSourceDevice();
Device& dst_dev = GetDestinationDevice();
Device& default_device = GetDefaultDevice();
// Allocate the source array
float data[] = {1.0f, 2.0f};
auto nop = [](void* p) {
(void)p; // unused
};
Array a = Array::FromBuffer({2, 1}, Dtype::kFloat32, std::shared_ptr<float>(data, nop), src_dev);
// Transfer
Array b = a.ToDevice(dst_dev);
EXPECT_EQ(&b.device(), &dst_dev) << "Array::ToDevice must allocate an array on the specified device.";
EXPECT_EQ(&a.device(), &src_dev) << "Array::ToDevice must not alter the device of the original array.";
if (&dst_dev == &src_dev) {
EXPECT_EQ(a.data().get(), b.data().get()) << "Array::ToDevice must return an alias in same-device transfer.";
}
EXPECT_EQ(&GetDefaultDevice(), &default_device) << "Array::ToDevice must not alter the default device.";
ExpectArraysEqual(a, b);
}
TEST_P(ArrayToDeviceCompatibleTest, ToDeviceNonContiguous) {
Device& src_dev = GetSourceDevice();
Device& dst_dev = GetDestinationDevice();
Device& default_device = GetDefaultDevice();
Array a = testing::MakeArray({2, 4}) //
.WithLinearData<int32_t>() //
.WithPadding(1) //
.WithDevice(src_dev);
// Transfer
Array b = a.ToDevice(dst_dev);
EXPECT_EQ(&b.device(), &dst_dev) << "Array::ToDevice must allocate an array on the specified device.";
EXPECT_EQ(&a.device(), &src_dev) << "Array::ToDevice must not alter the device of the original array.";
if (&dst_dev == &src_dev) {
EXPECT_EQ(a.data().get(), b.data().get()) << "Array::ToDevice must return an alias in same-device transfer.";
}
EXPECT_EQ(&GetDefaultDevice(), &default_device) << "Array::ToDevice must not alter the default device.";
EXPECT_EQ(&src_dev != &dst_dev, b.IsContiguous()) << "Array::ToDevice must return a contiguous array if device transfer occurs.";
ExpectArraysEqual(a, b);
}
INSTANTIATE_TEST_CASE_P(
BackendCombination,
ArrayToDeviceCompatibleTest,
::testing::Values(
std::make_tuple(-1, 0, 0), // transfer between same devices
std::make_tuple(-1, 0, 1), // transfer to 1
std::make_tuple(-1, 2, 0), // transfer from 2
std::make_tuple(2, 0, 1))); // checks default device does not change
// Test for incompatible transfer
TEST(ArrayToDeviceIncompatibleTest, ToDeviceIncompatible) {
testing::ContextSession context_session;
TestBackend src_backend{context_session.context(), 0}; // incompatible configuration
TestBackend dst_backend{context_session.context(), 3};
Device& src_dev = src_backend.GetDevice(0);
Device& dst_dev = dst_backend.GetDevice(0);
// Allocate the source array
float data[] = {1.0f, 2.0f};
auto nop = [](void* p) {
(void)p; // unused
};
Array a = Array::FromBuffer({2, 1}, Dtype::kFloat32, std::shared_ptr<float>(data, nop), src_dev);
// Transfer
EXPECT_THROW(a.ToDevice(dst_dev), XchainerError) << "Array::ToDevice must throw if incompatible device is given.";
}
TEST(ArrayToDeviceArithmeticTest, Arithmetic) {
testing::ContextSession context_session;
NativeBackend backend{context_session.context()};
XCHAINER_REQUIRE_DEVICE(backend, 3);
Device& dev0 = backend.GetDevice(0);
Device& dev1 = backend.GetDevice(1);
Device& dev2 = backend.GetDevice(2); // default device
DeviceScope device_scope{dev2};
// Allocate the source array
auto nop = [](void* p) {
(void)p; // unused
};
float data0[]{1.0f, 2.0f};
float data1[]{3.0f, 4.0f};
float data2[]{5.0f, 6.0f};
Shape shape{2, 1};
Array a0 = Array::FromBuffer(shape, Dtype::kFloat32, std::shared_ptr<float>(data0, nop), dev0);
Array a1 = Array::FromBuffer(shape, Dtype::kFloat32, std::shared_ptr<float>(data1, nop), dev0);
Array a2 = Array::FromBuffer(shape, Dtype::kFloat32, std::shared_ptr<float>(data2, nop), dev1);
a0.RequireGrad();
a1.RequireGrad();
a2.RequireGrad();
// Test preconditions
ASSERT_EQ(&dev0, &a0.device());
ASSERT_EQ(&dev0, &a1.device());
ASSERT_EQ(&dev1, &a2.device());
// Forward
Array b = a0 * a1;
Array b_dev1 = b.ToDevice(dev1);
Array c = b_dev1 + a2;
ASSERT_TRUE(c.IsGradRequired());
ASSERT_TRUE(b_dev1.IsGradRequired());
ASSERT_TRUE(b.IsGradRequired());
// Check forward correctness
EXPECT_EQ(&dev0, &b.device());
EXPECT_EQ(&dev1, &b_dev1.device());
EXPECT_EQ(&dev1, &c.device());
EXPECT_TRUE(c.IsGradRequired());
EXPECT_TRUE(b_dev1.IsGradRequired());
EXPECT_TRUE(b.IsGradRequired());
float datay[]{8.0f, 14.0f}; // d0 * d1 + d2
ExpectArraysEqual(c, Array::FromBuffer(shape, Dtype::kFloat32, std::shared_ptr<float>(datay, nop)));
// Backward
Backward(c);
// Check backward correctness
ASSERT_TRUE(a0.GetGrad().has_value());
ASSERT_TRUE(a1.GetGrad().has_value());
ASSERT_TRUE(a2.GetGrad().has_value());
ASSERT_TRUE(c.GetGrad().has_value());
EXPECT_EQ(&dev0, &a0.GetGrad()->device());
EXPECT_EQ(&dev0, &a1.GetGrad()->device());
EXPECT_EQ(&dev1, &a2.GetGrad()->device());
EXPECT_EQ(&dev1, &c.GetGrad()->device());
float data0_grad[]{3.0f, 4.0f};
float data1_grad[]{1.0f, 2.0f};
float data2_grad[]{1.0f, 1.0f};
ExpectArraysEqual(*a0.GetGrad(), Array::FromBuffer(shape, Dtype::kFloat32, std::shared_ptr<float>(data0_grad, nop)));
ExpectArraysEqual(*a1.GetGrad(), Array::FromBuffer(shape, Dtype::kFloat32, std::shared_ptr<float>(data1_grad, nop)));
ExpectArraysEqual(*a2.GetGrad(), Array::FromBuffer(shape, Dtype::kFloat32, std::shared_ptr<float>(data2_grad, nop)));
}
} // namespace
} // namespace xchainer
|
Add check for contiguity
|
Add check for contiguity
|
C++
|
mit
|
wkentaro/chainer,ktnyt/chainer,hvy/chainer,keisuke-umezawa/chainer,chainer/chainer,ktnyt/chainer,wkentaro/chainer,jnishi/chainer,okuta/chainer,niboshi/chainer,tkerola/chainer,niboshi/chainer,keisuke-umezawa/chainer,chainer/chainer,jnishi/chainer,keisuke-umezawa/chainer,chainer/chainer,niboshi/chainer,niboshi/chainer,pfnet/chainer,ktnyt/chainer,okuta/chainer,jnishi/chainer,okuta/chainer,okuta/chainer,wkentaro/chainer,jnishi/chainer,hvy/chainer,ktnyt/chainer,wkentaro/chainer,hvy/chainer,chainer/chainer,hvy/chainer,keisuke-umezawa/chainer
|
ab44926598ed68baf13c9546a5df3a57dc21a711
|
transforms/RemoveErrorCalls.cpp
|
transforms/RemoveErrorCalls.cpp
|
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
#include <cassert>
#include <vector>
#include <set>
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/IR/Type.h"
#if LLVM_VERSION_MAJOR >= 4 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 5)
#include "llvm/IR/InstIterator.h"
#else
#include "llvm/Support/InstIterator.h"
#endif
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include <llvm/IR/DebugInfoMetadata.h>
#include <llvm/Support/CommandLine.h>
using namespace llvm;
bool CloneMetadata(const llvm::Instruction *i1, llvm::Instruction *i2);
namespace {
llvm::cl::opt<bool> useExit("remove-error-calls-use-exit",
llvm::cl::desc("Insert __VERIFIER_exit instead of __VERIFIER_silent_exit\n"),
llvm::cl::init(false));
class RemoveErrorCalls : public FunctionPass {
public:
static char ID;
RemoveErrorCalls() : FunctionPass(ID) {}
virtual bool runOnFunction(Function &F);
};
bool RemoveErrorCalls::runOnFunction(Function &F)
{
bool modified = false;
Module *M = F.getParent();
std::unique_ptr<CallInst> ext;
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E;) {
Instruction *ins = &*I;
++I;
if (CallInst *CI = dyn_cast<CallInst>(ins)) {
if (CI->isInlineAsm())
continue;
const Value *val = CI->getCalledValue()->stripPointerCasts();
const Function *callee = dyn_cast<Function>(val);
if (!callee || callee->isIntrinsic())
continue;
assert(callee->hasName());
StringRef name = callee->getName();
if (name.equals("__VERIFIER_error") ||
name.equals("__assert_fail")) {
if (!ext) {
LLVMContext& Ctx = M->getContext();
Type *argTy = Type::getInt32Ty(Ctx);
auto extF
= M->getOrInsertFunction(useExit ? "__VERIFIER_exit" :
"__VERIFIER_silent_exit",
Type::getVoidTy(Ctx), argTy
#if LLVM_VERSION_MAJOR < 5
, nullptr
#endif
);
std::vector<Value *> args = { ConstantInt::get(argTy, 0) };
ext = std::unique_ptr<CallInst>(CallInst::Create(extF, args));
}
auto CI2 = ext->clone();
CloneMetadata(CI, CI2);
CI2->insertAfter(CI);
CI->eraseFromParent();
modified = true;
}
}
}
return modified;
}
} // namespace
static RegisterPass<RemoveErrorCalls> RERC("remove-error-calls",
"Remove calls to __VERIFIER_error");
char RemoveErrorCalls::ID;
|
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
#include <cassert>
#include <vector>
#include <set>
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/IR/Type.h"
#if LLVM_VERSION_MAJOR >= 4 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 5)
#include "llvm/IR/InstIterator.h"
#else
#include "llvm/Support/InstIterator.h"
#endif
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include <llvm/IR/DebugInfoMetadata.h>
#include <llvm/Support/CommandLine.h>
using namespace llvm;
bool CloneMetadata(const llvm::Instruction *i1, llvm::Instruction *i2);
namespace {
llvm::cl::opt<bool> useExit("remove-error-calls-use-exit",
llvm::cl::desc("Insert __VERIFIER_exit(0) instead of __VERIFIER_assume(0)\n"),
llvm::cl::init(false));
class RemoveErrorCalls : public FunctionPass {
public:
static char ID;
RemoveErrorCalls() : FunctionPass(ID) {}
virtual bool runOnFunction(Function &F);
};
bool RemoveErrorCalls::runOnFunction(Function &F)
{
bool modified = false;
Module *M = F.getParent();
std::unique_ptr<CallInst> ext;
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E;) {
Instruction *ins = &*I;
++I;
if (CallInst *CI = dyn_cast<CallInst>(ins)) {
if (CI->isInlineAsm())
continue;
const Value *val = CI->getCalledValue()->stripPointerCasts();
const Function *callee = dyn_cast<Function>(val);
if (!callee || callee->isIntrinsic())
continue;
assert(callee->hasName());
StringRef name = callee->getName();
if (name.equals("__VERIFIER_error") ||
name.equals("__assert_fail")) {
if (!ext) {
LLVMContext& Ctx = M->getContext();
Type *argTy = Type::getInt32Ty(Ctx);
auto extF
= M->getOrInsertFunction(useExit ? "__VERIFIER_exit" :
"__VERIFIER_assume",
Type::getVoidTy(Ctx), argTy
#if LLVM_VERSION_MAJOR < 5
, nullptr
#endif
);
std::vector<Value *> args = { ConstantInt::get(argTy, 0) };
ext = std::unique_ptr<CallInst>(CallInst::Create(extF, args));
}
// This will insert __VERIFIER_assume(0), which just aborts the path
// (if normal exit would be inserted, the tools would check leaks
// -- this is just a silent exit)
auto CI2 = ext->clone();
CloneMetadata(CI, CI2);
CI2->insertAfter(CI);
CI->eraseFromParent();
modified = true;
}
}
}
return modified;
}
} // namespace
static RegisterPass<RemoveErrorCalls> RERC("remove-error-calls",
"Remove calls to __VERIFIER_error");
char RemoveErrorCalls::ID;
|
Use __VERIFIER_assume instead of __VERIFIER_silent_exit
|
Use __VERIFIER_assume instead of __VERIFIER_silent_exit
|
C++
|
mit
|
staticafi/symbiotic,staticafi/symbiotic,staticafi/symbiotic,staticafi/symbiotic
|
b4798ac581b94e389b5561527e42ea264b58fca2
|
trunk/extension/src/command.cpp
|
trunk/extension/src/command.cpp
|
////////////////////////////////////////////////////////////////////////////////
// Name: command.cpp
// Purpose: Implementation of wxExCommand class
// Author: Anton van Wezenbeek
// Created: 2010-11-26
// RCS-ID: $Id$
// Copyright: (c) 2010 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/infobar.h>
#include <wx/extension/command.h>
#include <wx/extension/frame.h>
#include <wx/extension/log.h>
#if wxUSE_GUI
wxExSTCEntryDialog* wxExCommand::m_Dialog = NULL;
#endif
wxExCommand::wxExCommand()
: m_Error(false)
{
}
long wxExCommand::Execute(const wxString& command, const wxString& wd)
{
m_Command = command;
m_Error = false;
#if wxUSE_STATUSBAR
wxExFrame::StatusText(m_Command);
#endif
if (m_Dialog == NULL)
{
m_Dialog = new wxExSTCEntryDialog(
wxTheApp->GetTopWindow(),
"Command",
wxEmptyString,
wxEmptyString,
wxOK,
wxID_ANY,
wxDefaultPosition,
wxSize(350, 50));
}
m_Output.clear();
wxString cwd;
if (!wd.empty())
{
cwd = wxGetCwd();
if (!wxSetWorkingDirectory(wd))
{
wxLogError(_("Cannot set working directory"));
m_Error = true;
return -1;
}
}
wxArrayString output;
wxArrayString errors;
long retValue;
// Call wxExcute to execute the vcs command and
// collect the output and the errors.
if ((retValue = wxExecute(
m_Command,
output,
errors)) == -1)
{
// See also process, same log is shown.
wxLogError(_("Cannot execute") + ": " + m_Command);
}
else
{
wxExLog::Get()->Log(m_Command);
}
if (!cwd.empty())
{
wxSetWorkingDirectory(cwd);
}
// First output the errors.
for (
size_t i = 0;
i < errors.GetCount();
i++)
{
m_Output += errors[i] + "\n";
}
m_Error = !errors.empty() || retValue == -1;
// Then the normal output, will be empty if there are errors.
for (
size_t j = 0;
j < output.GetCount();
j++)
{
m_Output += output[j] + "\n";
}
return retValue;
}
#if wxUSE_GUI
void wxExCommand::ShowOutput(const wxString& caption) const
{
if (m_Output.empty())
{
wxInfoBar(wxTheApp->GetTopWindow()).ShowMessage(
_("Output is empty"));
}
else if (m_Dialog != NULL)
{
m_Dialog->SetText(m_Output);
m_Dialog->SetTitle(caption.empty() ? m_Command: caption);
m_Dialog->Show();
}
}
#endif
|
////////////////////////////////////////////////////////////////////////////////
// Name: command.cpp
// Purpose: Implementation of wxExCommand class
// Author: Anton van Wezenbeek
// Created: 2010-11-26
// RCS-ID: $Id$
// Copyright: (c) 2010 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/command.h>
#include <wx/extension/frame.h>
#include <wx/extension/log.h>
#if wxUSE_GUI
wxExSTCEntryDialog* wxExCommand::m_Dialog = NULL;
#endif
wxExCommand::wxExCommand()
: m_Error(false)
{
}
long wxExCommand::Execute(const wxString& command, const wxString& wd)
{
m_Command = command;
m_Error = false;
#if wxUSE_STATUSBAR
wxExFrame::StatusText(m_Command);
#endif
if (m_Dialog == NULL)
{
m_Dialog = new wxExSTCEntryDialog(
wxTheApp->GetTopWindow(),
"Command",
wxEmptyString,
wxEmptyString,
wxOK,
wxID_ANY,
wxDefaultPosition,
wxSize(350, 50));
}
m_Output.clear();
wxString cwd;
if (!wd.empty())
{
cwd = wxGetCwd();
if (!wxSetWorkingDirectory(wd))
{
wxLogError(_("Cannot set working directory"));
m_Error = true;
return -1;
}
}
wxArrayString output;
wxArrayString errors;
long retValue;
// Call wxExcute to execute the vcs command and
// collect the output and the errors.
if ((retValue = wxExecute(
m_Command,
output,
errors)) == -1)
{
// See also process, same log is shown.
wxLogError(_("Cannot execute") + ": " + m_Command);
}
else
{
wxExLog::Get()->Log(m_Command);
}
if (!cwd.empty())
{
wxSetWorkingDirectory(cwd);
}
// First output the errors.
for (
size_t i = 0;
i < errors.GetCount();
i++)
{
m_Output += errors[i] + "\n";
}
m_Error = !errors.empty() || retValue == -1;
// Then the normal output, will be empty if there are errors.
for (
size_t j = 0;
j < output.GetCount();
j++)
{
m_Output += output[j] + "\n";
}
return retValue;
}
#if wxUSE_GUI
void wxExCommand::ShowOutput(const wxString& caption) const
{
if (m_Output.empty())
{
wxMessageBox(_("Output is empty"));
}
else if (m_Dialog != NULL)
{
m_Dialog->SetText(m_Output);
m_Dialog->SetTitle(caption.empty() ? m_Command: caption);
m_Dialog->Show();
}
}
#endif
|
use normal message box
|
use normal message box
git-svn-id: e171abefef93db0a74257c7d87d5b6400fe00c1f@4595 f22100f3-aa73-48fe-a4fb-fd497bb32605
|
C++
|
mit
|
antonvw/wxExtension,antonvw/wxExtension,antonvw/wxExtension
|
3867aa15f02a7705b14bdcfc659f634cf077b58a
|
trunk/libmesh/src/apps/meshid.C
|
trunk/libmesh/src/apps/meshid.C
|
// Open the mesh named in command line arguments,
// update ids of one or more of the following enties
// as perscribed on the command line:
// blocks, sidesets and nodesets
#include <iostream>
#include "libmesh_config.h"
#ifdef LIBMESH_HAVE_EXODUS_API
#include "exodusII.h"
#include "exodusII_int.h"
#include "getpot.h"
#define BLOCKS 0x4
#define SIDES 0x2
#define NODES 0x1
void handle_error(int error)
{
std::cout << "An error occured while working with the netCDF API" << std::endl;
exit(1);
}
void usage_error(const char *progname)
{
std::cout << "Usage: " << progname
<< " --input inputmesh --oldid <n> --newid <n> [--nodesetonly | --sidesetonly | --blockonly]"
<< std::endl;
exit(1);
}
int main(int argc, char** argv)
{
GetPot cl(argc, argv);
// Command line parsing
if(!cl.search("--input"))
{
std::cerr << "No --input argument found!" << std::endl;
usage_error(argv[0]);
}
const char* meshname = cl.next("");
if(!cl.search("--oldid"))
{
std::cerr << "No --oldid argument found!" << std::endl;
usage_error(argv[0]);
}
long oldid = cl.next(0);
if(!cl.search("--newid"))
{
std::cerr << "No --newid argument found!" << std::endl;
usage_error(argv[0]);
}
long newid = cl.next(0);
unsigned char flags = 0;
if (cl.search("--nodesetonly"))
flags |= NODES;
if (cl.search("--sidesetonly"))
flags |= SIDES;
if (cl.search("--blockonly"))
flags |= BLOCKS;
if (!flags)
flags = NODES | SIDES | BLOCKS; // ALL ON
// flags are exclusive
if (flags != NODES && flags != SIDES && flags != BLOCKS && flags != (NODES | SIDES | BLOCKS))
{
std::cerr << "Only one of the following options may be active [--nodesetonly | --sidesetonly | --blockonly]!" << std::endl;
usage_error(argv[0]);
}
// Processing
std::string var_name, dim_name;
int status;
int nc_id, var_id, dim_id, var_len;
size_t dim_len;
status = nc_open (meshname, NC_WRITE, &nc_id);
if (status != NC_NOERR) handle_error(status);
for (unsigned char mask = 1<<2; mask; mask>>=1)
{
switch (flags & mask)
{
case BLOCKS:
dim_name = DIM_NUM_EL_BLK;
var_name = VAR_ID_EL_BLK;
break;
case SIDES:
dim_name = DIM_NUM_SS;
var_name = VAR_SS_IDS;
break;
case NODES:
dim_name = DIM_NUM_NS;
var_name = VAR_NS_IDS;
break;
default:
continue;
}
// Get the length of the "variable" in question - stored in a dimension field
status = nc_inq_dimid (nc_id, dim_name.c_str(), &dim_id);
if (status != NC_NOERR) handle_error(status);
status = nc_inq_dimlen (nc_id, dim_id, &dim_len);
if (status != NC_NOERR) handle_error(status);
// Now get the variable values themselves
std::vector<long> var_vals(dim_len);
status = nc_inq_varid (nc_id, var_name.c_str(), &var_id);
if (status != NC_NOERR) handle_error(status);
status = nc_get_var_long (nc_id, var_id, &var_vals[0]);
if (status != NC_NOERR) handle_error(status);
// Update the variable value specified on the command line
for (unsigned int i=0; i<dim_len; ++i)
if (var_vals[i] == oldid)
var_vals[i] = newid;
// Save that value back to the NetCDF database
status = nc_put_var_long (nc_id, var_id, &var_vals[0]);
if (status != NC_NOERR) handle_error(status);
}
// Write out the dataset
status = nc_close(nc_id);
exit(0);
}
#else // LIBMESH_HAVE_EXODUS_API
int main(int argc, char** argv)
{
std::cerr << "Error: meshid requires libMesh configured with --enable-exodus" << std::endl;
}
#endif // LIBMESH_HAVE_EXODUS_API
|
// Open the mesh named in command line arguments,
// update ids of one or more of the following enties
// as perscribed on the command line:
// blocks, sidesets and nodesets
#include <iostream>
#include "libmesh_config.h"
#ifdef LIBMESH_HAVE_EXODUS_API
#include "exodusII.h"
#include "exodusII_int.h"
#include "getpot.h"
#define BLOCKS 0x4
#define SIDES 0x2
#define NODES 0x1
// Report error from NetCDF and exit
void handle_error(int error, std::string message);
// Report error in input flags and exit
void usage_error(const char *progname);
int main(int argc, char** argv)
{
GetPot cl(argc, argv);
// Command line parsing
if(!cl.search("--input"))
{
std::cerr << "No --input argument found!" << std::endl;
usage_error(argv[0]);
}
const char* meshname = cl.next("");
if(!cl.search("--oldid"))
{
std::cerr << "No --oldid argument found!" << std::endl;
usage_error(argv[0]);
}
long oldid = cl.next(0);
if(!cl.search("--newid"))
{
std::cerr << "No --newid argument found!" << std::endl;
usage_error(argv[0]);
}
long newid = cl.next(0);
unsigned char flags = 0;
if (cl.search("--nodesetonly"))
flags |= NODES;
if (cl.search("--sidesetonly"))
flags |= SIDES;
if (cl.search("--blockonly"))
flags |= BLOCKS;
// No command line flags were set, turn on NODES, SIDES, and BLOCKS
if (!flags)
flags = NODES | SIDES | BLOCKS; // ALL ON
// flags are exclusive
if (flags != NODES &&
flags != SIDES &&
flags != BLOCKS &&
flags != (NODES | SIDES | BLOCKS))
{
std::cerr << "Only one of the following options may be active [--nodesetonly | --sidesetonly | --blockonly]!" << std::endl;
usage_error(argv[0]);
}
// Processing
std::string var_name, dim_name;
int status;
int nc_id, var_id, dim_id, var_len;
size_t dim_len;
status = nc_open (meshname, NC_WRITE, &nc_id);
if (status != NC_NOERR) handle_error(status, "Error while opening file.");
for (unsigned char mask = 4; mask; mask/=2)
{
// These are char*'s #defined in exodsuII_int.h
switch (flags & mask)
{
case BLOCKS:
dim_name = DIM_NUM_EL_BLK;
var_name = VAR_ID_EL_BLK;
break;
case SIDES:
dim_name = DIM_NUM_SS;
var_name = VAR_SS_IDS;
break;
case NODES:
dim_name = DIM_NUM_NS;
var_name = VAR_NS_IDS;
break;
default:
// We don't match this flag, so go to the next mask
continue;
}
// Get the ID and length of the variable in question - stored in a dimension field
status = nc_inq_dimid (nc_id, dim_name.c_str(), &dim_id);
if (status != NC_NOERR) handle_error(status, "Error while inquiring about a dimension's ID.");
status = nc_inq_dimlen (nc_id, dim_id, &dim_len);
if (status != NC_NOERR) handle_error(status, "Error while inquiring about a dimension's length.");
// Now get the variable values themselves
std::vector<long> var_vals(dim_len);
status = nc_inq_varid (nc_id, var_name.c_str(), &var_id);
if (status != NC_NOERR) handle_error(status, "Error while inquiring about a variable's ID.");
status = nc_get_var_long (nc_id, var_id, &var_vals[0]);
if (status != NC_NOERR) handle_error(status, "Error while retrieving a variable's values.");
// Update the variable value specified on the command line
for (unsigned int i=0; i<dim_len; ++i)
if (var_vals[i] == oldid)
var_vals[i] = newid;
// Save that value back to the NetCDF database
status = nc_put_var_long (nc_id, var_id, &var_vals[0]);
if (status != NC_NOERR) handle_error(status, "Error while writing a variable's values.");
} // end for
// Write out the dataset
status = nc_close(nc_id);
return 0;
}
#else // LIBMESH_HAVE_EXODUS_API
int main(int argc, char** argv)
{
std::cerr << "Error: meshid requires libMesh configured with --enable-exodus" << std::endl;
}
#endif // LIBMESH_HAVE_EXODUS_API
void handle_error(int error, std::string message)
{
std::cout << "Error " << error << " occured while working with the netCDF API" << std::endl;
std::cout << message << std::endl;
exit(1);
}
void usage_error(const char *progname)
{
std::cout << "Usage: " << progname
<< " --input inputmesh --oldid <n> --newid <n> [--nodesetonly | --sidesetonly | --blockonly]"
<< std::endl;
exit(1);
}
|
Print slightly more information when a NetCDF error is raised.
|
Print slightly more information when a NetCDF error is raised.
git-svn-id: e88a1e38e13faf406e05cc89eca8dd613216f6c4@4803 434f946d-2f3d-0410-ba4c-cb9f52fb0dbf
|
C++
|
lgpl-2.1
|
libMesh/libmesh,jwpeterson/libmesh,hrittich/libmesh,benkirk/libmesh,hrittich/libmesh,dmcdougall/libmesh,vikramvgarg/libmesh,capitalaslash/libmesh,90jrong/libmesh,90jrong/libmesh,roystgnr/libmesh,balborian/libmesh,libMesh/libmesh,dschwen/libmesh,cahaynes/libmesh,vikramvgarg/libmesh,pbauman/libmesh,90jrong/libmesh,capitalaslash/libmesh,cahaynes/libmesh,cahaynes/libmesh,roystgnr/libmesh,vikramvgarg/libmesh,vikramvgarg/libmesh,vikramvgarg/libmesh,jwpeterson/libmesh,aeslaughter/libmesh,BalticPinguin/libmesh,dknez/libmesh,coreymbryant/libmesh,svallaghe/libmesh,hrittich/libmesh,svallaghe/libmesh,aeslaughter/libmesh,cahaynes/libmesh,dmcdougall/libmesh,dmcdougall/libmesh,libMesh/libmesh,friedmud/libmesh,libMesh/libmesh,roystgnr/libmesh,vikramvgarg/libmesh,aeslaughter/libmesh,jwpeterson/libmesh,vikramvgarg/libmesh,roystgnr/libmesh,benkirk/libmesh,balborian/libmesh,balborian/libmesh,friedmud/libmesh,coreymbryant/libmesh,pbauman/libmesh,giorgiobornia/libmesh,giorgiobornia/libmesh,friedmud/libmesh,giorgiobornia/libmesh,pbauman/libmesh,balborian/libmesh,benkirk/libmesh,roystgnr/libmesh,benkirk/libmesh,90jrong/libmesh,friedmud/libmesh,pbauman/libmesh,balborian/libmesh,giorgiobornia/libmesh,coreymbryant/libmesh,BalticPinguin/libmesh,BalticPinguin/libmesh,friedmud/libmesh,friedmud/libmesh,dschwen/libmesh,90jrong/libmesh,capitalaslash/libmesh,svallaghe/libmesh,90jrong/libmesh,dmcdougall/libmesh,svallaghe/libmesh,jwpeterson/libmesh,pbauman/libmesh,svallaghe/libmesh,vikramvgarg/libmesh,giorgiobornia/libmesh,svallaghe/libmesh,giorgiobornia/libmesh,roystgnr/libmesh,pbauman/libmesh,libMesh/libmesh,pbauman/libmesh,balborian/libmesh,vikramvgarg/libmesh,dmcdougall/libmesh,hrittich/libmesh,coreymbryant/libmesh,BalticPinguin/libmesh,dmcdougall/libmesh,benkirk/libmesh,jwpeterson/libmesh,balborian/libmesh,benkirk/libmesh,balborian/libmesh,dschwen/libmesh,capitalaslash/libmesh,dknez/libmesh,roystgnr/libmesh,coreymbryant/libmesh,capitalaslash/libmesh,dschwen/libmesh,capitalaslash/libmesh,hrittich/libmesh,BalticPinguin/libmesh,aeslaughter/libmesh,90jrong/libmesh,dmcdougall/libmesh,friedmud/libmesh,BalticPinguin/libmesh,libMesh/libmesh,coreymbryant/libmesh,aeslaughter/libmesh,dknez/libmesh,dknez/libmesh,hrittich/libmesh,BalticPinguin/libmesh,giorgiobornia/libmesh,cahaynes/libmesh,90jrong/libmesh,cahaynes/libmesh,dknez/libmesh,hrittich/libmesh,aeslaughter/libmesh,BalticPinguin/libmesh,benkirk/libmesh,pbauman/libmesh,dknez/libmesh,hrittich/libmesh,balborian/libmesh,coreymbryant/libmesh,svallaghe/libmesh,coreymbryant/libmesh,dschwen/libmesh,capitalaslash/libmesh,cahaynes/libmesh,balborian/libmesh,dmcdougall/libmesh,dschwen/libmesh,benkirk/libmesh,jwpeterson/libmesh,roystgnr/libmesh,pbauman/libmesh,aeslaughter/libmesh,dschwen/libmesh,giorgiobornia/libmesh,capitalaslash/libmesh,dknez/libmesh,svallaghe/libmesh,dschwen/libmesh,jwpeterson/libmesh,friedmud/libmesh,giorgiobornia/libmesh,cahaynes/libmesh,friedmud/libmesh,aeslaughter/libmesh,hrittich/libmesh,libMesh/libmesh,svallaghe/libmesh,libMesh/libmesh,jwpeterson/libmesh,90jrong/libmesh,aeslaughter/libmesh,benkirk/libmesh,dknez/libmesh
|
9924680b3474fbf1cb289969ff44d94d4b494101
|
src/sparql/drivers/tracker_direct/qsparql_tracker_direct_driver_p.cpp
|
src/sparql/drivers/tracker_direct/qsparql_tracker_direct_driver_p.cpp
|
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsparql_tracker_direct_driver_p.h"
#include "qsparql_tracker_direct_result_p.h"
#include "qsparql_tracker_direct_sync_result_p.h"
#include "qsparql_tracker_direct_update_result_p.h"
#include <qsparqlconnection.h>
#include <QtCore/qdatetime.h>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qeventloop.h>
#include <QtCore/qdebug.h>
QT_BEGIN_NAMESPACE
// Helper functions used both by QTrackerDirectResult and
// QTrackerDirectSyncResult
namespace {
QVariant makeVariant(TrackerSparqlValueType type, TrackerSparqlCursor* cursor, int col)
{
glong strLen = 0;
const gchar* strData = 0;
// Get string data for types returned as strings from tracker
switch (type) {
case TRACKER_SPARQL_VALUE_TYPE_URI:
case TRACKER_SPARQL_VALUE_TYPE_STRING:
case TRACKER_SPARQL_VALUE_TYPE_DATETIME:
strData = tracker_sparql_cursor_get_string(cursor, col, &strLen);
break;
default:
break;
}
switch (type) {
case TRACKER_SPARQL_VALUE_TYPE_UNBOUND:
break;
case TRACKER_SPARQL_VALUE_TYPE_URI:
{
const QByteArray ba(strData, strLen);
return QVariant(QUrl::fromEncoded(ba));
}
case TRACKER_SPARQL_VALUE_TYPE_STRING:
{
return QVariant(QString::fromUtf8(strData, strLen));
}
case TRACKER_SPARQL_VALUE_TYPE_INTEGER:
{
const gint64 value = tracker_sparql_cursor_get_integer(cursor, col);
return QVariant(qlonglong(value));
}
case TRACKER_SPARQL_VALUE_TYPE_DOUBLE:
{
const gdouble value = tracker_sparql_cursor_get_double(cursor, col);
return QVariant(double(value));
}
case TRACKER_SPARQL_VALUE_TYPE_DATETIME:
{
return QVariant(QDateTime::fromString(QString::fromUtf8(strData, strLen), Qt::ISODate));
}
case TRACKER_SPARQL_VALUE_TYPE_BLANK_NODE:
// Note: this type is not currently used by Tracker. Here we're storing
// it as a null QVariant and losing information that it was a blank
// node. If Tracker starts using this type, a possible solution would
// be to store the blank node label into a QVariant along with some type
// information indicating that it was a blank node, and utilizing that
// information in binding().
break;
case TRACKER_SPARQL_VALUE_TYPE_BOOLEAN:
{
const gboolean value = tracker_sparql_cursor_get_boolean(cursor, col);
return QVariant(value != FALSE);
}
default:
break;
}
return QVariant();
}
} // namespace
QVariant readVariant(TrackerSparqlCursor* cursor, int col)
{
const TrackerSparqlValueType type =
tracker_sparql_cursor_get_value_type(cursor, col);
return makeVariant(type, cursor, col);
}
QSparqlError::ErrorType errorCodeToType(gint code)
{
switch (static_cast<TrackerSparqlError>(code)) {
case TRACKER_SPARQL_ERROR_PARSE:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_UNKNOWN_CLASS:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_UNKNOWN_PROPERTY:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_TYPE:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_CONSTRAINT:
return QSparqlError::ConnectionError;
case TRACKER_SPARQL_ERROR_NO_SPACE:
return QSparqlError::BackendError;
case TRACKER_SPARQL_ERROR_INTERNAL:
return QSparqlError::BackendError;
case TRACKER_SPARQL_ERROR_UNSUPPORTED:
return QSparqlError::BackendError;
default:
return QSparqlError::BackendError;
}
}
////////////////////////////////////////////////////////////////////////////
static void
async_open_callback(GObject * /*source_object*/,
GAsyncResult *result,
gpointer user_data)
{
QTrackerDirectDriverPrivate *d = static_cast<QTrackerDirectDriverPrivate*>(user_data);
GError * error = 0;
d->connection = tracker_sparql_connection_get_finish(result, &error);
if (!d->connection) {
d->error = QString::fromUtf8("Couldn't obtain a direct connection to the Tracker store: %1")
.arg(QString::fromUtf8(error ? error->message : "unknown error"));
qWarning() << d->error;
g_error_free(error);
d->setOpen(false);
}
d->asyncOpenCalled = true;
d->opened();
}
QTrackerDirectDriverPrivate::QTrackerDirectDriverPrivate(QTrackerDirectDriver *driver)
: connection(0), dataReadyInterval(1), connectionMutex(QMutex::Recursive), driver(driver),
asyncOpenCalled(false)
{
}
QTrackerDirectDriverPrivate::~QTrackerDirectDriverPrivate()
{
}
void QTrackerDirectDriverPrivate::setOpen(bool open)
{
driver->setOpen(open);
}
void QTrackerDirectDriverPrivate::opened()
{
Q_EMIT driver->opened();
}
void QTrackerDirectDriverPrivate::addActiveResult(QTrackerDirectResult* result)
{
for (QList<QPointer<QTrackerDirectResult> >::iterator it = activeResults.begin();
it != activeResults.end(); ++it) {
if (it->isNull()) {
// Replace entry for deleted result if one is found. This is done
// to avoid the activeResults list from growing indefinitely.
*it = result;
return;
}
}
// No deleted result found, append new one
activeResults.append(result);
}
QTrackerDirectDriver::QTrackerDirectDriver(QObject* parent)
: QSparqlDriver(parent)
{
d = new QTrackerDirectDriverPrivate(this);
/* Initialize GLib type system */
g_type_init();
}
QTrackerDirectDriver::~QTrackerDirectDriver()
{
delete d;
}
bool QTrackerDirectDriver::hasFeature(QSparqlConnection::Feature f) const
{
switch (f) {
case QSparqlConnection::QuerySize:
case QSparqlConnection::AskQueries:
case QSparqlConnection::UpdateQueries:
case QSparqlConnection::DefaultGraph:
case QSparqlConnection::SyncExec:
return true;
case QSparqlConnection::ConstructQueries:
case QSparqlConnection::AsyncExec:
return false;
default:
return false;
}
return false;
}
bool QTrackerDirectDriver::open(const QSparqlConnectionOptions& options)
{
QMutexLocker connectionLocker(&(d->connectionMutex));
d->dataReadyInterval = options.dataReadyInterval();
if (isOpen())
close();
tracker_sparql_connection_get_async(0, async_open_callback, static_cast<gpointer>(d));
setOpen(true);
setOpenError(false);
//Get the options for the thread pool, if no expiry time has been set
//set our own value of 2 seconds (the default value is 30 seconds)
if(options.threadExpiryTime() != -1)
d->threadPool.setExpiryTimeout(options.threadExpiryTime());
else
d->threadPool.setExpiryTimeout(2000);
if(options.maxThreadCount() != -1)
d->threadPool.setMaxThreadCount(options.maxThreadCount());
return true;
}
void QTrackerDirectDriver::close()
{
Q_FOREACH(QPointer<QTrackerDirectResult> result, d->activeResults) {
if (!result.isNull()) {
qWarning() << "QSparqlConnection closed before QSparqlResult with query:" <<
result->query();
disconnect(this, SIGNAL(opened()), result.data(), SLOT(exec()));
result->stopAndWait();
}
}
d->activeResults.clear();
QMutexLocker connectionLocker(&(d->connectionMutex));
if (!d->asyncOpenCalled && QCoreApplication::instance()) {
QEventLoop loop;
connect(this, SIGNAL(opened()), &loop, SLOT(quit()));
loop.exec();
}
if (d->connection) {
g_object_unref(d->connection);
d->connection = 0;
}
if (isOpen()) {
setOpen(false);
setOpenError(false);
}
}
QSparqlResult* QTrackerDirectDriver::exec(const QString &query, QSparqlQuery::StatementType type)
{
if (type == QSparqlQuery::AskStatement || type == QSparqlQuery::SelectStatement) {
QTrackerDirectResult *result = new QTrackerDirectResult(d, query, type);
d->addActiveResult(result);
if (d->asyncOpenCalled) {
result->exec();
} else {
connect(this, SIGNAL(opened()), result, SLOT(exec()));
}
return result;
} else {
QTrackerDirectUpdateResult *result = new QTrackerDirectUpdateResult(d, query, type);
if (d->asyncOpenCalled) {
result->exec();
} else {
connect(this, SIGNAL(opened()), result, SLOT(exec()));
}
return result;
}
}
QSparqlResult* QTrackerDirectDriver::syncExec(const QString& query, QSparqlQuery::StatementType type)
{
QTrackerDirectSyncResult* result = new QTrackerDirectSyncResult(d);
result->setQuery(query);
result->setStatementType(type);
if (type == QSparqlQuery::AskStatement || type == QSparqlQuery::SelectStatement) {
if (d->asyncOpenCalled) {
result->exec();
} else {
QEventLoop loop;
connect(this, SIGNAL(opened()), result, SLOT(exec()));
connect(this, SIGNAL(opened()), &loop, SLOT(quit()));
loop.exec();
}
} else if (type == QSparqlQuery::InsertStatement || type == QSparqlQuery::DeleteStatement) {
if (d->asyncOpenCalled) {
result->update();
} else {
QEventLoop loop;
connect(this, SIGNAL(opened()), result, SLOT(update()));
connect(this, SIGNAL(opened()), &loop, SLOT(quit()));
loop.exec();
}
}
return result;
}
QT_END_NAMESPACE
|
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsparql_tracker_direct_driver_p.h"
#include "qsparql_tracker_direct_result_p.h"
#include "qsparql_tracker_direct_sync_result_p.h"
#include "qsparql_tracker_direct_update_result_p.h"
#include <qsparqlconnection.h>
#include <QtCore/qdatetime.h>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qeventloop.h>
#include <QtCore/qdebug.h>
QT_BEGIN_NAMESPACE
// Helper functions used both by QTrackerDirectResult and
// QTrackerDirectSyncResult
namespace {
QVariant makeVariant(TrackerSparqlValueType type, TrackerSparqlCursor* cursor, int col)
{
glong strLen = 0;
const gchar* strData = 0;
// Get string data for types returned as strings from tracker
switch (type) {
case TRACKER_SPARQL_VALUE_TYPE_URI:
case TRACKER_SPARQL_VALUE_TYPE_STRING:
case TRACKER_SPARQL_VALUE_TYPE_DATETIME:
strData = tracker_sparql_cursor_get_string(cursor, col, &strLen);
break;
default:
break;
}
switch (type) {
case TRACKER_SPARQL_VALUE_TYPE_UNBOUND:
break;
case TRACKER_SPARQL_VALUE_TYPE_URI:
{
const QByteArray ba(strData, strLen);
return QVariant(QUrl::fromEncoded(ba));
}
case TRACKER_SPARQL_VALUE_TYPE_STRING:
{
return QVariant(QString::fromUtf8(strData, strLen));
}
case TRACKER_SPARQL_VALUE_TYPE_INTEGER:
{
const gint64 value = tracker_sparql_cursor_get_integer(cursor, col);
return QVariant(qlonglong(value));
}
case TRACKER_SPARQL_VALUE_TYPE_DOUBLE:
{
const gdouble value = tracker_sparql_cursor_get_double(cursor, col);
return QVariant(double(value));
}
case TRACKER_SPARQL_VALUE_TYPE_DATETIME:
{
return QVariant(QDateTime::fromString(QString::fromUtf8(strData, strLen), Qt::ISODate));
}
case TRACKER_SPARQL_VALUE_TYPE_BLANK_NODE:
// Note: this type is not currently used by Tracker. Here we're storing
// it as a null QVariant and losing information that it was a blank
// node. If Tracker starts using this type, a possible solution would
// be to store the blank node label into a QVariant along with some type
// information indicating that it was a blank node, and utilizing that
// information in binding().
break;
case TRACKER_SPARQL_VALUE_TYPE_BOOLEAN:
{
const gboolean value = tracker_sparql_cursor_get_boolean(cursor, col);
return QVariant(value != FALSE);
}
default:
break;
}
return QVariant();
}
} // namespace
QVariant readVariant(TrackerSparqlCursor* cursor, int col)
{
const TrackerSparqlValueType type =
tracker_sparql_cursor_get_value_type(cursor, col);
return makeVariant(type, cursor, col);
}
QSparqlError::ErrorType errorCodeToType(gint code)
{
switch (static_cast<TrackerSparqlError>(code)) {
case TRACKER_SPARQL_ERROR_PARSE:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_UNKNOWN_CLASS:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_UNKNOWN_PROPERTY:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_TYPE:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_CONSTRAINT:
return QSparqlError::ConnectionError;
case TRACKER_SPARQL_ERROR_NO_SPACE:
return QSparqlError::BackendError;
case TRACKER_SPARQL_ERROR_INTERNAL:
return QSparqlError::BackendError;
case TRACKER_SPARQL_ERROR_UNSUPPORTED:
return QSparqlError::BackendError;
default:
return QSparqlError::BackendError;
}
}
////////////////////////////////////////////////////////////////////////////
static void
async_open_callback(GObject * /*source_object*/,
GAsyncResult *result,
gpointer user_data)
{
QTrackerDirectDriverPrivate *d = static_cast<QTrackerDirectDriverPrivate*>(user_data);
GError * error = 0;
d->connection = tracker_sparql_connection_get_finish(result, &error);
if (!d->connection) {
d->error = QString::fromUtf8("Couldn't obtain a direct connection to the Tracker store: %1")
.arg(QString::fromUtf8(error ? error->message : "unknown error"));
qWarning() << d->error;
g_error_free(error);
d->setOpen(false);
}
d->asyncOpenCalled = true;
d->opened();
}
QTrackerDirectDriverPrivate::QTrackerDirectDriverPrivate(QTrackerDirectDriver *driver)
: connection(0), dataReadyInterval(1), connectionMutex(QMutex::Recursive), driver(driver),
asyncOpenCalled(false)
{
}
QTrackerDirectDriverPrivate::~QTrackerDirectDriverPrivate()
{
}
void QTrackerDirectDriverPrivate::setOpen(bool open)
{
driver->setOpen(open);
}
void QTrackerDirectDriverPrivate::opened()
{
Q_EMIT driver->opened();
}
void QTrackerDirectDriverPrivate::addActiveResult(QTrackerDirectResult* result)
{
for (QList<QPointer<QTrackerDirectResult> >::iterator it = activeResults.begin();
it != activeResults.end(); ++it) {
if (it->isNull()) {
// Replace entry for deleted result if one is found. This is done
// to avoid the activeResults list from growing indefinitely.
*it = result;
return;
}
}
// No deleted result found, append new one
activeResults.append(result);
}
QTrackerDirectDriver::QTrackerDirectDriver(QObject* parent)
: QSparqlDriver(parent)
{
d = new QTrackerDirectDriverPrivate(this);
/* Initialize GLib type system */
g_type_init();
}
QTrackerDirectDriver::~QTrackerDirectDriver()
{
delete d;
}
bool QTrackerDirectDriver::hasFeature(QSparqlConnection::Feature f) const
{
switch (f) {
case QSparqlConnection::QuerySize:
case QSparqlConnection::AskQueries:
case QSparqlConnection::UpdateQueries:
case QSparqlConnection::DefaultGraph:
case QSparqlConnection::SyncExec:
return true;
case QSparqlConnection::ConstructQueries:
case QSparqlConnection::AsyncExec:
return false;
default:
return false;
}
return false;
}
bool QTrackerDirectDriver::open(const QSparqlConnectionOptions& options)
{
QMutexLocker connectionLocker(&(d->connectionMutex));
d->dataReadyInterval = options.dataReadyInterval();
if (isOpen())
close();
tracker_sparql_connection_get_async(0, async_open_callback, static_cast<gpointer>(d));
setOpen(true);
setOpenError(false);
//Get the options for the thread pool, if no expiry time has been set
//set our own value of 2 seconds (the default value is 30 seconds)
if(options.threadExpiryTime() != -1)
d->threadPool.setExpiryTimeout(options.threadExpiryTime());
else
d->threadPool.setExpiryTimeout(2000);
//get the max thread count from an option if it was set, else
//we'll set it to 2 * the qt default of number of cores
if(options.maxThreadCount() != -1)
d->threadPool.setMaxThreadCount(options.maxThreadCount());
else {
int maxThreads = d->threadPool.maxThreadCount() * 2;
d->threadPool.setMaxThreadCount(maxThreads);
}
return true;
}
void QTrackerDirectDriver::close()
{
Q_FOREACH(QPointer<QTrackerDirectResult> result, d->activeResults) {
if (!result.isNull()) {
qWarning() << "QSparqlConnection closed before QSparqlResult with query:" <<
result->query();
disconnect(this, SIGNAL(opened()), result.data(), SLOT(exec()));
result->stopAndWait();
}
}
d->activeResults.clear();
QMutexLocker connectionLocker(&(d->connectionMutex));
if (!d->asyncOpenCalled && QCoreApplication::instance()) {
QEventLoop loop;
connect(this, SIGNAL(opened()), &loop, SLOT(quit()));
loop.exec();
}
if (d->connection) {
g_object_unref(d->connection);
d->connection = 0;
}
if (isOpen()) {
setOpen(false);
setOpenError(false);
}
}
QSparqlResult* QTrackerDirectDriver::exec(const QString &query, QSparqlQuery::StatementType type)
{
if (type == QSparqlQuery::AskStatement || type == QSparqlQuery::SelectStatement) {
QTrackerDirectResult *result = new QTrackerDirectResult(d, query, type);
d->addActiveResult(result);
if (d->asyncOpenCalled) {
result->exec();
} else {
connect(this, SIGNAL(opened()), result, SLOT(exec()));
}
return result;
} else {
QTrackerDirectUpdateResult *result = new QTrackerDirectUpdateResult(d, query, type);
if (d->asyncOpenCalled) {
result->exec();
} else {
connect(this, SIGNAL(opened()), result, SLOT(exec()));
}
return result;
}
}
QSparqlResult* QTrackerDirectDriver::syncExec(const QString& query, QSparqlQuery::StatementType type)
{
QTrackerDirectSyncResult* result = new QTrackerDirectSyncResult(d);
result->setQuery(query);
result->setStatementType(type);
if (type == QSparqlQuery::AskStatement || type == QSparqlQuery::SelectStatement) {
if (d->asyncOpenCalled) {
result->exec();
} else {
QEventLoop loop;
connect(this, SIGNAL(opened()), result, SLOT(exec()));
connect(this, SIGNAL(opened()), &loop, SLOT(quit()));
loop.exec();
}
} else if (type == QSparqlQuery::InsertStatement || type == QSparqlQuery::DeleteStatement) {
if (d->asyncOpenCalled) {
result->update();
} else {
QEventLoop loop;
connect(this, SIGNAL(opened()), result, SLOT(update()));
connect(this, SIGNAL(opened()), &loop, SLOT(quit()));
loop.exec();
}
}
return result;
}
QT_END_NAMESPACE
|
Set the default number of threads for the thread pool to num cores * 2
|
Set the default number of threads for the thread pool to num cores * 2
|
C++
|
lgpl-2.1
|
vranki/libqtsparql,vranki/libqtsparql,vranki/libqtsparql,vranki/libqtsparql
|
ff4eaa52340ab666c0fb5f8b2476aaf855422a96
|
utests/runtime_compile_link.cpp
|
utests/runtime_compile_link.cpp
|
#include <cstdint>
#include <cstring>
#include <iostream>
#include "utest_helper.hpp"
#include "utest_file_map.hpp"
#define BUFFERSIZE 32*1024
int init_program(const char* name, cl_context ctx, cl_program *pg )
{
cl_int err;
char* ker_path = cl_do_kiss_path(name, device);
cl_file_map_t *fm = cl_file_map_new();
err = cl_file_map_open(fm, ker_path);
if(err != CL_FILE_MAP_SUCCESS)
OCL_ASSERT(0);
const char *src = cl_file_map_begin(fm);
*pg = clCreateProgramWithSource(ctx, 1, &src, NULL, &err);
free(ker_path);
cl_file_map_delete(fm);
return 0;
}
void runtime_compile_link(void)
{
cl_int err;
const char* header_file_name="runtime_compile_link.h";
cl_program foo_pg;
init_program(header_file_name, ctx, &foo_pg);
const char* myinc_file_name="include/runtime_compile_link_inc.h";
cl_program myinc_pg;
init_program(myinc_file_name, ctx, &myinc_pg);
const char* file_name_A="runtime_compile_link_a.cl";
cl_program program_A;
init_program(file_name_A, ctx, &program_A);
cl_program input_headers[2] = { foo_pg, myinc_pg};
const char * input_header_names[2] = {header_file_name, myinc_file_name};
err = clCompileProgram(program_A,
0, NULL, // num_devices & device_list
NULL, // compile_options
2, // num_input_headers
input_headers,
input_header_names,
NULL, NULL);
OCL_ASSERT(err==CL_SUCCESS);
const char* file_name_B="runtime_compile_link_b.cl";
cl_program program_B;
init_program(file_name_B, ctx, &program_B);
err = clCompileProgram(program_B,
0, NULL, // num_devices & device_list
NULL, // compile_options
2, // num_input_headers
input_headers,
input_header_names,
NULL, NULL);
OCL_ASSERT(err==CL_SUCCESS);
cl_program input_programs[2] = { program_A, program_B};
cl_program linked_program = clLinkProgram(ctx, 0, NULL, NULL, 2, input_programs, NULL, NULL, &err);
OCL_ASSERT(linked_program != NULL);
OCL_ASSERT(err == CL_SUCCESS);
// link success, run this kernel.
const size_t n = 16;
int64_t src1[n], src2[n];
src1[0] = (int64_t)1 << 63, src2[0] = 0x7FFFFFFFFFFFFFFFll;
src1[1] = (int64_t)1 << 63, src2[1] = ((int64_t)1 << 63) | 1;
src1[2] = -1ll, src2[2] = 0;
src1[3] = ((int64_t)123 << 32) | 0x7FFFFFFF, src2[3] = ((int64_t)123 << 32) | 0x80000000;
src1[4] = 0x7FFFFFFFFFFFFFFFll, src2[4] = (int64_t)1 << 63;
src1[5] = ((int64_t)1 << 63) | 1, src2[5] = (int64_t)1 << 63;
src1[6] = 0, src2[6] = -1ll;
src1[7] = ((int64_t)123 << 32) | 0x80000000, src2[7] = ((int64_t)123 << 32) | 0x7FFFFFFF;
for(size_t i=8; i<n; i++) {
src1[i] = i;
src2[i] = i;
}
globals[0] = n;
locals[0] = 16;
OCL_CREATE_BUFFER(buf[0], 0, n * sizeof(int64_t), NULL);
OCL_CREATE_BUFFER(buf[1], 0, n * sizeof(int64_t), NULL);
OCL_CREATE_BUFFER(buf[2], 0, n * sizeof(int64_t), NULL);
OCL_MAP_BUFFER(0);
OCL_MAP_BUFFER(1);
memcpy(buf_data[0], src1, sizeof(src1));
memcpy(buf_data[1], src2, sizeof(src2));
OCL_UNMAP_BUFFER(0);
OCL_UNMAP_BUFFER(1);
kernel = clCreateKernel(linked_program, "runtime_compile_link_a", &err);
OCL_ASSERT(err == CL_SUCCESS);
OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]);
OCL_SET_ARG(1, sizeof(cl_mem), &buf[1]);
OCL_SET_ARG(2, sizeof(cl_mem), &buf[2]);
clEnqueueNDRangeKernel(queue, kernel, 1, NULL, globals, locals, 0, NULL, NULL);
OCL_MAP_BUFFER(2);
for (int32_t i = 0; i < (int32_t) n; ++i) {
int64_t *dest = (int64_t *)buf_data[2];
int64_t x = (src1[i] < src2[i]) ? 3 : 4;
OCL_ASSERT(x == dest[i]);
}
OCL_UNMAP_BUFFER(2);
OCL_DESTROY_KERNEL_KEEP_PROGRAM(true);
}
MAKE_UTEST_FROM_FUNCTION(runtime_compile_link);
|
#include <cstdint>
#include <cstring>
#include <iostream>
#include "utest_helper.hpp"
#include "utest_file_map.hpp"
#define BUFFERSIZE 32*1024
int init_program(const char* name, cl_context ctx, cl_program *pg )
{
cl_int err;
char* ker_path = cl_do_kiss_path(name, device);
cl_file_map_t *fm = cl_file_map_new();
err = cl_file_map_open(fm, ker_path);
if(err != CL_FILE_MAP_SUCCESS)
OCL_ASSERT(0);
const char *src = cl_file_map_begin(fm);
*pg = clCreateProgramWithSource(ctx, 1, &src, NULL, &err);
free(ker_path);
cl_file_map_delete(fm);
return 0;
}
void runtime_compile_link(void)
{
cl_int err;
const char* header_file_name="runtime_compile_link.h";
cl_program foo_pg;
init_program(header_file_name, ctx, &foo_pg);
const char* myinc_file_name="include/runtime_compile_link_inc.h";
cl_program myinc_pg;
init_program(myinc_file_name, ctx, &myinc_pg);
const char* file_name_A="runtime_compile_link_a.cl";
cl_program program_A;
init_program(file_name_A, ctx, &program_A);
cl_program input_headers[2] = { foo_pg, myinc_pg};
const char * input_header_names[2] = {header_file_name, myinc_file_name};
err = clCompileProgram(program_A,
0, NULL, // num_devices & device_list
NULL, // compile_options
2, // num_input_headers
input_headers,
input_header_names,
NULL, NULL);
OCL_ASSERT(err==CL_SUCCESS);
const char* file_name_B="runtime_compile_link_b.cl";
cl_program program_B;
init_program(file_name_B, ctx, &program_B);
err = clCompileProgram(program_B,
0, NULL, // num_devices & device_list
NULL, // compile_options
2, // num_input_headers
input_headers,
input_header_names,
NULL, NULL);
OCL_ASSERT(err==CL_SUCCESS);
cl_program input_programs[2] = { program_A, program_B};
cl_program linked_program = clLinkProgram(ctx, 0, NULL, "-create-library", 2, input_programs, NULL, NULL, &err);
OCL_ASSERT(linked_program != NULL);
OCL_ASSERT(err == CL_SUCCESS);
size_t binarySize;
unsigned char *binary;
// Get the size of the resulting binary (only one device)
err= clGetProgramInfo( linked_program, CL_PROGRAM_BINARY_SIZES, sizeof( binarySize ), &binarySize, NULL );
OCL_ASSERT(err==CL_SUCCESS);
// Create a buffer and get the actual binary
binary = (unsigned char*)malloc(sizeof(unsigned char)*binarySize);
if (binary == NULL) {
OCL_ASSERT(0);
return ;
}
unsigned char *buffers[ 1 ] = { binary };
// Do another sanity check here first
size_t size;
cl_int loadErrors[ 1 ];
err = clGetProgramInfo( linked_program, CL_PROGRAM_BINARIES, 0, NULL, &size );
OCL_ASSERT(err==CL_SUCCESS);
if( size != sizeof( buffers ) ){
free(binary);
return ;
}
err = clGetProgramInfo( linked_program, CL_PROGRAM_BINARIES, sizeof( buffers ), &buffers, NULL );
OCL_ASSERT(err==CL_SUCCESS);
cl_device_id deviceID;
err = clGetProgramInfo( linked_program, CL_PROGRAM_DEVICES, sizeof( deviceID), &deviceID, NULL );
OCL_ASSERT(err==CL_SUCCESS);
cl_program program_with_binary = clCreateProgramWithBinary(ctx, 1, &deviceID, &binarySize, (const unsigned char**)buffers, loadErrors, &err);
OCL_ASSERT(err==CL_SUCCESS);
cl_program new_linked_program = clLinkProgram(ctx, 1, &deviceID, NULL, 1, &program_with_binary, NULL, NULL, &err);
OCL_ASSERT(err==CL_SUCCESS);
// link success, run this kernel.
const size_t n = 16;
int64_t src1[n], src2[n];
src1[0] = (int64_t)1 << 63, src2[0] = 0x7FFFFFFFFFFFFFFFll;
src1[1] = (int64_t)1 << 63, src2[1] = ((int64_t)1 << 63) | 1;
src1[2] = -1ll, src2[2] = 0;
src1[3] = ((int64_t)123 << 32) | 0x7FFFFFFF, src2[3] = ((int64_t)123 << 32) | 0x80000000;
src1[4] = 0x7FFFFFFFFFFFFFFFll, src2[4] = (int64_t)1 << 63;
src1[5] = ((int64_t)1 << 63) | 1, src2[5] = (int64_t)1 << 63;
src1[6] = 0, src2[6] = -1ll;
src1[7] = ((int64_t)123 << 32) | 0x80000000, src2[7] = ((int64_t)123 << 32) | 0x7FFFFFFF;
for(size_t i=8; i<n; i++) {
src1[i] = i;
src2[i] = i;
}
globals[0] = n;
locals[0] = 16;
OCL_CREATE_BUFFER(buf[0], 0, n * sizeof(int64_t), NULL);
OCL_CREATE_BUFFER(buf[1], 0, n * sizeof(int64_t), NULL);
OCL_CREATE_BUFFER(buf[2], 0, n * sizeof(int64_t), NULL);
OCL_MAP_BUFFER(0);
OCL_MAP_BUFFER(1);
memcpy(buf_data[0], src1, sizeof(src1));
memcpy(buf_data[1], src2, sizeof(src2));
OCL_UNMAP_BUFFER(0);
OCL_UNMAP_BUFFER(1);
kernel = clCreateKernel(new_linked_program, "runtime_compile_link_a", &err);
OCL_ASSERT(err == CL_SUCCESS);
OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]);
OCL_SET_ARG(1, sizeof(cl_mem), &buf[1]);
OCL_SET_ARG(2, sizeof(cl_mem), &buf[2]);
clEnqueueNDRangeKernel(queue, kernel, 1, NULL, globals, locals, 0, NULL, NULL);
OCL_MAP_BUFFER(2);
for (int32_t i = 0; i < (int32_t) n; ++i) {
int64_t *dest = (int64_t *)buf_data[2];
int64_t x = (src1[i] < src2[i]) ? 3 : 4;
OCL_ASSERT(x == dest[i]);
}
OCL_UNMAP_BUFFER(2);
OCL_DESTROY_KERNEL_KEEP_PROGRAM(true);
}
MAKE_UTEST_FROM_FUNCTION(runtime_compile_link);
|
add the usage of link program from llvm binary.
|
add the usage of link program from llvm binary.
user A could compile and link kernel source to llvm binary first, then
query the binary to save to file; With the binary, user B can call
clCreateProgramWithBinary without compile the source again.
this usage could protect those who need to protect the kernel source.
Signed-off-by: Luo <[email protected]>
Reviewed-by: Zhigang Gong <[email protected]>
|
C++
|
lgpl-2.1
|
zhenyw/beignet,wdv4758h/beignet,wdv4758h/beignet,freedesktop-unofficial-mirror/beignet,zhenyw/beignet,freedesktop-unofficial-mirror/beignet,wdv4758h/beignet,wdv4758h/beignet,freedesktop-unofficial-mirror/beignet,freedesktop-unofficial-mirror/beignet,zhenyw/beignet,wdv4758h/beignet,zhenyw/beignet,zhenyw/beignet
|
bc5535bec7ec132c305cccf428e311d1318c5900
|
src/openMVG/sfm/pipelines/sequential/sequential_SfM_test.cpp
|
src/openMVG/sfm/pipelines/sequential/sequential_SfM_test.cpp
|
// Copyright (c) 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//-----------------
// Test summary:
//-----------------
// - Create features points and matching from the synthetic dataset
// - Init a SfM_Data scene VIew and Intrinsic from a synthetic dataset
// - Perform Sequential SfM on the data
// - Assert that:
// - mean residual error is below the gaussian noise added to observation
// - the desired number of tracks are found,
// - the desired number of poses are found.
//-----------------
#include "openMVG/sfm/pipelines/pipelines_test.hpp"
#include "openMVG/sfm/sfm.hpp"
using namespace openMVG;
using namespace openMVG::cameras;
using namespace openMVG::geometry;
using namespace openMVG::sfm;
#include "testing/testing.h"
#include <cmath>
#include <cstdio>
#include <iostream>
// Test a scene where all the camera intrinsics are known
TEST(SEQUENTIAL_SFM, Known_Intrinsics) {
const int nviews = 6;
const int npoints = 128;
const nViewDatasetConfigurator config;
const NViewDataSet d = NRealisticCamerasRing(nviews, npoints, config);
// Translate the input dataset to a SfM_Data scene
const SfM_Data sfm_data = getInputScene(d, config, PINHOLE_CAMERA);
// Remove poses and structure
SfM_Data sfm_data_2 = sfm_data;
sfm_data_2.poses.clear();
sfm_data_2.structure.clear();
SequentialSfMReconstructionEngine sfmEngine(
sfm_data_2,
"./",
stlplus::create_filespec("./", "Reconstruction_Report.html"));
// Configure the features_provider & the matches_provider from the synthetic dataset
std::shared_ptr<Features_Provider> feats_provider =
std::make_shared<Synthetic_Features_Provider>();
// Add a tiny noise in 2D observations to make data more realistic
std::normal_distribution<double> distribution(0.0,0.5);
dynamic_cast<Synthetic_Features_Provider*>(feats_provider.get())->load(d, distribution);
std::shared_ptr<Matches_Provider> matches_provider =
std::make_shared<Synthetic_Matches_Provider>();
dynamic_cast<Synthetic_Matches_Provider*>(matches_provider.get())->load(d);
// Configure data provider (Features and Matches)
sfmEngine.SetFeaturesProvider(feats_provider.get());
sfmEngine.SetMatchesProvider(matches_provider.get());
// Set an initial pair
sfmEngine.setInitialPair(Pair(0,1));
// Configure reconstruction parameters
sfmEngine.Set_bFixedIntrinsics(true);
EXPECT_TRUE (sfmEngine.Process());
const double dResidual = RMSE(sfmEngine.Get_SfM_Data());
std::cout << "RMSE residual: " << dResidual << std::endl;
EXPECT_TRUE( dResidual < 0.5);
EXPECT_TRUE( sfmEngine.Get_SfM_Data().GetPoses().size() == nviews);
EXPECT_TRUE( sfmEngine.Get_SfM_Data().GetLandmarks().size() == npoints);
}
// Test a scene where only the two first camera have known intrinsics
TEST(SEQUENTIAL_SFM, Partially_Known_Intrinsics) {
const int nviews = 6;
const int npoints = 256;
const nViewDatasetConfigurator config;
const NViewDataSet d = NRealisticCamerasRing(nviews, npoints, config);
// Translate the input dataset to a SfM_Data scene
const SfM_Data sfm_data = getInputScene(d, config, PINHOLE_CAMERA);
// Remove poses and structure
SfM_Data sfm_data_2 = sfm_data;
sfm_data_2.poses.clear();
sfm_data_2.structure.clear();
// Only the first two views will have valid intrinsics
// Remaining one will have undefined intrinsics
for (Views::iterator iterV = sfm_data_2.views.begin();
iterV != sfm_data_2.views.end(); ++iterV)
{
if (std::distance(sfm_data_2.views.begin(),iterV) >1)
{
iterV->second.get()->id_intrinsic = UndefinedIndexT;
}
}
SequentialSfMReconstructionEngine sfmEngine(
sfm_data_2,
"./",
stlplus::create_filespec("./", "Reconstruction_Report.html"));
// Configure the features_provider & the matches_provider from the synthetic dataset
std::shared_ptr<Features_Provider> feats_provider =
std::make_shared<Synthetic_Features_Provider>();
// Add a tiny noise in 2D observations to make data more realistic
std::normal_distribution<double> distribution(0.0,0.5);
dynamic_cast<Synthetic_Features_Provider*>(feats_provider.get())->load(d, distribution);
std::shared_ptr<Matches_Provider> matches_provider =
std::make_shared<Synthetic_Matches_Provider>();
dynamic_cast<Synthetic_Matches_Provider*>(matches_provider.get())->load(d);
// Configure data provider (Features and Matches)
sfmEngine.SetFeaturesProvider(feats_provider.get());
sfmEngine.SetMatchesProvider(matches_provider.get());
// Set an initial pair
sfmEngine.setInitialPair(Pair(0,1));
// Configure reconstruction parameters
sfmEngine.Set_bFixedIntrinsics(true);
EXPECT_TRUE (sfmEngine.Process());
const double dResidual = RMSE(sfmEngine.Get_SfM_Data());
std::cout << "RMSE residual: " << dResidual << std::endl;
EXPECT_TRUE( dResidual < 0.5);
EXPECT_TRUE( sfmEngine.Get_SfM_Data().GetPoses().size() == nviews);
EXPECT_TRUE( sfmEngine.Get_SfM_Data().GetLandmarks().size() == npoints);
}
/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr);}
/* ************************************************************************* */
|
// Copyright (c) 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//-----------------
// Test summary:
//-----------------
// - Create features points and matching from the synthetic dataset
// - Init a SfM_Data scene VIew and Intrinsic from a synthetic dataset
// - Perform Sequential SfM on the data
// - Assert that:
// - mean residual error is below the gaussian noise added to observation
// - the desired number of tracks are found,
// - the desired number of poses are found.
//-----------------
#include "openMVG/sfm/pipelines/pipelines_test.hpp"
#include "openMVG/sfm/sfm.hpp"
using namespace openMVG;
using namespace openMVG::cameras;
using namespace openMVG::geometry;
using namespace openMVG::sfm;
#include "testing/testing.h"
#include <cmath>
#include <cstdio>
#include <iostream>
// Test a scene where all the camera intrinsics are known
TEST(SEQUENTIAL_SFM, Known_Intrinsics) {
const int nviews = 6;
const int npoints = 128;
const nViewDatasetConfigurator config;
const NViewDataSet d = NRealisticCamerasRing(nviews, npoints, config);
// Translate the input dataset to a SfM_Data scene
const SfM_Data sfm_data = getInputScene(d, config, PINHOLE_CAMERA);
// Remove poses and structure
SfM_Data sfm_data_2 = sfm_data;
sfm_data_2.poses.clear();
sfm_data_2.structure.clear();
SequentialSfMReconstructionEngine sfmEngine(
sfm_data_2,
"./",
stlplus::create_filespec("./", "Reconstruction_Report.html"));
// Configure the features_provider & the matches_provider from the synthetic dataset
std::shared_ptr<Features_Provider> feats_provider =
std::make_shared<Synthetic_Features_Provider>();
// Add a tiny noise in 2D observations to make data more realistic
std::normal_distribution<double> distribution(0.0,0.5);
dynamic_cast<Synthetic_Features_Provider*>(feats_provider.get())->load(d, distribution);
std::shared_ptr<Matches_Provider> matches_provider =
std::make_shared<Synthetic_Matches_Provider>();
dynamic_cast<Synthetic_Matches_Provider*>(matches_provider.get())->load(d);
// Configure data provider (Features and Matches)
sfmEngine.SetFeaturesProvider(feats_provider.get());
sfmEngine.SetMatchesProvider(matches_provider.get());
// Set an initial pair
sfmEngine.setInitialPair(Pair(0,1));
// Configure reconstruction parameters
sfmEngine.Set_bFixedIntrinsics(true);
EXPECT_TRUE (sfmEngine.Process());
const double dResidual = RMSE(sfmEngine.Get_SfM_Data());
std::cout << "RMSE residual: " << dResidual << std::endl;
EXPECT_TRUE( dResidual < 0.5);
EXPECT_TRUE( sfmEngine.Get_SfM_Data().GetPoses().size() == nviews);
EXPECT_TRUE( sfmEngine.Get_SfM_Data().GetLandmarks().size() == npoints);
}
// Test a scene where only the two first camera have known intrinsics
TEST(SEQUENTIAL_SFM, Partially_Known_Intrinsics) {
const int nviews = 6;
const int npoints = 256;
const nViewDatasetConfigurator config;
const NViewDataSet d = NRealisticCamerasRing(nviews, npoints, config);
// Translate the input dataset to a SfM_Data scene
const SfM_Data sfm_data = getInputScene(d, config, PINHOLE_CAMERA);
// Remove poses and structure
SfM_Data sfm_data_2 = sfm_data;
sfm_data_2.poses.clear();
sfm_data_2.structure.clear();
// Only the first two views will have valid intrinsics
// Remaining one will have undefined intrinsics
for (Views::iterator iterV = sfm_data_2.views.begin();
iterV != sfm_data_2.views.end(); ++iterV)
{
if (std::distance(sfm_data_2.views.begin(),iterV) >1)
{
iterV->second.get()->id_intrinsic = UndefinedIndexT;
}
}
SequentialSfMReconstructionEngine sfmEngine(
sfm_data_2,
"./",
stlplus::create_filespec("./", "Reconstruction_Report.html"));
// Configure the features_provider & the matches_provider from the synthetic dataset
std::shared_ptr<Features_Provider> feats_provider =
std::make_shared<Synthetic_Features_Provider>();
// Add a tiny noise in 2D observations to make data more realistic
std::normal_distribution<double> distribution(0.0,0.5);
dynamic_cast<Synthetic_Features_Provider*>(feats_provider.get())->load(d, distribution);
std::shared_ptr<Matches_Provider> matches_provider =
std::make_shared<Synthetic_Matches_Provider>();
dynamic_cast<Synthetic_Matches_Provider*>(matches_provider.get())->load(d);
// Configure data provider (Features and Matches)
sfmEngine.SetFeaturesProvider(feats_provider.get());
sfmEngine.SetMatchesProvider(matches_provider.get());
// Set an initial pair
sfmEngine.setInitialPair(Pair(0,1));
// Configure reconstruction parameters
sfmEngine.Set_bFixedIntrinsics(true);
EXPECT_TRUE (sfmEngine.Process());
const double dResidual = RMSE(sfmEngine.Get_SfM_Data());
std::cout << "RMSE residual: " << dResidual << std::endl;
EXPECT_TRUE( dResidual < 0.5);
EXPECT_EQ(nviews, sfmEngine.Get_SfM_Data().GetPoses().size());
EXPECT_EQ(npoints, sfmEngine.Get_SfM_Data().GetLandmarks().size());
}
/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr);}
/* ************************************************************************* */
|
use EXPECT_EQ instead of EXPECT_TRUE
|
[unittest] use EXPECT_EQ instead of EXPECT_TRUE
|
C++
|
mit
|
poparteu/openMVG,poparteu/openMVG,poparteu/openMVG,poparteu/openMVG
|
987f4558b916a2e9f76bebaa43c325ddf3b1f82b
|
tensorflow_addons/custom_ops/text/cc/kernels/skip_gram_kernels.cc
|
tensorflow_addons/custom_ops/text/cc/kernels/skip_gram_kernels.cc
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <algorithm>
#include <string>
#include <vector>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/random/philox_random.h"
#include "tensorflow/core/lib/random/simple_philox.h"
#include "tensorflow/core/util/guarded_philox_random.h"
namespace tensorflow {
namespace addons {
template <typename T>
class SkipGramGenerateCandidatesOp : public OpKernel {
public:
explicit SkipGramGenerateCandidatesOp(OpKernelConstruction* context)
: OpKernel(context) {
OP_REQUIRES_OK(context, generator_.Init(context));
}
void Compute(OpKernelContext* context) override {
const Tensor* input_tensor;
OP_REQUIRES_OK(context, context->input("input_tensor", &input_tensor));
const auto input = input_tensor->flat<T>();
const Tensor* min_skips_tensor;
OP_REQUIRES_OK(context, context->input("min_skips", &min_skips_tensor));
const int min_skips = *(min_skips_tensor->scalar<int>().data());
const Tensor* max_skips_tensor;
OP_REQUIRES_OK(context, context->input("max_skips", &max_skips_tensor));
const int max_skips = *(max_skips_tensor->scalar<int>().data());
const Tensor& input_check = context->input(0);
OP_REQUIRES(context, TensorShapeUtils::IsVector(input_check.shape()),
errors::InvalidArgument("input_tensor must be of rank 1"));
OP_REQUIRES(
context, min_skips >= 0 && max_skips >= 0,
errors::InvalidArgument("Both min_skips and max_skips must be >= 0."));
OP_REQUIRES(context, min_skips <= max_skips,
errors::InvalidArgument("min_skips must be <= max_skips."));
const Tensor* start_tensor;
OP_REQUIRES_OK(context, context->input("start", &start_tensor));
const int start = *(start_tensor->scalar<int>().data());
const Tensor* limit_tensor;
OP_REQUIRES_OK(context, context->input("limit", &limit_tensor));
const int limit = *(limit_tensor->scalar<int>().data());
const int end =
limit < 0 ? input.size()
: std::min(start + limit, static_cast<int>(input.size()));
const Tensor* emit_self_tensor;
OP_REQUIRES_OK(context,
context->input("emit_self_as_target", &emit_self_tensor));
const bool emit_self_as_target = *(emit_self_tensor->scalar<bool>().data());
std::vector<T> tokens;
std::vector<T> labels;
// Reserve the number of random numbers we will use - we use one for each
// token between start and end.
random::PhiloxRandom local_gen =
generator_.ReserveSamples32(end - start + 1);
random::SimplePhilox rng(&local_gen);
// For each token in the sentence, pick a random skip, then generates
// (token, label) pairs for all labels whose distances from the token are
// within the range [-skip, skip].
for (int i = start; i < end; ++i) {
const int skips = min_skips + rng.Uniform(max_skips - min_skips + 1);
for (int j = -skips; j <= skips; ++j) {
if ((i + j < start) || (i + j >= end) ||
(j == 0 && !emit_self_as_target)) {
continue;
}
tokens.push_back(input(i));
labels.push_back(input(i + j));
}
}
Tensor* tokens_output = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(
"tokens", TensorShape({static_cast<int>(tokens.size())}),
&tokens_output));
Tensor* labels_output = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(
"labels", TensorShape({static_cast<int>(labels.size())}),
&labels_output));
OP_REQUIRES(
context, tokens_output->IsSameSize(*labels_output),
errors::Internal(strings::StrCat(
"Mismatch between tokens_output shape of ",
tokens_output->shape().DebugString(),
" and labels_output shape of ",
labels_output->shape().DebugString(),
". This should never happen - contact ami-team@ if it does.")));
// Copies results to output tensors.
for (int i = 0; i < tokens.size(); ++i) {
tokens_output->vec<T>()(i) = tokens[i];
labels_output->vec<T>()(i) = labels[i];
}
}
private:
GuardedPhiloxRandom generator_;
};
#define REGISTER_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("Addons>SkipGramGenerateCandidates") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T"), \
SkipGramGenerateCandidatesOp<type>)
REGISTER_KERNEL(string);
REGISTER_KERNEL(int64);
REGISTER_KERNEL(int32);
REGISTER_KERNEL(int16);
#undef REGISTER_KERNEL
} // end namespace addons
} // namespace tensorflow
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <algorithm>
#include <string>
#include <vector>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/random/philox_random.h"
#include "tensorflow/core/lib/random/simple_philox.h"
#include "tensorflow/core/util/guarded_philox_random.h"
namespace tensorflow {
namespace addons {
template <typename T>
class SkipGramGenerateCandidatesOp : public OpKernel {
public:
explicit SkipGramGenerateCandidatesOp(OpKernelConstruction* context)
: OpKernel(context) {
OP_REQUIRES_OK(context, generator_.Init(context));
}
void Compute(OpKernelContext* context) override {
const Tensor* input_tensor;
OP_REQUIRES_OK(context, context->input("input_tensor", &input_tensor));
const auto input = input_tensor->flat<T>();
const Tensor* min_skips_tensor;
OP_REQUIRES_OK(context, context->input("min_skips", &min_skips_tensor));
const int min_skips = *(min_skips_tensor->scalar<int>().data());
const Tensor* max_skips_tensor;
OP_REQUIRES_OK(context, context->input("max_skips", &max_skips_tensor));
const int max_skips = *(max_skips_tensor->scalar<int>().data());
const Tensor& input_check = context->input(0);
OP_REQUIRES(context, TensorShapeUtils::IsVector(input_check.shape()),
errors::InvalidArgument("input_tensor must be of rank 1"));
OP_REQUIRES(
context, min_skips >= 0 && max_skips >= 0,
errors::InvalidArgument("Both min_skips and max_skips must be >= 0."));
OP_REQUIRES(context, min_skips <= max_skips,
errors::InvalidArgument("min_skips must be <= max_skips."));
const Tensor* start_tensor;
OP_REQUIRES_OK(context, context->input("start", &start_tensor));
const int start = *(start_tensor->scalar<int>().data());
const Tensor* limit_tensor;
OP_REQUIRES_OK(context, context->input("limit", &limit_tensor));
const int limit = *(limit_tensor->scalar<int>().data());
const int end =
limit < 0 ? input.size()
: std::min(start + limit, static_cast<int>(input.size()));
const Tensor* emit_self_tensor;
OP_REQUIRES_OK(context,
context->input("emit_self_as_target", &emit_self_tensor));
const bool emit_self_as_target = *(emit_self_tensor->scalar<bool>().data());
std::vector<T> tokens;
std::vector<T> labels;
// Reserve the number of random numbers we will use - we use one for each
// token between start and end.
random::PhiloxRandom local_gen =
generator_.ReserveSamples32(end - start + 1);
random::SimplePhilox rng(&local_gen);
// For each token in the sentence, pick a random skip, then generates
// (token, label) pairs for all labels whose distances from the token are
// within the range [-skip, skip].
for (int i = start; i < end; ++i) {
const int skips = min_skips + rng.Uniform(max_skips - min_skips + 1);
for (int j = -skips; j <= skips; ++j) {
if ((i + j < start) || (i + j >= end) ||
(j == 0 && !emit_self_as_target)) {
continue;
}
tokens.push_back(input(i));
labels.push_back(input(i + j));
}
}
Tensor* tokens_output = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(
"tokens", TensorShape({static_cast<int>(tokens.size())}),
&tokens_output));
Tensor* labels_output = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(
"labels", TensorShape({static_cast<int>(labels.size())}),
&labels_output));
OP_REQUIRES(
context, tokens_output->IsSameSize(*labels_output),
errors::Internal(strings::StrCat(
"Mismatch between tokens_output shape of ",
tokens_output->shape().DebugString(),
" and labels_output shape of ",
labels_output->shape().DebugString(),
". This should never happen - contact ami-team@ if it does.")));
// Copies results to output tensors.
for (int i = 0; i < tokens.size(); ++i) {
tokens_output->vec<T>()(i) = tokens[i];
labels_output->vec<T>()(i) = labels[i];
}
}
private:
GuardedPhiloxRandom generator_;
};
#define REGISTER_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("Addons>SkipGramGenerateCandidates") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T"), \
SkipGramGenerateCandidatesOp<type>)
REGISTER_KERNEL(tstring);
REGISTER_KERNEL(int64);
REGISTER_KERNEL(int32);
REGISTER_KERNEL(int16);
#undef REGISTER_KERNEL
} // end namespace addons
} // namespace tensorflow
|
Migrate from std::string to tensorflow::tstring. (#705)
|
Migrate from std::string to tensorflow::tstring. (#705)
Note that during the transition period tstring is typedef'ed to
std::string.
See: https://github.com/tensorflow/community/pull/91
|
C++
|
apache-2.0
|
tensorflow/addons,tensorflow/addons,tensorflow/addons
|
61d40bdb2fc3c3270f762ed3ea4e2e4282a4e032
|
cui/source/options/optchart.cxx
|
cui/source/options/optchart.cxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <unotools/pathoptions.hxx>
#include <cuires.hrc>
#include "optchart.hxx"
#include "optchart.hrc"
#include <dialmgr.hxx>
#include <vcl/msgbox.hxx>
#include <svx/svxids.hrc> // for SID_SCH_EDITOPTIONS
// ====================
// class ChartColorLB
// ====================
void ChartColorLB::FillBox( const SvxChartColorTable & rTab )
{
long nCount = rTab.size();
SetUpdateMode( sal_False );
for( long i = 0; i < nCount; i++ )
{
Append( const_cast< XColorEntry * >( & rTab[ i ] ));
}
SetUpdateMode( sal_True );
}
// ====================
// class SvxDefaultColorOptPage
// ====================
SvxDefaultColorOptPage::SvxDefaultColorOptPage( Window* pParent, const SfxItemSet& rInAttrs ) :
SfxTabPage( pParent, CUI_RES( RID_OPTPAGE_CHART_DEFCOLORS ), rInAttrs ),
aGbChartColors ( this, CUI_RES( FL_CHART_COLOR_LIST ) ),
aLbChartColors ( this, CUI_RES( LB_CHART_COLOR_LIST ) ),
aGbColorBox ( this, CUI_RES( FL_COLOR_BOX ) ),
aValSetColorBox ( this, CUI_RES( CT_COLOR_BOX ) ),
aPBDefault ( this, CUI_RES( PB_RESET_TO_DEFAULT ) ),
aPBAdd ( this, CUI_RES( PB_ADD_CHART_COLOR ) ),
aPBRemove ( this, CUI_RES( PB_REMOVE_CHART_COLOR ) )
{
FreeResource();
aPBDefault.SetClickHdl( LINK( this, SvxDefaultColorOptPage, ResetToDefaults ) );
aPBAdd.SetClickHdl( LINK( this, SvxDefaultColorOptPage, AddChartColor ) );
aPBRemove.SetClickHdl( LINK( this, SvxDefaultColorOptPage, RemoveChartColor ) );
aLbChartColors.SetSelectHdl( LINK( this, SvxDefaultColorOptPage, ListClickedHdl ) );
aValSetColorBox.SetSelectHdl( LINK( this, SvxDefaultColorOptPage, BoxClickedHdl ) );
aValSetColorBox.SetStyle( aValSetColorBox.GetStyle()
| WB_ITEMBORDER | WB_NAMEFIELD );
aValSetColorBox.SetColCount( 8 );
aValSetColorBox.SetLineCount( 13 );
aValSetColorBox.SetExtraSpacing( 0 );
aValSetColorBox.Show();
pChartOptions = new SvxChartOptions;
pColorTab = new XColorTable( SvtPathOptions().GetPalettePath() );
const SfxPoolItem* pItem = NULL;
if ( rInAttrs.GetItemState( SID_SCH_EDITOPTIONS, sal_False, &pItem ) == SFX_ITEM_SET )
{
pColorConfig = SAL_STATIC_CAST( SvxChartColorTableItem*, pItem->Clone() );
}
else
{
SvxChartColorTable aTable;
aTable.useDefault();
pColorConfig = new SvxChartColorTableItem( SID_SCH_EDITOPTIONS, aTable );
pColorConfig->SetOptions( pChartOptions );
}
Construct();
}
SvxDefaultColorOptPage::~SvxDefaultColorOptPage()
{
// save changes
pChartOptions->SetDefaultColors( pColorConfig->GetColorTable() );
pChartOptions->Commit();
delete pColorConfig;
delete pColorTab;
delete pChartOptions;
}
void SvxDefaultColorOptPage::Construct()
{
if( pColorConfig )
aLbChartColors.FillBox( pColorConfig->GetColorTable() );
FillColorBox();
aLbChartColors.SelectEntryPos( 0 );
ListClickedHdl( &aLbChartColors );
}
SfxTabPage* SvxDefaultColorOptPage::Create( Window* pParent, const SfxItemSet& rAttrs )
{
return new SvxDefaultColorOptPage( pParent, rAttrs );
}
sal_Bool SvxDefaultColorOptPage::FillItemSet( SfxItemSet& rOutAttrs )
{
if( pColorConfig )
rOutAttrs.Put( *SAL_STATIC_CAST( SfxPoolItem*, pColorConfig ));
return sal_True;
}
void SvxDefaultColorOptPage::Reset( const SfxItemSet& )
{
aLbChartColors.SelectEntryPos( 0 );
ListClickedHdl( &aLbChartColors );
}
void SvxDefaultColorOptPage::FillColorBox()
{
if( !pColorTab ) return;
long nCount = pColorTab->Count();
XColorEntry* pColorEntry;
if( nCount > 104 )
aValSetColorBox.SetStyle( aValSetColorBox.GetStyle() | WB_VSCROLL );
for( long i = 0; i < nCount; i++ )
{
pColorEntry = pColorTab->GetColor( i );
aValSetColorBox.InsertItem( (sal_uInt16) i + 1, pColorEntry->GetColor(), pColorEntry->GetName() );
}
}
long SvxDefaultColorOptPage::GetColorIndex( const Color& rCol )
{
if( pColorTab )
{
long nCount = pColorTab->Count();
XColorEntry* pColorEntry;
for( long i = nCount - 1; i >= 0; i-- ) // default chart colors are at the end of the table
{
pColorEntry = pColorTab->GetColor( i );
if( pColorEntry && pColorEntry->GetColor() == rCol )
return SAL_STATIC_CAST( XPropertyTable*, pColorTab )->Get( pColorEntry->GetName() );
}
}
return -1L;
}
// --------------------
// event handlers
// --------------------
// ResetToDefaults
// ---------------
IMPL_LINK( SvxDefaultColorOptPage, ResetToDefaults, void *, EMPTYARG )
{
if( pColorConfig )
{
pColorConfig->GetColorTable().useDefault();
aLbChartColors.Clear();
aLbChartColors.FillBox( pColorConfig->GetColorTable() );
aLbChartColors.GetFocus();
aLbChartColors.SelectEntryPos( 0 );
}
return 0L;
}
// AddChartColor
// ------------
IMPL_LINK( SvxDefaultColorOptPage, AddChartColor, void *, EMPTYARG )
{
if( pColorConfig )
{
ColorData black = RGB_COLORDATA( 0x00, 0x00, 0x00 );
pColorConfig->GetColorTable().append (XColorEntry ( black, pColorConfig->GetColorTable().getDefaultName(pColorConfig->GetColorTable().size())));
aLbChartColors.Clear();
aLbChartColors.FillBox( pColorConfig->GetColorTable() );
aLbChartColors.GetFocus();
aLbChartColors.SelectEntryPos( pColorConfig->GetColorTable().size() - 1 );
}
return 0L;
}
// RemoveChartColor
// ----------------
IMPL_LINK( SvxDefaultColorOptPage, RemoveChartColor, PushButton*, pButton )
{
size_t nIndex = aLbChartColors.GetSelectEntryPos();
if (aLbChartColors.GetSelectEntryCount() == 0)
return 0L;
if( pColorConfig )
{
OSL_ENSURE(pColorConfig->GetColorTable().size() > 1, "don't delete the last chart color");
QueryBox aQuery(pButton, CUI_RES(RID_OPTQB_COLOR_CHART_DELETE));
aQuery.SetText(String(CUI_RES(RID_OPTSTR_COLOR_CHART_DELETE)));
if(RET_YES == aQuery.Execute())
{
pColorConfig->GetColorTable().remove( nIndex );
aLbChartColors.Clear();
aLbChartColors.FillBox( pColorConfig->GetColorTable() );
aLbChartColors.GetFocus();
if (nIndex == aLbChartColors.GetEntryCount() && aLbChartColors.GetEntryCount() > 0)
aLbChartColors.SelectEntryPos( pColorConfig->GetColorTable().size() - 1 );
else if (aLbChartColors.GetEntryCount() > 0)
aLbChartColors.SelectEntryPos( nIndex );
}
}
return 0L;
}
// ListClickedHdl
// --------------
IMPL_LINK( SvxDefaultColorOptPage, ListClickedHdl, ChartColorLB*, pColorList )
{
Color aCol = pColorList->GetSelectEntryColor();
long nIndex = GetColorIndex( aCol );
if( nIndex == -1 ) // not found
{
aValSetColorBox.SetNoSelection();
}
else
{
aValSetColorBox.SelectItem( (sal_uInt16)nIndex + 1 ); // ValueSet is 1-based
}
return 0L;
}
// BoxClickedHdl
// -------------
IMPL_LINK( SvxDefaultColorOptPage, BoxClickedHdl, ValueSet*, EMPTYARG )
{
sal_uInt16 nIdx = aLbChartColors.GetSelectEntryPos();
if( nIdx != LISTBOX_ENTRY_NOTFOUND )
{
XColorEntry aEntry( aValSetColorBox.GetItemColor( aValSetColorBox.GetSelectItemId() ),
aLbChartColors.GetSelectEntry() );
aLbChartColors.Modify( & aEntry, nIdx );
pColorConfig->ReplaceColorByIndex( nIdx, aEntry );
aLbChartColors.SelectEntryPos( nIdx ); // reselect entry
}
return 0L;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <unotools/pathoptions.hxx>
#include <cuires.hrc>
#include "optchart.hxx"
#include "optchart.hrc"
#include <dialmgr.hxx>
#include <vcl/msgbox.hxx>
#include <svx/svxids.hrc> // for SID_SCH_EDITOPTIONS
// ====================
// class ChartColorLB
// ====================
void ChartColorLB::FillBox( const SvxChartColorTable & rTab )
{
long nCount = rTab.size();
SetUpdateMode( sal_False );
for( long i = 0; i < nCount; i++ )
{
Append( const_cast< XColorEntry * >( & rTab[ i ] ));
}
SetUpdateMode( sal_True );
}
// ====================
// class SvxDefaultColorOptPage
// ====================
SvxDefaultColorOptPage::SvxDefaultColorOptPage( Window* pParent, const SfxItemSet& rInAttrs ) :
SfxTabPage( pParent, CUI_RES( RID_OPTPAGE_CHART_DEFCOLORS ), rInAttrs ),
aGbChartColors ( this, CUI_RES( FL_CHART_COLOR_LIST ) ),
aLbChartColors ( this, CUI_RES( LB_CHART_COLOR_LIST ) ),
aGbColorBox ( this, CUI_RES( FL_COLOR_BOX ) ),
aValSetColorBox ( this, CUI_RES( CT_COLOR_BOX ) ),
aPBDefault ( this, CUI_RES( PB_RESET_TO_DEFAULT ) ),
aPBAdd ( this, CUI_RES( PB_ADD_CHART_COLOR ) ),
aPBRemove ( this, CUI_RES( PB_REMOVE_CHART_COLOR ) )
{
FreeResource();
aPBDefault.SetClickHdl( LINK( this, SvxDefaultColorOptPage, ResetToDefaults ) );
aPBAdd.SetClickHdl( LINK( this, SvxDefaultColorOptPage, AddChartColor ) );
aPBRemove.SetClickHdl( LINK( this, SvxDefaultColorOptPage, RemoveChartColor ) );
aLbChartColors.SetSelectHdl( LINK( this, SvxDefaultColorOptPage, ListClickedHdl ) );
aValSetColorBox.SetSelectHdl( LINK( this, SvxDefaultColorOptPage, BoxClickedHdl ) );
aValSetColorBox.SetStyle( aValSetColorBox.GetStyle()
| WB_ITEMBORDER | WB_NAMEFIELD );
aValSetColorBox.SetColCount( 8 );
aValSetColorBox.SetLineCount( 13 );
aValSetColorBox.SetExtraSpacing( 0 );
aValSetColorBox.Show();
pChartOptions = new SvxChartOptions;
pColorTab = new XColorTable( SvtPathOptions().GetPalettePath() );
const SfxPoolItem* pItem = NULL;
if ( rInAttrs.GetItemState( SID_SCH_EDITOPTIONS, sal_False, &pItem ) == SFX_ITEM_SET )
{
pColorConfig = SAL_STATIC_CAST( SvxChartColorTableItem*, pItem->Clone() );
}
else
{
SvxChartColorTable aTable;
aTable.useDefault();
pColorConfig = new SvxChartColorTableItem( SID_SCH_EDITOPTIONS, aTable );
pColorConfig->SetOptions( pChartOptions );
}
Construct();
}
SvxDefaultColorOptPage::~SvxDefaultColorOptPage()
{
// save changes
pChartOptions->SetDefaultColors( pColorConfig->GetColorTable() );
pChartOptions->Commit();
delete pColorConfig;
delete pColorTab;
delete pChartOptions;
}
void SvxDefaultColorOptPage::Construct()
{
if( pColorConfig )
aLbChartColors.FillBox( pColorConfig->GetColorTable() );
FillColorBox();
aLbChartColors.SelectEntryPos( 0 );
ListClickedHdl( &aLbChartColors );
}
SfxTabPage* SvxDefaultColorOptPage::Create( Window* pParent, const SfxItemSet& rAttrs )
{
return new SvxDefaultColorOptPage( pParent, rAttrs );
}
sal_Bool SvxDefaultColorOptPage::FillItemSet( SfxItemSet& rOutAttrs )
{
if( pColorConfig )
rOutAttrs.Put( *SAL_STATIC_CAST( SfxPoolItem*, pColorConfig ));
return sal_True;
}
void SvxDefaultColorOptPage::Reset( const SfxItemSet& )
{
aLbChartColors.SelectEntryPos( 0 );
ListClickedHdl( &aLbChartColors );
}
void SvxDefaultColorOptPage::FillColorBox()
{
if( !pColorTab ) return;
long nCount = pColorTab->Count();
XColorEntry* pColorEntry;
if( nCount > 104 )
aValSetColorBox.SetStyle( aValSetColorBox.GetStyle() | WB_VSCROLL );
for( long i = 0; i < nCount; i++ )
{
pColorEntry = pColorTab->GetColor( i );
aValSetColorBox.InsertItem( (sal_uInt16) i + 1, pColorEntry->GetColor(), pColorEntry->GetName() );
}
}
long SvxDefaultColorOptPage::GetColorIndex( const Color& rCol )
{
if( pColorTab )
{
long nCount = pColorTab->Count();
XColorEntry* pColorEntry;
for( long i = nCount - 1; i >= 0; i-- ) // default chart colors are at the end of the table
{
pColorEntry = pColorTab->GetColor( i );
if( pColorEntry && pColorEntry->GetColor() == rCol )
return SAL_STATIC_CAST( XPropertyTable*, pColorTab )->Get( pColorEntry->GetName() );
}
}
return -1L;
}
// --------------------
// event handlers
// --------------------
// ResetToDefaults
// ---------------
IMPL_LINK( SvxDefaultColorOptPage, ResetToDefaults, void *, EMPTYARG )
{
if( pColorConfig )
{
pColorConfig->GetColorTable().useDefault();
aLbChartColors.Clear();
aLbChartColors.FillBox( pColorConfig->GetColorTable() );
aLbChartColors.GetFocus();
aLbChartColors.SelectEntryPos( 0 );
aPBRemove.Enable( sal_True );
}
return 0L;
}
// AddChartColor
// ------------
IMPL_LINK( SvxDefaultColorOptPage, AddChartColor, void *, EMPTYARG )
{
if( pColorConfig )
{
ColorData black = RGB_COLORDATA( 0x00, 0x00, 0x00 );
pColorConfig->GetColorTable().append (XColorEntry ( black, pColorConfig->GetColorTable().getDefaultName(pColorConfig->GetColorTable().size())));
aLbChartColors.Clear();
aLbChartColors.FillBox( pColorConfig->GetColorTable() );
aLbChartColors.GetFocus();
aLbChartColors.SelectEntryPos( pColorConfig->GetColorTable().size() - 1 );
aPBRemove.Enable( sal_True );
}
return 0L;
}
// RemoveChartColor
// ----------------
IMPL_LINK( SvxDefaultColorOptPage, RemoveChartColor, PushButton*, pButton )
{
size_t nIndex = aLbChartColors.GetSelectEntryPos();
if (aLbChartColors.GetSelectEntryCount() == 0)
return 0L;
if( pColorConfig )
{
OSL_ENSURE(pColorConfig->GetColorTable().size() > 1, "don't delete the last chart color");
QueryBox aQuery(pButton, CUI_RES(RID_OPTQB_COLOR_CHART_DELETE));
aQuery.SetText(String(CUI_RES(RID_OPTSTR_COLOR_CHART_DELETE)));
if(RET_YES == aQuery.Execute())
{
pColorConfig->GetColorTable().remove( nIndex );
aLbChartColors.Clear();
aLbChartColors.FillBox( pColorConfig->GetColorTable() );
aLbChartColors.GetFocus();
if (nIndex == aLbChartColors.GetEntryCount() && aLbChartColors.GetEntryCount() > 0)
aLbChartColors.SelectEntryPos( pColorConfig->GetColorTable().size() - 1 );
else if (aLbChartColors.GetEntryCount() > 0)
aLbChartColors.SelectEntryPos( nIndex );
else
aPBRemove.Enable( sal_False );
}
}
return 0L;
}
// ListClickedHdl
// --------------
IMPL_LINK( SvxDefaultColorOptPage, ListClickedHdl, ChartColorLB*, pColorList )
{
Color aCol = pColorList->GetSelectEntryColor();
long nIndex = GetColorIndex( aCol );
if( nIndex == -1 ) // not found
{
aValSetColorBox.SetNoSelection();
}
else
{
aValSetColorBox.SelectItem( (sal_uInt16)nIndex + 1 ); // ValueSet is 1-based
}
return 0L;
}
// BoxClickedHdl
// -------------
IMPL_LINK( SvxDefaultColorOptPage, BoxClickedHdl, ValueSet*, EMPTYARG )
{
sal_uInt16 nIdx = aLbChartColors.GetSelectEntryPos();
if( nIdx != LISTBOX_ENTRY_NOTFOUND )
{
XColorEntry aEntry( aValSetColorBox.GetItemColor( aValSetColorBox.GetSelectItemId() ),
aLbChartColors.GetSelectEntry() );
aLbChartColors.Modify( & aEntry, nIdx );
pColorConfig->ReplaceColorByIndex( nIdx, aEntry );
aLbChartColors.SelectEntryPos( nIdx ); // reselect entry
}
return 0L;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Disable Removebutton in optchart
|
Disable Removebutton in optchart
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
a7b101b5dad52ea268d783bf86ad331db4e036a2
|
data-structures/chain/chain.cpp
|
data-structures/chain/chain.cpp
|
#include <iostream>
#include <sstream>
#include "Myexception.h"
#include "chain.h"
using namespace std;
void chain :: readAndStoreFromFile(char* fileName)
{
//This function reads integers from the file given by fileName then store them in the chain
ifstream in;
in.open(filename.c_str());
if (!in) return; // file doesn't exist
int line;
while(getline(in, line)) {
insert(1, line);
}
/*int line;
while(std::getline(data, line))
std::stringstream str(line);
std::string text;
std::getline(str,text,'=');
double value;
str >> value;
}*/
}
void chain :: eraseModuloValue(int theInt)
{
//This function erases all the entries from the list which are multiple of theInt
}
void chain :: oddAndEvenOrdering()
{
//This function reorders the list such a way that all odd numbers precede all even numbers.
//Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering.
}
void chain :: reverse()
{
//Reverses the list
}
chain :: chain(int initialCapacity)
{
//Constructor
if(initialCapacity < 1)
{
ostringstream s;
s << "Initial capacity = " << initialCapacity << " Must be > 0";
throw illegalParameterValue(s.str());
}
firstNode = NULL;
listSize = 0;
}
chain :: ~chain()
{
//Destructor. Delete all nodes in chain
while(firstNode != NULL)
{
//delete firstNode
chainNode* nextNode = firstNode->next;
delete firstNode;
firstNode = nextNode;
}
}
int* chain :: get(int theIndex) const
{
//Return element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return NULL;
}
chainNode* currentNode = firstNode;
for(int i=0;i<theIndex;i++)
currentNode = currentNode->next;
return ¤tNode->element;
}
int chain :: indexOf(const int& theElement) const
{
//Return index of first occurrence of theElement.
//Return -1 of theElement not in list.
chainNode* currentNode = firstNode;
int index = 0;
while(currentNode != NULL && currentNode->element != theElement)
{
//move to the next node
currentNode = currentNode->next;
index++;
}
//make sure we found matching element
if(currentNode == NULL)
return -1;
else
return index;
}
void chain :: erase(int theIndex)
{
//Delete the element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
chainNode* deleteNode;
if(theIndex == 0)
{
//remove first node from chain
deleteNode = firstNode;
firstNode = firstNode->next;
}
else
{
//use p to get to predecessor of desired node
chainNode* p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
deleteNode = p->next;
p->next = p->next->next; //remove deleteNode from chain
}
listSize--;
delete deleteNode;
}
void chain :: insert(int theIndex, const int& theElement)
{
//Insert theElement so that its index is theIndex.
try{
if (theIndex < 0 || theIndex > listSize)
{// invalid index
ostringstream s;
s << "index = " << theIndex << " size = " << listSize;
throw illegalIndex(s.str());
}
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
if(theIndex == 0)
//insert at front
firstNode = new chainNode(theElement, firstNode);
else
{
chainNode *p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
//insert after p
p->next = new chainNode(theElement, p->next);
}
listSize++;
}
void chain :: output() const
{
//Put the list into the output.
for(int i=0;i<listSize;i++)
cout << *this->get(i) << " ";
cout<<endl;
}
void chain::checkIndex(int theIndex) const
{
// Verify that theIndex is between 0 and
// listSize - 1.
if (theIndex < 0 || theIndex >= listSize){
ostringstream s;
s << "index = " << theIndex << " size = "
<< listSize<<", the input index is invalid";
throw illegalIndex(s.str());
}
}
|
#include <iostream>
#include <sstream>
#include "Myexception.h"
#include "chain.h"
using namespace std;
void chain :: readAndStoreFromFile(char* fileName)
{
//This function reads integers from the file given by fileName then store them in the chain
ifstream in;
in.open(filename.c_str());
if (!in) return; // file doesn't exist
int line;
while(in >> line) {
insert(1, line);
}
/*int line;
while(std::getline(data, line))
std::stringstream str(line);
std::string text;
std::getline(str,text,'=');
double value;
str >> value;
}*/
}
void chain :: eraseModuloValue(int theInt)
{
//This function erases all the entries from the list which are multiple of theInt
}
void chain :: oddAndEvenOrdering()
{
//This function reorders the list such a way that all odd numbers precede all even numbers.
//Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering.
}
void chain :: reverse()
{
//Reverses the list
}
chain :: chain(int initialCapacity)
{
//Constructor
if(initialCapacity < 1)
{
ostringstream s;
s << "Initial capacity = " << initialCapacity << " Must be > 0";
throw illegalParameterValue(s.str());
}
firstNode = NULL;
listSize = 0;
}
chain :: ~chain()
{
//Destructor. Delete all nodes in chain
while(firstNode != NULL)
{
//delete firstNode
chainNode* nextNode = firstNode->next;
delete firstNode;
firstNode = nextNode;
}
}
int* chain :: get(int theIndex) const
{
//Return element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return NULL;
}
chainNode* currentNode = firstNode;
for(int i=0;i<theIndex;i++)
currentNode = currentNode->next;
return ¤tNode->element;
}
int chain :: indexOf(const int& theElement) const
{
//Return index of first occurrence of theElement.
//Return -1 of theElement not in list.
chainNode* currentNode = firstNode;
int index = 0;
while(currentNode != NULL && currentNode->element != theElement)
{
//move to the next node
currentNode = currentNode->next;
index++;
}
//make sure we found matching element
if(currentNode == NULL)
return -1;
else
return index;
}
void chain :: erase(int theIndex)
{
//Delete the element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
chainNode* deleteNode;
if(theIndex == 0)
{
//remove first node from chain
deleteNode = firstNode;
firstNode = firstNode->next;
}
else
{
//use p to get to predecessor of desired node
chainNode* p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
deleteNode = p->next;
p->next = p->next->next; //remove deleteNode from chain
}
listSize--;
delete deleteNode;
}
void chain :: insert(int theIndex, const int& theElement)
{
//Insert theElement so that its index is theIndex.
try{
if (theIndex < 0 || theIndex > listSize)
{// invalid index
ostringstream s;
s << "index = " << theIndex << " size = " << listSize;
throw illegalIndex(s.str());
}
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
if(theIndex == 0)
//insert at front
firstNode = new chainNode(theElement, firstNode);
else
{
chainNode *p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
//insert after p
p->next = new chainNode(theElement, p->next);
}
listSize++;
}
void chain :: output() const
{
//Put the list into the output.
for(int i=0;i<listSize;i++)
cout << *this->get(i) << " ";
cout<<endl;
}
void chain::checkIndex(int theIndex) const
{
// Verify that theIndex is between 0 and
// listSize - 1.
if (theIndex < 0 || theIndex >= listSize){
ostringstream s;
s << "index = " << theIndex << " size = "
<< listSize<<", the input index is invalid";
throw illegalIndex(s.str());
}
}
|
Update chain.cpp
|
Update chain.cpp
|
C++
|
mit
|
atthehotcorner/coursework,atthehotcorner/coursework,atthehotcorner/coursework
|
40336160a7b0a70502cda3c37567ec8b78c6bead
|
tools/swift-llvm-opt/LLVMOpt.cpp
|
tools/swift-llvm-opt/LLVMOpt.cpp
|
//===--- LLVMOpt.cpp ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// This is a simple reimplementation of opt that includes support for Swift-
/// specific LLVM passes. It is meant to make it easier to handle issues related
/// to transitioning to the new LLVM pass manager (which lacks the dynamism of
/// the old pass manager) and also problems during the code base transition to
/// that pass manager. Additionally it will enable a user to exactly simulate
/// Swift's LLVM pass pipeline by using the same pass pipeline building
/// machinery in IRGen, something not possible with opt.
///
//===----------------------------------------------------------------------===//
#include "swift/Subsystems.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/LLVMPasses/PassesFwd.h"
#include "swift/LLVMPasses/Passes.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/CallGraphSCCPass.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/RegionPass.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Bitcode/BitcodeWriterPass.h"
#include "llvm/CodeGen/CommandFlags.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/IRPrintingPasses.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/LegacyPassNameParser.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/InitializePasses.h"
#include "llvm/LinkAllIR.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
using namespace swift;
static llvm::codegen::RegisterCodeGenFlags CGF;
//===----------------------------------------------------------------------===//
// Option Declarations
//===----------------------------------------------------------------------===//
// The OptimizationList is automatically populated with registered passes by the
// PassNameParser.
//
static llvm::cl::list<const llvm::PassInfo *, bool, llvm::PassNameParser>
PassList(llvm::cl::desc("Optimizations available:"));
static llvm::cl::opt<bool>
Optimized("O", llvm::cl::desc("Optimization level O. Similar to swift -O"));
// TODO: I wanted to call this 'verify', but some other pass is using this
// option.
static llvm::cl::opt<bool> VerifyEach(
"verify-each",
llvm::cl::desc("Should we spend time verifying that the IR is well "
"formed"));
static llvm::cl::opt<std::string>
TargetTriple("mtriple",
llvm::cl::desc("Override target triple for module"));
static llvm::cl::opt<bool>
PrintStats("print-stats",
llvm::cl::desc("Should LLVM Statistics be printed"));
static llvm::cl::opt<std::string> InputFilename(llvm::cl::Positional,
llvm::cl::desc("<input file>"),
llvm::cl::init("-"),
llvm::cl::value_desc("filename"));
static llvm::cl::opt<std::string>
OutputFilename("o", llvm::cl::desc("Override output filename"),
llvm::cl::value_desc("filename"));
static llvm::cl::opt<std::string> DefaultDataLayout(
"default-data-layout",
llvm::cl::desc("data layout string to use if not specified by module"),
llvm::cl::value_desc("layout-string"), llvm::cl::init(""));
//===----------------------------------------------------------------------===//
// Helper Methods
//===----------------------------------------------------------------------===//
static llvm::CodeGenOpt::Level GetCodeGenOptLevel() {
// TODO: Is this the right thing to do here?
if (Optimized)
return llvm::CodeGenOpt::Default;
return llvm::CodeGenOpt::None;
}
// Returns the TargetMachine instance or zero if no triple is provided.
static llvm::TargetMachine *
getTargetMachine(llvm::Triple TheTriple, StringRef CPUStr,
StringRef FeaturesStr, const llvm::TargetOptions &Options) {
std::string Error;
const auto *TheTarget = llvm::TargetRegistry::lookupTarget(
llvm::codegen::getMArch(), TheTriple, Error);
// Some modules don't specify a triple, and this is okay.
if (!TheTarget) {
return nullptr;
}
return TheTarget->createTargetMachine(
TheTriple.getTriple(), CPUStr, FeaturesStr, Options,
Optional<llvm::Reloc::Model>(llvm::codegen::getExplicitRelocModel()),
llvm::codegen::getExplicitCodeModel(), GetCodeGenOptLevel());
}
static void dumpOutput(llvm::Module &M, llvm::raw_ostream &os) {
// For now just always dump assembly.
llvm::legacy::PassManager EmitPasses;
EmitPasses.add(createPrintModulePass(os));
EmitPasses.run(M);
}
// This function isn't referenced outside its translation unit, but it
// can't use the "static" keyword because its address is used for
// getMainExecutable (since some platforms don't support taking the
// address of main, and some platforms can't implement getMainExecutable
// without being given the address of a function in the main executable).
void anchorForGetMainExecutable() {}
static inline void addPass(llvm::legacy::PassManagerBase &PM, llvm::Pass *P) {
// Add the pass to the pass manager...
PM.add(P);
if (P->getPassID() == &SwiftAAWrapperPass::ID) {
PM.add(llvm::createExternalAAWrapperPass([](llvm::Pass &P, llvm::Function &,
llvm::AAResults &AAR) {
if (auto *WrapperPass = P.getAnalysisIfAvailable<SwiftAAWrapperPass>())
AAR.addAAResult(WrapperPass->getResult());
}));
}
// If we are verifying all of the intermediate steps, add the verifier...
if (VerifyEach)
PM.add(llvm::createVerifierPass());
}
static void runSpecificPasses(StringRef Binary, llvm::Module *M,
llvm::TargetMachine *TM,
llvm::Triple &ModuleTriple) {
llvm::legacy::PassManager Passes;
llvm::TargetLibraryInfoImpl TLII(ModuleTriple);
Passes.add(new llvm::TargetLibraryInfoWrapperPass(TLII));
const llvm::DataLayout &DL = M->getDataLayout();
if (DL.isDefault() && !DefaultDataLayout.empty()) {
M->setDataLayout(DefaultDataLayout);
}
// Add internal analysis passes from the target machine.
Passes.add(createTargetTransformInfoWrapperPass(
TM ? TM->getTargetIRAnalysis() : llvm::TargetIRAnalysis()));
if (TM) {
// FIXME: We should dyn_cast this when supported.
auto <M = static_cast<llvm::LLVMTargetMachine &>(*TM);
llvm::Pass *TPC = LTM.createPassConfig(Passes);
Passes.add(TPC);
}
for (const llvm::PassInfo *PassInfo : PassList) {
llvm::Pass *P = nullptr;
if (PassInfo->getNormalCtor())
P = PassInfo->getNormalCtor()();
else
llvm::errs() << Binary
<< ": cannot create pass: " << PassInfo->getPassName()
<< "\n";
if (P) {
addPass(Passes, P);
}
}
// Do it.
Passes.run(*M);
}
//===----------------------------------------------------------------------===//
// Main Implementation
//===----------------------------------------------------------------------===//
int main(int argc, char **argv) {
PROGRAM_START(argc, argv);
INITIALIZE_LLVM();
// Initialize passes
llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
initializeCore(Registry);
initializeScalarOpts(Registry);
initializeObjCARCOpts(Registry);
initializeVectorization(Registry);
initializeIPO(Registry);
initializeAnalysis(Registry);
initializeTransformUtils(Registry);
initializeInstCombine(Registry);
initializeInstrumentation(Registry);
initializeTarget(Registry);
// For codegen passes, only passes that do IR to IR transformation are
// supported.
initializeCodeGenPreparePass(Registry);
initializeAtomicExpandPass(Registry);
initializeRewriteSymbolsLegacyPassPass(Registry);
initializeWinEHPreparePass(Registry);
initializeDwarfEHPrepareLegacyPassPass(Registry);
initializeSjLjEHPreparePass(Registry);
// Register Swift Only Passes.
initializeSwiftAAWrapperPassPass(Registry);
initializeSwiftARCOptPass(Registry);
initializeSwiftARCContractPass(Registry);
initializeInlineTreePrinterPass(Registry);
initializeLegacySwiftMergeFunctionsPass(Registry);
llvm::cl::ParseCommandLineOptions(argc, argv, "Swift LLVM optimizer\n");
if (PrintStats)
llvm::EnableStatistics();
llvm::SMDiagnostic Err;
// Load the input module...
auto LLVMContext = std::make_unique<llvm::LLVMContext>();
std::unique_ptr<llvm::Module> M =
parseIRFile(InputFilename, Err, *LLVMContext.get());
if (!M) {
Err.print(argv[0], llvm::errs());
return 1;
}
if (verifyModule(*M, &llvm::errs())) {
llvm::errs() << argv[0] << ": " << InputFilename
<< ": error: input module is broken!\n";
return 1;
}
// If we are supposed to override the target triple, do so now.
if (!TargetTriple.empty())
M->setTargetTriple(llvm::Triple::normalize(TargetTriple));
// Figure out what stream we are supposed to write to...
std::unique_ptr<llvm::ToolOutputFile> Out;
// Default to standard output.
if (OutputFilename.empty())
OutputFilename = "-";
std::error_code EC;
Out.reset(
new llvm::ToolOutputFile(OutputFilename, EC, llvm::sys::fs::OF_None));
if (EC) {
llvm::errs() << EC.message() << '\n';
return 1;
}
llvm::Triple ModuleTriple(M->getTargetTriple());
std::string CPUStr, FeaturesStr;
llvm::TargetMachine *Machine = nullptr;
const llvm::TargetOptions Options =
llvm::codegen::InitTargetOptionsFromCodeGenFlags(ModuleTriple);
if (ModuleTriple.getArch()) {
CPUStr = llvm::codegen::getCPUStr();
FeaturesStr = llvm::codegen::getFeaturesStr();
Machine = getTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
}
std::unique_ptr<llvm::TargetMachine> TM(Machine);
// Override function attributes based on CPUStr, FeaturesStr, and command line
// flags.
llvm::codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
if (Optimized) {
IRGenOptions Opts;
Opts.OptMode = OptimizationMode::ForSpeed;
// Then perform the optimizations.
performLLVMOptimizations(Opts, M.get(), TM.get());
} else {
runSpecificPasses(argv[0], M.get(), TM.get(), ModuleTriple);
}
// Finally dump the output.
dumpOutput(*M, Out->os());
return 0;
}
|
//===--- LLVMOpt.cpp ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// This is a simple reimplementation of opt that includes support for Swift-
/// specific LLVM passes. It is meant to make it easier to handle issues related
/// to transitioning to the new LLVM pass manager (which lacks the dynamism of
/// the old pass manager) and also problems during the code base transition to
/// that pass manager. Additionally it will enable a user to exactly simulate
/// Swift's LLVM pass pipeline by using the same pass pipeline building
/// machinery in IRGen, something not possible with opt.
///
//===----------------------------------------------------------------------===//
#include "swift/Subsystems.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/LLVMPasses/PassesFwd.h"
#include "swift/LLVMPasses/Passes.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/CallGraphSCCPass.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/RegionPass.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Bitcode/BitcodeWriterPass.h"
#include "llvm/CodeGen/CommandFlags.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/IRPrintingPasses.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/LegacyPassNameParser.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/InitializePasses.h"
#include "llvm/LinkAllIR.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
using namespace swift;
static llvm::codegen::RegisterCodeGenFlags CGF;
//===----------------------------------------------------------------------===//
// Option Declarations
//===----------------------------------------------------------------------===//
// The OptimizationList is automatically populated with registered passes by the
// PassNameParser.
//
static llvm::cl::list<const llvm::PassInfo *, bool, llvm::PassNameParser>
PassList(llvm::cl::desc("Optimizations available:"));
static llvm::cl::opt<bool>
UseLegacyPassManager("legacy-pass-manager",
llvm::cl::desc("Use the legacy llvm pass manager"),
llvm::cl::init(true));
static llvm::cl::opt<bool>
Optimized("O", llvm::cl::desc("Optimization level O. Similar to swift -O"));
// TODO: I wanted to call this 'verify', but some other pass is using this
// option.
static llvm::cl::opt<bool> VerifyEach(
"verify-each",
llvm::cl::desc("Should we spend time verifying that the IR is well "
"formed"));
static llvm::cl::opt<std::string>
TargetTriple("mtriple",
llvm::cl::desc("Override target triple for module"));
static llvm::cl::opt<bool>
PrintStats("print-stats",
llvm::cl::desc("Should LLVM Statistics be printed"));
static llvm::cl::opt<std::string> InputFilename(llvm::cl::Positional,
llvm::cl::desc("<input file>"),
llvm::cl::init("-"),
llvm::cl::value_desc("filename"));
static llvm::cl::opt<std::string>
OutputFilename("o", llvm::cl::desc("Override output filename"),
llvm::cl::value_desc("filename"));
static llvm::cl::opt<std::string> DefaultDataLayout(
"default-data-layout",
llvm::cl::desc("data layout string to use if not specified by module"),
llvm::cl::value_desc("layout-string"), llvm::cl::init(""));
//===----------------------------------------------------------------------===//
// Helper Methods
//===----------------------------------------------------------------------===//
static llvm::CodeGenOpt::Level GetCodeGenOptLevel() {
// TODO: Is this the right thing to do here?
if (Optimized)
return llvm::CodeGenOpt::Default;
return llvm::CodeGenOpt::None;
}
// Returns the TargetMachine instance or zero if no triple is provided.
static llvm::TargetMachine *
getTargetMachine(llvm::Triple TheTriple, StringRef CPUStr,
StringRef FeaturesStr, const llvm::TargetOptions &Options) {
std::string Error;
const auto *TheTarget = llvm::TargetRegistry::lookupTarget(
llvm::codegen::getMArch(), TheTriple, Error);
// Some modules don't specify a triple, and this is okay.
if (!TheTarget) {
return nullptr;
}
return TheTarget->createTargetMachine(
TheTriple.getTriple(), CPUStr, FeaturesStr, Options,
Optional<llvm::Reloc::Model>(llvm::codegen::getExplicitRelocModel()),
llvm::codegen::getExplicitCodeModel(), GetCodeGenOptLevel());
}
static void dumpOutput(llvm::Module &M, llvm::raw_ostream &os) {
// For now just always dump assembly.
llvm::legacy::PassManager EmitPasses;
EmitPasses.add(createPrintModulePass(os));
EmitPasses.run(M);
}
// This function isn't referenced outside its translation unit, but it
// can't use the "static" keyword because its address is used for
// getMainExecutable (since some platforms don't support taking the
// address of main, and some platforms can't implement getMainExecutable
// without being given the address of a function in the main executable).
void anchorForGetMainExecutable() {}
static inline void addPass(llvm::legacy::PassManagerBase &PM, llvm::Pass *P) {
// Add the pass to the pass manager...
PM.add(P);
if (P->getPassID() == &SwiftAAWrapperPass::ID) {
PM.add(llvm::createExternalAAWrapperPass([](llvm::Pass &P, llvm::Function &,
llvm::AAResults &AAR) {
if (auto *WrapperPass = P.getAnalysisIfAvailable<SwiftAAWrapperPass>())
AAR.addAAResult(WrapperPass->getResult());
}));
}
// If we are verifying all of the intermediate steps, add the verifier...
if (VerifyEach)
PM.add(llvm::createVerifierPass());
}
static void runSpecificPasses(StringRef Binary, llvm::Module *M,
llvm::TargetMachine *TM,
llvm::Triple &ModuleTriple) {
llvm::legacy::PassManager Passes;
llvm::TargetLibraryInfoImpl TLII(ModuleTriple);
Passes.add(new llvm::TargetLibraryInfoWrapperPass(TLII));
const llvm::DataLayout &DL = M->getDataLayout();
if (DL.isDefault() && !DefaultDataLayout.empty()) {
M->setDataLayout(DefaultDataLayout);
}
// Add internal analysis passes from the target machine.
Passes.add(createTargetTransformInfoWrapperPass(
TM ? TM->getTargetIRAnalysis() : llvm::TargetIRAnalysis()));
if (TM) {
// FIXME: We should dyn_cast this when supported.
auto <M = static_cast<llvm::LLVMTargetMachine &>(*TM);
llvm::Pass *TPC = LTM.createPassConfig(Passes);
Passes.add(TPC);
}
for (const llvm::PassInfo *PassInfo : PassList) {
llvm::Pass *P = nullptr;
if (PassInfo->getNormalCtor())
P = PassInfo->getNormalCtor()();
else
llvm::errs() << Binary
<< ": cannot create pass: " << PassInfo->getPassName()
<< "\n";
if (P) {
addPass(Passes, P);
}
}
// Do it.
Passes.run(*M);
}
//===----------------------------------------------------------------------===//
// Main Implementation
//===----------------------------------------------------------------------===//
int main(int argc, char **argv) {
PROGRAM_START(argc, argv);
INITIALIZE_LLVM();
// Initialize passes
llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
initializeCore(Registry);
initializeScalarOpts(Registry);
initializeObjCARCOpts(Registry);
initializeVectorization(Registry);
initializeIPO(Registry);
initializeAnalysis(Registry);
initializeTransformUtils(Registry);
initializeInstCombine(Registry);
initializeInstrumentation(Registry);
initializeTarget(Registry);
// For codegen passes, only passes that do IR to IR transformation are
// supported.
initializeCodeGenPreparePass(Registry);
initializeAtomicExpandPass(Registry);
initializeRewriteSymbolsLegacyPassPass(Registry);
initializeWinEHPreparePass(Registry);
initializeDwarfEHPrepareLegacyPassPass(Registry);
initializeSjLjEHPreparePass(Registry);
// Register Swift Only Passes.
initializeSwiftAAWrapperPassPass(Registry);
initializeSwiftARCOptPass(Registry);
initializeSwiftARCContractPass(Registry);
initializeInlineTreePrinterPass(Registry);
initializeLegacySwiftMergeFunctionsPass(Registry);
llvm::cl::ParseCommandLineOptions(argc, argv, "Swift LLVM optimizer\n");
if (PrintStats)
llvm::EnableStatistics();
llvm::SMDiagnostic Err;
// Load the input module...
auto LLVMContext = std::make_unique<llvm::LLVMContext>();
std::unique_ptr<llvm::Module> M =
parseIRFile(InputFilename, Err, *LLVMContext.get());
if (!M) {
Err.print(argv[0], llvm::errs());
return 1;
}
if (verifyModule(*M, &llvm::errs())) {
llvm::errs() << argv[0] << ": " << InputFilename
<< ": error: input module is broken!\n";
return 1;
}
// If we are supposed to override the target triple, do so now.
if (!TargetTriple.empty())
M->setTargetTriple(llvm::Triple::normalize(TargetTriple));
// Figure out what stream we are supposed to write to...
std::unique_ptr<llvm::ToolOutputFile> Out;
// Default to standard output.
if (OutputFilename.empty())
OutputFilename = "-";
std::error_code EC;
Out.reset(
new llvm::ToolOutputFile(OutputFilename, EC, llvm::sys::fs::OF_None));
if (EC) {
llvm::errs() << EC.message() << '\n';
return 1;
}
llvm::Triple ModuleTriple(M->getTargetTriple());
std::string CPUStr, FeaturesStr;
llvm::TargetMachine *Machine = nullptr;
const llvm::TargetOptions Options =
llvm::codegen::InitTargetOptionsFromCodeGenFlags(ModuleTriple);
if (ModuleTriple.getArch()) {
CPUStr = llvm::codegen::getCPUStr();
FeaturesStr = llvm::codegen::getFeaturesStr();
Machine = getTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
}
std::unique_ptr<llvm::TargetMachine> TM(Machine);
// Override function attributes based on CPUStr, FeaturesStr, and command line
// flags.
llvm::codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
if (Optimized) {
IRGenOptions Opts;
Opts.OptMode = OptimizationMode::ForSpeed;
Opts.LegacyPassManager = UseLegacyPassManager;
// Then perform the optimizations.
performLLVMOptimizations(Opts, M.get(), TM.get());
} else {
runSpecificPasses(argv[0], M.get(), TM.get(), ModuleTriple);
}
// Finally dump the output.
dumpOutput(*M, Out->os());
return 0;
}
|
Add option to disable legacy pass manager to swift-llvm-opt
|
Add option to disable legacy pass manager to swift-llvm-opt
|
C++
|
apache-2.0
|
roambotics/swift,JGiola/swift,benlangmuir/swift,benlangmuir/swift,roambotics/swift,roambotics/swift,JGiola/swift,glessard/swift,roambotics/swift,benlangmuir/swift,apple/swift,apple/swift,benlangmuir/swift,apple/swift,apple/swift,roambotics/swift,JGiola/swift,JGiola/swift,glessard/swift,glessard/swift,glessard/swift,roambotics/swift,benlangmuir/swift,glessard/swift,glessard/swift,apple/swift,benlangmuir/swift,JGiola/swift,apple/swift,JGiola/swift
|
cd8dfa4e6d8aefa2fffdc2663bea81053c6ae897
|
T0/MakeTrendT0.C
|
T0/MakeTrendT0.C
|
#include "TChain.h"
#include "TTree.h"
#include "TH1F.h"
#include "TF1.h"
#include "TH2F.h"
#include "TCanvas.h"
#include "TObjArray.h"
#include "TTreeStream.h"
#define NPMTs 24
int MakeTrendT0( char *infile, int run) {
char *outfile = "trending.root";
if(!infile) return -1;
if(!outfile) return -1;
TFile *f = TFile::Open(infile,"read");
if (!f) {
printf("File %s not available\n", infile);
return -1;
}
// LOAD HISTOGRAMS FROM QAresults.root
TObjArray *fTzeroObject = (TObjArray*) f->Get("T0_Performance/QAT0chists");
TH1F* fTzeroORAplusORC =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fTzeroORAplusORC"))->Clone("A");
TH1F* fResolution =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fResolution"))->Clone("B");
TH1F* fTzeroORA =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fTzeroORA"))->Clone("C");
TH1F* fTzeroORC =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fTzeroORC"))->Clone("D");
TH2F *fTimeVSAmplitude[NPMTs];//counting PMTs from 0
TH1D *fAmplitude[NPMTs];
TH1D *fTime[NPMTs];
//-----> add new histogram here
// sigma fit of resolution, mean T0A, T0C and T0C&A, mean amplitude for each PMT
double resolutionSigma = -9999; //dummy init
double tzeroOrAPlusOrC = -9999; //dummy init
double tzeroOrA = -9999; //dummy init
double tzeroOrC = -9999; //dummy init
double meanAmplitude[NPMTs]; //dummy init
double meanTime[NPMTs]; //dummy init
double timeDelayOCDB[NPMTs]; //dummy init
//.................................................................................
for(int ipmt=1; ipmt<=NPMTs; ipmt++){ //loop over all PMTs
fTimeVSAmplitude[ipmt-1] =(TH2F*) ((TH2F*) fTzeroObject->FindObject(Form("fTimeVSAmplitude%d",ipmt)))->Clone(Form("E%d",ipmt));
int nbinsX = fTimeVSAmplitude[ipmt-1]->GetNbinsX();
int nbinsY = fTimeVSAmplitude[ipmt-1]->GetNbinsY();
//Amplitude
fAmplitude[ipmt-1] = (TH1D*) fTimeVSAmplitude[ipmt-1]->ProjectionX(Form("fAmplitude%d",ipmt), 1, nbinsY);
meanAmplitude[ipmt-1] = -9999; //dummy init
if(fAmplitude[ipmt-1]->GetEntries()>0){
meanAmplitude[ipmt-1] = fAmplitude[ipmt-1]->GetMean();
}
//Time
fTime[ipmt-1] = (TH1D*) fTimeVSAmplitude[ipmt-1]->ProjectionY(Form("fTime%d",ipmt), 1, nbinsX);
meanTime[ipmt-1] = -9999; //dummy init
if(fTime[ipmt-1]->GetEntries()>0){
if(fTime[ipmt-1]->GetEntries()>20){
meanTime[ipmt-1] = GetParameterGaus((TH1F*) fTime[ipmt-1], 1); // Mean Time
}else if(fTime[ipmt-1]->GetEntries()>0){
meanTime[ipmt-1] = fTime[ipmt-1]->GetMean();
}
}
}
if(fResolution->GetEntries()>20){
resolutionSigma = GetParameterGaus(fResolution, 2); //gaussian sigma
}else if(fResolution->GetEntries()>0){
resolutionSigma = fResolution->GetRMS(); //gaussian sigma
}
if(fTzeroORAplusORC->GetEntries()>20){
tzeroOrAPlusOrC = GetParameterGaus(fTzeroORAplusORC, 1); //gaussian mean
}else if(fTzeroORAplusORC->GetEntries()>0){
tzeroOrAPlusOrC = fTzeroORAplusORC->GetMean();
}
if(fTzeroORA->GetEntries()>20){
tzeroOrA = GetParameterGaus(fTzeroORA, 1); //gaussian mean
}else if(fTzeroORA->GetEntries()>0){
tzeroOrA = fTzeroORA->GetMean();
}
if(fTzeroORC->GetEntries()>20){
tzeroOrC = GetParameterGaus(fTzeroORC, 1); //gaussian mean
}else if(fTzeroORC->GetEntries()>0){
tzeroOrC = fTzeroORC->GetMean(); //gaussian mean
}
//-----> analyze the new histogram here and set mean/sigma
f->Close();
//-------------------- READ OCDB TIME DELAYS ---------------------------
// Arguments:
AliCDBManager* man = AliCDBManager::Instance();
man->SetDefaultStorage("raw://");
man->SetRun(run);
AliCDBEntry *entry = AliCDBManager::Instance()->Get("T0/Calib/TimeDelay");
AliT0CalibTimeEq *clb = (AliT0CalibTimeEq*)entry->GetObject();
for (Int_t i=0; i<NPMTs; i++){
timeDelayOCDB[i] = 0;
if(clb)
timeDelayOCDB[i] = clb->GetCFDvalue(i,0);
}
//--------------- write walues to the output ------------
TTreeSRedirector* pcstream = NULL;
pcstream = new TTreeSRedirector(outfile);
if (!pcstream) return;
TFile *x = pcstream->GetFile();
x->cd();
TObjString runType;
Int_t startTimeGRP=0;
Int_t stopTimeGRP=0;
Int_t time=0;
Int_t duration=0;
time = (startTimeGRP+stopTimeGRP)/2;
duration = (stopTimeGRP-startTimeGRP);
(*pcstream)<<"t0QA"<<
"run="<<run;//<<
//"time="<<time<<
// "startTimeGRP="<<startTimeGRP<<
// "stopTimeGRP="<<stopTimeGRP<<
/// "duration="<<duration<<
// "runType.="<<&runType;
(*pcstream)<<"t0QA"<<
"resolution="<< resolutionSigma<<
"tzeroOrAPlusOrC="<< tzeroOrAPlusOrC<<
"tzeroOrA="<< tzeroOrA<<
"tzeroOrC="<< tzeroOrC<<
"amplPMT1="<<meanAmplitude[0]<<
"amplPMT2="<<meanAmplitude[1]<<
"amplPMT3="<<meanAmplitude[2]<<
"amplPMT4="<<meanAmplitude[3]<<
"amplPMT5="<<meanAmplitude[4]<<
"amplPMT6="<<meanAmplitude[5]<<
"amplPMT7="<<meanAmplitude[6]<<
"amplPMT8="<<meanAmplitude[7]<<
"amplPMT9="<<meanAmplitude[8]<<
"amplPMT10="<<meanAmplitude[9]<<
"amplPMT11="<<meanAmplitude[10]<<
"amplPMT12="<<meanAmplitude[11]<<
"amplPMT13="<<meanAmplitude[12]<<
"amplPMT14="<<meanAmplitude[13]<<
"amplPMT15="<<meanAmplitude[14]<<
"amplPMT16="<<meanAmplitude[15]<<
"amplPMT17="<<meanAmplitude[16]<<
"amplPMT18="<<meanAmplitude[17]<<
"amplPMT19="<<meanAmplitude[18]<<
"amplPMT20="<<meanAmplitude[19]<<
"amplPMT21="<<meanAmplitude[20]<<
"amplPMT22="<<meanAmplitude[21]<<
"amplPMT23="<<meanAmplitude[22]<<
"amplPMT24="<<meanAmplitude[23]<<
"timePMT1="<<meanTime[0]<<
"timePMT2="<<meanTime[1]<<
"timePMT3="<<meanTime[2]<<
"timePMT4="<<meanTime[3]<<
"timePMT5="<<meanTime[4]<<
"timePMT6="<<meanTime[5]<<
"timePMT7="<<meanTime[6]<<
"timePMT8="<<meanTime[7]<<
"timePMT9="<<meanTime[8]<<
"timePMT10="<<meanTime[9]<<
"timePMT11="<<meanTime[10]<<
"timePMT12="<<meanTime[11]<<
"timePMT13="<<meanTime[12]<<
"timePMT14="<<meanTime[13]<<
"timePMT15="<<meanTime[14]<<
"timePMT16="<<meanTime[15]<<
"timePMT17="<<meanTime[16]<<
"timePMT18="<<meanTime[17]<<
"timePMT19="<<meanTime[18]<<
"timePMT20="<<meanTime[19]<<
"timePMT21="<<meanTime[20]<<
"timePMT22="<<meanTime[21]<<
"timePMT23="<<meanTime[22]<<
"timePMT24="<<meanTime[23];
(*pcstream)<<"t0QA"<<
"timeDelayPMT1="<<timeDelayOCDB[0]<<
"timeDelayPMT2="<<timeDelayOCDB[1]<<
"timeDelayPMT3="<<timeDelayOCDB[2]<<
"timeDelayPMT4="<<timeDelayOCDB[3]<<
"timeDelayPMT5="<<timeDelayOCDB[4]<<
"timeDelayPMT6="<<timeDelayOCDB[5]<<
"timeDelayPMT7="<<timeDelayOCDB[6]<<
"timeDelayPMT8="<<timeDelayOCDB[7]<<
"timeDelayPMT9="<<timeDelayOCDB[8]<<
"timeDelayPMT10="<<timeDelayOCDB[9]<<
"timeDelayPMT11="<<timeDelayOCDB[10]<<
"timeDelayPMT12="<<timeDelayOCDB[11]<<
"timeDelayPMT13="<<timeDelayOCDB[12]<<
"timeDelayPMT14="<<timeDelayOCDB[13]<<
"timeDelayPMT15="<<timeDelayOCDB[14]<<
"timeDelayPMT16="<<timeDelayOCDB[15]<<
"timeDelayPMT17="<<timeDelayOCDB[16]<<
"timeDelayPMT18="<<timeDelayOCDB[17]<<
"timeDelayPMT19="<<timeDelayOCDB[18]<<
"timeDelayPMT20="<<timeDelayOCDB[19]<<
"timeDelayPMT21="<<timeDelayOCDB[20]<<
"timeDelayPMT22="<<timeDelayOCDB[21]<<
"timeDelayPMT23="<<timeDelayOCDB[22]<<
"timeDelayPMT24="<<timeDelayOCDB[23];
//-----> add the mean/sigma of the new histogram here
(*pcstream)<<"t0QA"<<"\n";
pcstream->Close();
delete pcstream;
return;
}
//_____________________________________________________________________________
double GetParameterGaus(TH1F *histo, int whichParameter){
int maxBin = histo->GetMaximumBin();
double max = (histo->GetBinContent(maxBin-1) + histo->GetBinContent(maxBin) + histo->GetBinContent(maxBin+1))/3;
double mean = histo->GetBinCenter(maxBin); //mean
double lowfwhm = histo->GetBinCenter(histo->FindFirstBinAbove(max/2));
double highfwhm = histo->GetBinCenter(histo->FindLastBinAbove(max/2));
double sigma = (highfwhm - lowfwhm)/2.35482; //estimate fwhm FWHM = 2.35482*sigma
TF1 *gaussfit = new TF1("gaussfit","gaus", mean - 4*sigma, mean + 4*sigma); // fit in +- 4 sigma window
gaussfit->SetParameters(max, mean, sigma);
if(whichParameter==2)
histo->Fit(gaussfit,"RQNI");
else
histo->Fit(gaussfit,"RQN");
double parValue = gaussfit->GetParameter(whichParameter);
delete gaussfit;
return parValue;
}
|
#define NPMTs 24
int MakeTrendT0( char *infile, int run) {
gSystem->Load("libANALYSIS");
gSystem->Load("libANALYSISalice");
gSystem->Load("libCORRFW");
gSystem->Load("libTENDER");
gSystem->Load("libPWGPP.so");
char *outfile = "trending.root";
if(!infile) return -1;
if(!outfile) return -1;
TFile *f = TFile::Open(infile,"read");
if (!f) {
printf("File %s not available\n", infile);
return -1;
}
// LOAD HISTOGRAMS FROM QAresults.root
TObjArray *fTzeroObject = (TObjArray*) f->Get("T0_Performance/QAT0chists");
TH1F* fTzeroORAplusORC =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fTzeroORAplusORC"))->Clone("A");
TH1F* fResolution =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fResolution"))->Clone("B");
TH1F* fTzeroORA =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fTzeroORA"))->Clone("C");
TH1F* fTzeroORC =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fTzeroORC"))->Clone("D");
TH2F *fTimeVSAmplitude[NPMTs];//counting PMTs from 0
TH1D *fAmplitude[NPMTs];
TH1D *fTime[NPMTs];
//-----> add new histogram here
// sigma fit of resolution, mean T0A, T0C and T0C&A, mean amplitude for each PMT
double resolutionSigma = -9999; //dummy init
double tzeroOrAPlusOrC = -9999; //dummy init
double tzeroOrA = -9999; //dummy init
double tzeroOrC = -9999; //dummy init
double meanAmplitude[NPMTs]; //dummy init
double meanTime[NPMTs]; //dummy init
double timeDelayOCDB[NPMTs]; //dummy init
//.................................................................................
for(int ipmt=1; ipmt<=NPMTs; ipmt++){ //loop over all PMTs
fTimeVSAmplitude[ipmt-1] =(TH2F*) ((TH2F*) fTzeroObject->FindObject(Form("fTimeVSAmplitude%d",ipmt)))->Clone(Form("E%d",ipmt));
int nbinsX = fTimeVSAmplitude[ipmt-1]->GetNbinsX();
int nbinsY = fTimeVSAmplitude[ipmt-1]->GetNbinsY();
//Amplitude
fAmplitude[ipmt-1] = (TH1D*) fTimeVSAmplitude[ipmt-1]->ProjectionX(Form("fAmplitude%d",ipmt), 1, nbinsY);
meanAmplitude[ipmt-1] = -9999; //dummy init
if(fAmplitude[ipmt-1]->GetEntries()>0){
meanAmplitude[ipmt-1] = fAmplitude[ipmt-1]->GetMean();
}
//Time
fTime[ipmt-1] = (TH1D*) fTimeVSAmplitude[ipmt-1]->ProjectionY(Form("fTime%d",ipmt), 1, nbinsX);
meanTime[ipmt-1] = -9999; //dummy init
if(fTime[ipmt-1]->GetEntries()>0){
if(fTime[ipmt-1]->GetEntries()>20){
meanTime[ipmt-1] = GetParameterGaus((TH1F*) fTime[ipmt-1], 1); // Mean Time
}else if(fTime[ipmt-1]->GetEntries()>0){
meanTime[ipmt-1] = fTime[ipmt-1]->GetMean();
}
}
}
if(fResolution->GetEntries()>20){
resolutionSigma = GetParameterGaus(fResolution, 2); //gaussian sigma
}else if(fResolution->GetEntries()>0){
resolutionSigma = fResolution->GetRMS(); //gaussian sigma
}
if(fTzeroORAplusORC->GetEntries()>20){
tzeroOrAPlusOrC = GetParameterGaus(fTzeroORAplusORC, 1); //gaussian mean
}else if(fTzeroORAplusORC->GetEntries()>0){
tzeroOrAPlusOrC = fTzeroORAplusORC->GetMean();
}
if(fTzeroORA->GetEntries()>20){
tzeroOrA = GetParameterGaus(fTzeroORA, 1); //gaussian mean
}else if(fTzeroORA->GetEntries()>0){
tzeroOrA = fTzeroORA->GetMean();
}
if(fTzeroORC->GetEntries()>20){
tzeroOrC = GetParameterGaus(fTzeroORC, 1); //gaussian mean
}else if(fTzeroORC->GetEntries()>0){
tzeroOrC = fTzeroORC->GetMean(); //gaussian mean
}
//-----> analyze the new histogram here and set mean/sigma
f->Close();
//-------------------- READ OCDB TIME DELAYS ---------------------------
// Arguments:
AliCDBManager* man = AliCDBManager::Instance();
man->SetDefaultStorage("raw://");
man->SetRun(run);
AliCDBEntry *entry = AliCDBManager::Instance()->Get("T0/Calib/TimeDelay");
AliT0CalibTimeEq *clb = (AliT0CalibTimeEq*)entry->GetObject();
for (Int_t i=0; i<NPMTs; i++){
timeDelayOCDB[i] = 0;
if(clb)
timeDelayOCDB[i] = clb->GetCFDvalue(i,0);
}
//--------------- write walues to the output ------------
TTreeSRedirector* pcstream = NULL;
pcstream = new TTreeSRedirector(outfile);
if (!pcstream) return;
TFile *x = pcstream->GetFile();
x->cd();
TObjString runType;
Int_t startTimeGRP=0;
Int_t stopTimeGRP=0;
Int_t time=0;
Int_t duration=0;
time = (startTimeGRP+stopTimeGRP)/2;
duration = (stopTimeGRP-startTimeGRP);
(*pcstream)<<"t0QA"<<
"run="<<run;//<<
//"time="<<time<<
// "startTimeGRP="<<startTimeGRP<<
// "stopTimeGRP="<<stopTimeGRP<<
/// "duration="<<duration<<
// "runType.="<<&runType;
(*pcstream)<<"t0QA"<<
"resolution="<< resolutionSigma<<
"tzeroOrAPlusOrC="<< tzeroOrAPlusOrC<<
"tzeroOrA="<< tzeroOrA<<
"tzeroOrC="<< tzeroOrC<<
"amplPMT1="<<meanAmplitude[0]<<
"amplPMT2="<<meanAmplitude[1]<<
"amplPMT3="<<meanAmplitude[2]<<
"amplPMT4="<<meanAmplitude[3]<<
"amplPMT5="<<meanAmplitude[4]<<
"amplPMT6="<<meanAmplitude[5]<<
"amplPMT7="<<meanAmplitude[6]<<
"amplPMT8="<<meanAmplitude[7]<<
"amplPMT9="<<meanAmplitude[8]<<
"amplPMT10="<<meanAmplitude[9]<<
"amplPMT11="<<meanAmplitude[10]<<
"amplPMT12="<<meanAmplitude[11]<<
"amplPMT13="<<meanAmplitude[12]<<
"amplPMT14="<<meanAmplitude[13]<<
"amplPMT15="<<meanAmplitude[14]<<
"amplPMT16="<<meanAmplitude[15]<<
"amplPMT17="<<meanAmplitude[16]<<
"amplPMT18="<<meanAmplitude[17]<<
"amplPMT19="<<meanAmplitude[18]<<
"amplPMT20="<<meanAmplitude[19]<<
"amplPMT21="<<meanAmplitude[20]<<
"amplPMT22="<<meanAmplitude[21]<<
"amplPMT23="<<meanAmplitude[22]<<
"amplPMT24="<<meanAmplitude[23]<<
"timePMT1="<<meanTime[0]<<
"timePMT2="<<meanTime[1]<<
"timePMT3="<<meanTime[2]<<
"timePMT4="<<meanTime[3]<<
"timePMT5="<<meanTime[4]<<
"timePMT6="<<meanTime[5]<<
"timePMT7="<<meanTime[6]<<
"timePMT8="<<meanTime[7]<<
"timePMT9="<<meanTime[8]<<
"timePMT10="<<meanTime[9]<<
"timePMT11="<<meanTime[10]<<
"timePMT12="<<meanTime[11]<<
"timePMT13="<<meanTime[12]<<
"timePMT14="<<meanTime[13]<<
"timePMT15="<<meanTime[14]<<
"timePMT16="<<meanTime[15]<<
"timePMT17="<<meanTime[16]<<
"timePMT18="<<meanTime[17]<<
"timePMT19="<<meanTime[18]<<
"timePMT20="<<meanTime[19]<<
"timePMT21="<<meanTime[20]<<
"timePMT22="<<meanTime[21]<<
"timePMT23="<<meanTime[22]<<
"timePMT24="<<meanTime[23];
(*pcstream)<<"t0QA"<<
"timeDelayPMT1="<<timeDelayOCDB[0]<<
"timeDelayPMT2="<<timeDelayOCDB[1]<<
"timeDelayPMT3="<<timeDelayOCDB[2]<<
"timeDelayPMT4="<<timeDelayOCDB[3]<<
"timeDelayPMT5="<<timeDelayOCDB[4]<<
"timeDelayPMT6="<<timeDelayOCDB[5]<<
"timeDelayPMT7="<<timeDelayOCDB[6]<<
"timeDelayPMT8="<<timeDelayOCDB[7]<<
"timeDelayPMT9="<<timeDelayOCDB[8]<<
"timeDelayPMT10="<<timeDelayOCDB[9]<<
"timeDelayPMT11="<<timeDelayOCDB[10]<<
"timeDelayPMT12="<<timeDelayOCDB[11]<<
"timeDelayPMT13="<<timeDelayOCDB[12]<<
"timeDelayPMT14="<<timeDelayOCDB[13]<<
"timeDelayPMT15="<<timeDelayOCDB[14]<<
"timeDelayPMT16="<<timeDelayOCDB[15]<<
"timeDelayPMT17="<<timeDelayOCDB[16]<<
"timeDelayPMT18="<<timeDelayOCDB[17]<<
"timeDelayPMT19="<<timeDelayOCDB[18]<<
"timeDelayPMT20="<<timeDelayOCDB[19]<<
"timeDelayPMT21="<<timeDelayOCDB[20]<<
"timeDelayPMT22="<<timeDelayOCDB[21]<<
"timeDelayPMT23="<<timeDelayOCDB[22]<<
"timeDelayPMT24="<<timeDelayOCDB[23];
//-----> add the mean/sigma of the new histogram here
(*pcstream)<<"t0QA"<<"\n";
pcstream->Close();
delete pcstream;
return;
}
//_____________________________________________________________________________
double GetParameterGaus(TH1F *histo, int whichParameter){
int maxBin = histo->GetMaximumBin();
double max = (histo->GetBinContent(maxBin-1) + histo->GetBinContent(maxBin) + histo->GetBinContent(maxBin+1))/3;
double mean = histo->GetBinCenter(maxBin); //mean
double lowfwhm = histo->GetBinCenter(histo->FindFirstBinAbove(max/2));
double highfwhm = histo->GetBinCenter(histo->FindLastBinAbove(max/2));
double sigma = (highfwhm - lowfwhm)/2.35482; //estimate fwhm FWHM = 2.35482*sigma
TF1 *gaussfit = new TF1("gaussfit","gaus", mean - 4*sigma, mean + 4*sigma); // fit in +- 4 sigma window
gaussfit->SetParameters(max, mean, sigma);
if(whichParameter==2)
histo->Fit(gaussfit,"RQNI");
else
histo->Fit(gaussfit,"RQN");
double parValue = gaussfit->GetParameter(whichParameter);
delete gaussfit;
return parValue;
}
|
make the script working
|
make the script working
|
C++
|
bsd-3-clause
|
mkrzewic/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,shahor02/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,miranov25/AliRoot,alisw/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,sebaleh/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,ALICEHLT/AliRoot,ecalvovi/AliRoot,shahor02/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,shahor02/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,shahor02/AliRoot,miranov25/AliRoot,alisw/AliRoot,miranov25/AliRoot,alisw/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot
|
157247f98fcfe73dbb126b740206e8603eb6e002
|
examples/protocols/asio/asio_chat/main/chat_message.hpp
|
examples/protocols/asio/asio_chat/main/chat_message.hpp
|
//
// chat_message.hpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef CHAT_MESSAGE_HPP
#define CHAT_MESSAGE_HPP
#include <cstdio>
#include <cstdlib>
#include <cstring>
class chat_message
{
public:
enum { header_length = 4 };
enum { max_body_length = 512 };
chat_message()
: body_length_(0)
{
}
const char* data() const
{
return data_;
}
char* data()
{
return data_;
}
std::size_t length() const
{
return header_length + body_length_;
}
const char* body() const
{
return data_ + header_length;
}
char* body()
{
return data_ + header_length;
}
std::size_t body_length() const
{
return body_length_;
}
void body_length(std::size_t new_length)
{
body_length_ = new_length;
if (body_length_ > max_body_length)
body_length_ = max_body_length;
}
bool decode_header()
{
char header[header_length + 1] = "";
std::strncat(header, data_, header_length);
body_length_ = std::atoi(header);
if (body_length_ > max_body_length)
{
body_length_ = 0;
return false;
}
return true;
}
void encode_header()
{
char header[header_length + 1] = "";
std::sprintf(header, "%4d", static_cast<int>(body_length_));
std::memcpy(data_, header, header_length);
}
private:
char data_[header_length + max_body_length];
std::size_t body_length_;
};
#endif // CHAT_MESSAGE_HPP
|
//
// chat_message.hpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef CHAT_MESSAGE_HPP
#define CHAT_MESSAGE_HPP
#include <cstdio>
#include <cstdlib>
#include <cstring>
class chat_message
{
public:
static constexpr std::size_t header_length = 4;
static constexpr std::size_t max_body_length = 512;
chat_message()
: body_length_(0)
{
}
const char* data() const
{
return data_;
}
char* data()
{
return data_;
}
std::size_t length() const
{
return header_length + body_length_;
}
const char* body() const
{
return data_ + header_length;
}
char* body()
{
return data_ + header_length;
}
std::size_t body_length() const
{
return body_length_;
}
void body_length(std::size_t new_length)
{
body_length_ = new_length;
if (body_length_ > max_body_length)
body_length_ = max_body_length;
}
bool decode_header()
{
char header[header_length + 1] = "";
std::strncat(header, data_, header_length);
body_length_ = std::atoi(header);
if (body_length_ > max_body_length)
{
body_length_ = 0;
return false;
}
return true;
}
void encode_header()
{
char header[header_length + 1] = "";
std::sprintf(header, "%4d", static_cast<int>(body_length_));
std::memcpy(data_, header, header_length);
}
private:
char data_[header_length + max_body_length];
std::size_t body_length_;
};
#endif // CHAT_MESSAGE_HPP
|
fix example for compatibility with C++20
|
asio: fix example for compatibility with C++20
Fix deprecated-enum-enum-conversion warning when compiling the
example with C++20
|
C++
|
apache-2.0
|
espressif/esp-idf,espressif/esp-idf,espressif/esp-idf,espressif/esp-idf
|
e7fbd026b227d72982daf60d1cee3e3d7e799b42
|
core/metrics_registration.hh
|
core/metrics_registration.hh
|
/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2016 ScyllaDB.
*/
#pragma once
/*!
* \file metrics_registration.hh
* \brief holds the metric_groups definition needed by class that reports metrics
*
* If class A needs to report metrics,
* typically you include metrics_registration.hh, in A header file and add to A:
* * metric_groups _metrics as a member
* * set_metrics() method that would be called in the constructor.
* \code
* class A {
* metric_groups _metrics
*
* void setup_metrics();
*
* };
* \endcode
* To define the metrics, include in your source file metircs.hh
* @see metrics.hh for the definition for adding a metric.
*/
namespace seastar {
namespace metrics {
namespace impl {
class metric_groups_def;
struct metric_definition_impl;
class metric_groups_impl;
}
using group_name_type = sstring; /*!< A group of logically related metrics */
class metric_groups;
class metric_definition {
std::unique_ptr<impl::metric_definition_impl> _impl;
public:
metric_definition(const impl::metric_definition_impl& impl) noexcept;
metric_definition(metric_definition&& m) noexcept;
~metric_definition();
friend metric_groups;
friend impl::metric_groups_impl;
};
class metric_group_definition {
public:
group_name_type name;
std::initializer_list<metric_definition> metrics;
metric_group_definition(const group_name_type& name, std::initializer_list<metric_definition> l);
metric_group_definition(const metric_group_definition&) = delete;
~metric_group_definition();
};
/*!
* metric_groups
* \brief holds the metric definition.
*
* Add multiple metric groups definitions.
* Initialization can be done in the constructor or with a call to add_group
* @see metrics.hh for example and supported metrics
*/
class metric_groups {
std::unique_ptr<impl::metric_groups_def> _impl;
public:
metric_groups() noexcept;
metric_groups(metric_groups&&) = default;
virtual ~metric_groups();
/*!
* \brief add metrics belong to the same group in the constructor.
*
* combine the constructor with the add_group functionality.
*/
metric_groups(std::initializer_list<metric_group_definition> mg);
/*!
* \brief add metrics belong to the same group.
*
* use the metrics creation functions to add metrics.
*
* for example:
* _metrics.add_group("my_group", {
* make_counter("my_counter_name1", counter, description("my counter description")),
* make_counter("my_counter_name2", counter, description("my second counter description")),
* make_gauge("my_gauge_name1", gauge, description("my gauge description")),
* });
*
* metric name should be unique inside the group.
* you can change add_group calls like:
* _metrics.add_group("my group1", {...}).add_group("my group2", {...});
*/
metric_groups& add_group(const group_name_type& name, const std::initializer_list<metric_definition>& l);
/*!
* \brief clear all metrics groups registrations.
*/
void clear();
};
/*!
* \brief hold a single metric group
* Initialization is done in the constructor or
* with a call to add_group
*/
class metric_group : public metric_groups {
public:
metric_group() noexcept;
metric_group(const metric_group&) = delete;
metric_group(metric_group&&) = default;
virtual ~metric_group();
/*!
* \brief add metrics belong to the same group in the constructor.
*
*
*/
metric_group(const group_name_type& name, std::initializer_list<metric_definition> l);
};
}
}
|
/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2016 ScyllaDB.
*/
#pragma once
/*!
* \file metrics_registration.hh
* \brief holds the metric_groups definition needed by class that reports metrics
*
* If class A needs to report metrics,
* typically you include metrics_registration.hh, in A header file and add to A:
* * metric_groups _metrics as a member
* * set_metrics() method that would be called in the constructor.
* \code
* class A {
* metric_groups _metrics
*
* void setup_metrics();
*
* };
* \endcode
* To define the metrics, include in your source file metircs.hh
* @see metrics.hh for the definition for adding a metric.
*/
namespace seastar {
namespace metrics {
namespace impl {
class metric_groups_def;
struct metric_definition_impl;
class metric_groups_impl;
}
using group_name_type = sstring; /*!< A group of logically related metrics */
class metric_groups;
class metric_definition {
std::unique_ptr<impl::metric_definition_impl> _impl;
public:
metric_definition(const impl::metric_definition_impl& impl) noexcept;
metric_definition(metric_definition&& m) noexcept;
~metric_definition();
friend metric_groups;
friend impl::metric_groups_impl;
};
class metric_group_definition {
public:
group_name_type name;
std::initializer_list<metric_definition> metrics;
metric_group_definition(const group_name_type& name, std::initializer_list<metric_definition> l);
metric_group_definition(const metric_group_definition&) = delete;
~metric_group_definition();
};
/*!
* metric_groups
* \brief holds the metric definition.
*
* Add multiple metric groups definitions.
* Initialization can be done in the constructor or with a call to add_group
* @see metrics.hh for example and supported metrics
*/
class metric_groups {
std::unique_ptr<impl::metric_groups_def> _impl;
public:
metric_groups() noexcept;
metric_groups(metric_groups&&) = default;
virtual ~metric_groups();
metric_groups& operator=(metric_groups&&) = default;
/*!
* \brief add metrics belong to the same group in the constructor.
*
* combine the constructor with the add_group functionality.
*/
metric_groups(std::initializer_list<metric_group_definition> mg);
/*!
* \brief add metrics belong to the same group.
*
* use the metrics creation functions to add metrics.
*
* for example:
* _metrics.add_group("my_group", {
* make_counter("my_counter_name1", counter, description("my counter description")),
* make_counter("my_counter_name2", counter, description("my second counter description")),
* make_gauge("my_gauge_name1", gauge, description("my gauge description")),
* });
*
* metric name should be unique inside the group.
* you can change add_group calls like:
* _metrics.add_group("my group1", {...}).add_group("my group2", {...});
*/
metric_groups& add_group(const group_name_type& name, const std::initializer_list<metric_definition>& l);
/*!
* \brief clear all metrics groups registrations.
*/
void clear();
};
/*!
* \brief hold a single metric group
* Initialization is done in the constructor or
* with a call to add_group
*/
class metric_group : public metric_groups {
public:
metric_group() noexcept;
metric_group(const metric_group&) = delete;
metric_group(metric_group&&) = default;
virtual ~metric_group();
metric_group& operator=(metric_group&&) = default;
/*!
* \brief add metrics belong to the same group in the constructor.
*
*
*/
metric_group(const group_name_type& name, std::initializer_list<metric_definition> l);
};
}
}
|
add missing move assignment operators for metric_group, metric_groups
|
metrics: add missing move assignment operators for metric_group, metric_groups
|
C++
|
apache-2.0
|
cloudius-systems/seastar,scylladb/seastar,avikivity/seastar,avikivity/seastar,dreamsxin/seastar,syuu1228/seastar,dreamsxin/seastar,dreamsxin/seastar,cloudius-systems/seastar,scylladb/seastar,syuu1228/seastar,scylladb/seastar,cloudius-systems/seastar,syuu1228/seastar,avikivity/seastar
|
00f0859e1fe9d87be2917c2abed0476271398f70
|
benchmark/parsingcompetition.cpp
|
benchmark/parsingcompetition.cpp
|
#include "simdjson.h"
#ifndef _MSC_VER
#include "linux-perf-events.h"
#include <unistd.h>
#ifdef __linux__
#include <libgen.h>
#endif //__linux__
#endif // _MSC_VER
#include <memory>
#include "benchmark.h"
// #define RAPIDJSON_SSE2 // bad for performance
// #define RAPIDJSON_SSE42 // bad for performance
#include "rapidjson/document.h"
#include "rapidjson/reader.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "sajson.h"
#include <nlohmann/json.hpp>
using json = nlohmann::json;
#ifdef ALLPARSER
#include "fastjson.cpp"
#include "fastjson_dom.cpp"
#include "gason.cpp"
#include "json11.cpp"
extern "C" {
#include "cJSON.c"
#include "cJSON.h"
#include "jsmn.c"
#include "jsmn.h"
#include "ujdecode.h"
#include "ultrajsondec.c"
}
#include "jsoncpp.cpp"
#include "json/json.h"
#endif
using namespace rapidjson;
#ifdef ALLPARSER
// fastjson has a tricky interface
void on_json_error(void *, UNUSED const fastjson::ErrorContext &ec) {
// std::cerr<<"ERROR: "<<ec.mesg<<std::endl;
}
bool fastjson_parse(const char *input) {
fastjson::Token token;
fastjson::dom::Chunk chunk;
return fastjson::dom::parse_string(input, &token, &chunk, 0, &on_json_error,
NULL);
}
// end of fastjson stuff
#endif
size_t sum_line_lengths(char * data, size_t length) {
std::stringstream is;
is.rdbuf()->pubsetbuf(data, length);
std::string line;
size_t sumofalllinelengths{0};
while(getline(is, line)) {
sumofalllinelengths += line.size();
}
return sumofalllinelengths;
}
int main(int argc, char *argv[]) {
bool verbose = false;
bool just_data = false;
int c;
while ((c = getopt(argc, argv, "vt")) != -1)
switch (c) {
case 't':
just_data = true;
break;
case 'v':
verbose = true;
break;
default:
abort();
}
if (optind >= argc) {
std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl;
std::cerr << "Or " << argv[0] << " -v <jsonfile>" << std::endl;
std::cerr << "The '-t' flag outputs a table. " << std::endl;
exit(1);
}
const char *filename = argv[optind];
if (optind + 1 < argc) {
std::cerr << "warning: ignoring everything after " << argv[optind + 1]
<< std::endl;
}
simdjson::padded_string p;
try {
simdjson::get_corpus(filename).swap(p);
} catch (const std::exception &e) { // caught by reference to base
std::cout << "Could not load the file " << filename << std::endl;
return EXIT_FAILURE;
}
if (verbose) {
std::cout << "Input has ";
if (p.size() > 1024 * 1024)
std::cout << p.size() / (1024 * 1024) << " MB ";
else if (p.size() > 1024)
std::cout << p.size() / 1024 << " KB ";
else
std::cout << p.size() << " B ";
std::cout << std::endl;
}
simdjson::ParsedJson pj;
bool allocok = pj.allocate_capacity(p.size(), 1024);
if (!allocok) {
std::cerr << "can't allocate memory" << std::endl;
return EXIT_FAILURE;
}
int repeat = (p.size() < 1 * 1000 * 1000 ? 1000 : 10);
int volume = p.size();
if (just_data) {
printf("%-42s %20s %20s %20s %20s \n", "name", "cycles_per_byte",
"cycles_per_byte_err", "gb_per_s", "gb_per_s_err");
}
if (!just_data) {
size_t lc = sum_line_lengths(p.data(), p.size());
BEST_TIME("getline ",sum_line_lengths(p.data(), p.size()) , lc, ,
repeat, volume, !just_data);
}
if (!just_data)
BEST_TIME("simdjson (dynamic mem) ", build_parsed_json(p).is_valid(), true,
, repeat, volume, !just_data);
// (static alloc)
BEST_TIME("simdjson ", json_parse(p, pj), simdjson::SUCCESS, , repeat, volume,
!just_data);
rapidjson::Document d;
char *buffer = (char *)malloc(p.size() + 1);
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
#ifndef ALLPARSER
if (!just_data)
#endif
BEST_TIME("RapidJSON ",
d.Parse<kParseValidateEncodingFlag>((const char *)buffer)
.HasParseError(),
false, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
BEST_TIME("RapidJSON (insitu)",
d.ParseInsitu<kParseValidateEncodingFlag>(buffer).HasParseError(),
false,
memcpy(buffer, p.data(), p.size()) && (buffer[p.size()] = '\0'),
repeat, volume, !just_data);
#ifndef ALLPARSER
if (!just_data)
#endif
BEST_TIME("sajson (dynamic mem)",
sajson::parse(sajson::dynamic_allocation(),
sajson::mutable_string_view(p.size(), buffer))
.is_valid(),
true, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
size_t ast_buffer_size = p.size();
size_t *ast_buffer = (size_t *)malloc(ast_buffer_size * sizeof(size_t));
// (static alloc, insitu)
BEST_TIME(
"sajson",
sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),
sajson::mutable_string_view(p.size(), buffer))
.is_valid(),
true, memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);
size_t expected = json::parse(p.data(), p.data() + p.size()).size();
BEST_TIME("nlohmann-json", json::parse(buffer, buffer + p.size()).size(),
expected, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
#ifdef ALLPARSER
std::string json11err;
BEST_TIME("dropbox (json11) ",
((json11::Json::parse(buffer, json11err).is_null()) ||
(!json11err.empty())),
false, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
BEST_TIME("fastjson ", fastjson_parse(buffer), true,
memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);
JsonValue value;
JsonAllocator allocator;
char *endptr;
BEST_TIME("gason ", jsonParse(buffer, &endptr, &value, allocator),
JSON_OK, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
void *state;
BEST_TIME("ultrajson ",
(UJDecode(buffer, p.size(), NULL, &state) == NULL), false,
memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);
{
std::unique_ptr<jsmntok_t[]> tokens =
std::make_unique<jsmntok_t[]>(p.size());
jsmn_parser parser;
jsmn_init(&parser);
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
BEST_TIME(
"jsmn ",
(jsmn_parse(&parser, buffer, p.size(), tokens.get(), p.size()) > 0),
true, jsmn_init(&parser), repeat, volume, !just_data);
}
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
cJSON *tree = cJSON_Parse(buffer);
BEST_TIME("cJSON ", ((tree = cJSON_Parse(buffer)) != NULL), true,
cJSON_Delete(tree), repeat, volume, !just_data);
cJSON_Delete(tree);
Json::CharReaderBuilder b;
Json::CharReader *json_cpp_reader = b.newCharReader();
Json::Value root;
Json::String errs;
BEST_TIME("jsoncpp ",
json_cpp_reader->parse(buffer, buffer + volume, &root, &errs), true,
, repeat, volume, !just_data);
delete json_cpp_reader;
#endif
if (!just_data)
BEST_TIME("memcpy ",
(memcpy(buffer, p.data(), p.size()) == buffer), true, , repeat,
volume, !just_data);
#ifdef __linux__
if (!just_data) {
printf("\n \n <doing additional analysis with performance counters (Linux "
"only)>\n");
std::vector<int> evts;
evts.push_back(PERF_COUNT_HW_CPU_CYCLES);
evts.push_back(PERF_COUNT_HW_INSTRUCTIONS);
evts.push_back(PERF_COUNT_HW_BRANCH_MISSES);
evts.push_back(PERF_COUNT_HW_CACHE_REFERENCES);
evts.push_back(PERF_COUNT_HW_CACHE_MISSES);
LinuxEvents<PERF_TYPE_HARDWARE> unified(evts);
std::vector<unsigned long long> results;
std::vector<unsigned long long> stats;
results.resize(evts.size());
stats.resize(evts.size());
std::fill(stats.begin(), stats.end(), 0); // unnecessary
for (int i = 0; i < repeat; i++) {
unified.start();
if (json_parse(p, pj) != simdjson::SUCCESS)
printf("bug\n");
unified.end(results);
std::transform(stats.begin(), stats.end(), results.begin(), stats.begin(),
std::plus<unsigned long long>());
}
printf("simdjson : cycles %10.0f instructions %10.0f branchmisses %10.0f "
"cacheref %10.0f cachemisses %10.0f bytespercachemiss %10.0f "
"inspercycle %10.1f insperbyte %10.1f\n",
stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat,
stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat,
stats[4] * 1.0 / repeat, volume * repeat * 1.0 / stats[2],
stats[1] * 1.0 / stats[0], stats[1] * 1.0 / (volume * repeat));
std::fill(stats.begin(), stats.end(), 0);
for (int i = 0; i < repeat; i++) {
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
unified.start();
if (d.ParseInsitu<kParseValidateEncodingFlag>(buffer).HasParseError() !=
false)
printf("bug\n");
unified.end(results);
std::transform(stats.begin(), stats.end(), results.begin(), stats.begin(),
std::plus<unsigned long long>());
}
printf("RapidJSON: cycles %10.0f instructions %10.0f branchmisses %10.0f "
"cacheref %10.0f cachemisses %10.0f bytespercachemiss %10.0f "
"inspercycle %10.1f insperbyte %10.1f\n",
stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat,
stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat,
stats[4] * 1.0 / repeat, volume * repeat * 1.0 / stats[2],
stats[1] * 1.0 / stats[0], stats[1] * 1.0 / (volume * repeat));
std::fill(stats.begin(), stats.end(), 0); // unnecessary
for (int i = 0; i < repeat; i++) {
memcpy(buffer, p.data(), p.size());
unified.start();
if (sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),
sajson::mutable_string_view(p.size(), buffer))
.is_valid() != true)
printf("bug\n");
unified.end(results);
std::transform(stats.begin(), stats.end(), results.begin(), stats.begin(),
std::plus<unsigned long long>());
}
printf("sajson : cycles %10.0f instructions %10.0f branchmisses %10.0f "
"cacheref %10.0f cachemisses %10.0f bytespercachemiss %10.0f "
"inspercycle %10.1f insperbyte %10.1f\n",
stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat,
stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat,
stats[4] * 1.0 / repeat, volume * repeat * 1.0 / stats[2],
stats[1] * 1.0 / stats[0], stats[1] * 1.0 / (volume * repeat));
}
#endif // __linux__
free(ast_buffer);
free(buffer);
}
|
#include "simdjson.h"
#ifndef _MSC_VER
#include "linux-perf-events.h"
#include <unistd.h>
#ifdef __linux__
#include <libgen.h>
#endif //__linux__
#endif // _MSC_VER
#include <memory>
#include "benchmark.h"
// #define RAPIDJSON_SSE2 // bad for performance
// #define RAPIDJSON_SSE42 // bad for performance
#include "rapidjson/document.h"
#include "rapidjson/reader.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "sajson.h"
#include <nlohmann/json.hpp>
using json = nlohmann::json;
#ifdef ALLPARSER
#include "fastjson.cpp"
#include "fastjson_dom.cpp"
#include "gason.cpp"
#include "json11.cpp"
extern "C" {
#include "cJSON.c"
#include "cJSON.h"
#include "jsmn.c"
#include "jsmn.h"
#include "ujdecode.h"
#include "ultrajsondec.c"
}
#include "jsoncpp.cpp"
#include "json/json.h"
#endif
using namespace rapidjson;
#ifdef ALLPARSER
// fastjson has a tricky interface
void on_json_error(void *, UNUSED const fastjson::ErrorContext &ec) {
// std::cerr<<"ERROR: "<<ec.mesg<<std::endl;
}
bool fastjson_parse(const char *input) {
fastjson::Token token;
fastjson::dom::Chunk chunk;
return fastjson::dom::parse_string(input, &token, &chunk, 0, &on_json_error,
NULL);
}
// end of fastjson stuff
#endif
size_t sum_line_lengths(char * data, size_t length) {
std::stringstream is;
is.rdbuf()->pubsetbuf(data, length);
std::string line;
size_t sumofalllinelengths{0};
while(getline(is, line)) {
sumofalllinelengths += line.size();
}
return sumofalllinelengths;
}
bool bench(const char *filename, bool verbose, bool just_data, int repeat_multiplier) {
simdjson::padded_string p;
try {
simdjson::get_corpus(filename).swap(p);
} catch (const std::exception &e) { // caught by reference to base
std::cout << "Could not load the file " << filename << std::endl;
return false;
}
int repeat = (50000000 * repeat_multiplier) / p.size();
if (repeat < 10) { repeat = 10; }
if (verbose) {
std::cout << "Input " << filename << " has ";
if (p.size() > 1024 * 1024)
std::cout << p.size() / (1024 * 1024) << " MB";
else if (p.size() > 1024)
std::cout << p.size() / 1024 << " KB";
else
std::cout << p.size() << " B";
std::cout << ": will run " << repeat << " iterations." << std::endl;
}
simdjson::ParsedJson pj;
bool allocok = pj.allocate_capacity(p.size(), 1024);
if (!allocok) {
std::cerr << "can't allocate memory" << std::endl;
return false;
}
int volume = p.size();
if (just_data) {
printf("%-42s %20s %20s %20s %20s \n", "name", "cycles_per_byte",
"cycles_per_byte_err", "gb_per_s", "gb_per_s_err");
}
if (!just_data) {
size_t lc = sum_line_lengths(p.data(), p.size());
BEST_TIME("getline ",sum_line_lengths(p.data(), p.size()) , lc, ,
repeat, volume, !just_data);
}
if (!just_data)
BEST_TIME("simdjson (dynamic mem) ", build_parsed_json(p).is_valid(), true,
, repeat, volume, !just_data);
// (static alloc)
BEST_TIME("simdjson ", json_parse(p, pj), simdjson::SUCCESS, , repeat, volume,
!just_data);
rapidjson::Document d;
char *buffer = (char *)malloc(p.size() + 1);
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
#ifndef ALLPARSER
if (!just_data)
#endif
BEST_TIME("RapidJSON ",
d.Parse<kParseValidateEncodingFlag>((const char *)buffer)
.HasParseError(),
false, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
BEST_TIME("RapidJSON (insitu)",
d.ParseInsitu<kParseValidateEncodingFlag>(buffer).HasParseError(),
false,
memcpy(buffer, p.data(), p.size()) && (buffer[p.size()] = '\0'),
repeat, volume, !just_data);
#ifndef ALLPARSER
if (!just_data)
#endif
BEST_TIME("sajson (dynamic mem)",
sajson::parse(sajson::dynamic_allocation(),
sajson::mutable_string_view(p.size(), buffer))
.is_valid(),
true, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
size_t ast_buffer_size = p.size();
size_t *ast_buffer = (size_t *)malloc(ast_buffer_size * sizeof(size_t));
// (static alloc, insitu)
BEST_TIME(
"sajson",
sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),
sajson::mutable_string_view(p.size(), buffer))
.is_valid(),
true, memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);
size_t expected = json::parse(p.data(), p.data() + p.size()).size();
BEST_TIME("nlohmann-json", json::parse(buffer, buffer + p.size()).size(),
expected, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
#ifdef ALLPARSER
std::string json11err;
BEST_TIME("dropbox (json11) ",
((json11::Json::parse(buffer, json11err).is_null()) ||
(!json11err.empty())),
false, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
BEST_TIME("fastjson ", fastjson_parse(buffer), true,
memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);
JsonValue value;
JsonAllocator allocator;
char *endptr;
BEST_TIME("gason ", jsonParse(buffer, &endptr, &value, allocator),
JSON_OK, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
void *state;
BEST_TIME("ultrajson ",
(UJDecode(buffer, p.size(), NULL, &state) == NULL), false,
memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);
{
std::unique_ptr<jsmntok_t[]> tokens =
std::make_unique<jsmntok_t[]>(p.size());
jsmn_parser parser;
jsmn_init(&parser);
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
BEST_TIME(
"jsmn ",
(jsmn_parse(&parser, buffer, p.size(), tokens.get(), p.size()) > 0),
true, jsmn_init(&parser), repeat, volume, !just_data);
}
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
cJSON *tree = cJSON_Parse(buffer);
BEST_TIME("cJSON ", ((tree = cJSON_Parse(buffer)) != NULL), true,
cJSON_Delete(tree), repeat, volume, !just_data);
cJSON_Delete(tree);
Json::CharReaderBuilder b;
Json::CharReader *json_cpp_reader = b.newCharReader();
Json::Value root;
Json::String errs;
BEST_TIME("jsoncpp ",
json_cpp_reader->parse(buffer, buffer + volume, &root, &errs), true,
, repeat, volume, !just_data);
delete json_cpp_reader;
#endif
if (!just_data)
BEST_TIME("memcpy ",
(memcpy(buffer, p.data(), p.size()) == buffer), true, , repeat,
volume, !just_data);
#ifdef __linux__
if (!just_data) {
printf("\n \n <doing additional analysis with performance counters (Linux "
"only)>\n");
std::vector<int> evts;
evts.push_back(PERF_COUNT_HW_CPU_CYCLES);
evts.push_back(PERF_COUNT_HW_INSTRUCTIONS);
evts.push_back(PERF_COUNT_HW_BRANCH_MISSES);
evts.push_back(PERF_COUNT_HW_CACHE_REFERENCES);
evts.push_back(PERF_COUNT_HW_CACHE_MISSES);
LinuxEvents<PERF_TYPE_HARDWARE> unified(evts);
std::vector<unsigned long long> results;
std::vector<unsigned long long> stats;
results.resize(evts.size());
stats.resize(evts.size());
std::fill(stats.begin(), stats.end(), 0); // unnecessary
for (int i = 0; i < repeat; i++) {
unified.start();
if (json_parse(p, pj) != simdjson::SUCCESS)
printf("bug\n");
unified.end(results);
std::transform(stats.begin(), stats.end(), results.begin(), stats.begin(),
std::plus<unsigned long long>());
}
printf("simdjson : cycles %10.0f instructions %10.0f branchmisses %10.0f "
"cacheref %10.0f cachemisses %10.0f bytespercachemiss %10.0f "
"inspercycle %10.1f insperbyte %10.1f\n",
stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat,
stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat,
stats[4] * 1.0 / repeat, volume * repeat * 1.0 / stats[2],
stats[1] * 1.0 / stats[0], stats[1] * 1.0 / (volume * repeat));
std::fill(stats.begin(), stats.end(), 0);
for (int i = 0; i < repeat; i++) {
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
unified.start();
if (d.ParseInsitu<kParseValidateEncodingFlag>(buffer).HasParseError() !=
false)
printf("bug\n");
unified.end(results);
std::transform(stats.begin(), stats.end(), results.begin(), stats.begin(),
std::plus<unsigned long long>());
}
printf("RapidJSON: cycles %10.0f instructions %10.0f branchmisses %10.0f "
"cacheref %10.0f cachemisses %10.0f bytespercachemiss %10.0f "
"inspercycle %10.1f insperbyte %10.1f\n",
stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat,
stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat,
stats[4] * 1.0 / repeat, volume * repeat * 1.0 / stats[2],
stats[1] * 1.0 / stats[0], stats[1] * 1.0 / (volume * repeat));
std::fill(stats.begin(), stats.end(), 0); // unnecessary
for (int i = 0; i < repeat; i++) {
memcpy(buffer, p.data(), p.size());
unified.start();
if (sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),
sajson::mutable_string_view(p.size(), buffer))
.is_valid() != true)
printf("bug\n");
unified.end(results);
std::transform(stats.begin(), stats.end(), results.begin(), stats.begin(),
std::plus<unsigned long long>());
}
printf("sajson : cycles %10.0f instructions %10.0f branchmisses %10.0f "
"cacheref %10.0f cachemisses %10.0f bytespercachemiss %10.0f "
"inspercycle %10.1f insperbyte %10.1f\n",
stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat,
stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat,
stats[4] * 1.0 / repeat, volume * repeat * 1.0 / stats[2],
stats[1] * 1.0 / stats[0], stats[1] * 1.0 / (volume * repeat));
}
#endif // __linux__
free(ast_buffer);
free(buffer);
return true;
}
int main(int argc, char *argv[]) {
bool verbose = false;
bool just_data = false;
double repeat_multiplier = 1;
int c;
while ((c = getopt(argc, argv, "r:vt")) != -1)
switch (c) {
case 'r':
repeat_multiplier = atof(optarg);
break;
case 't':
just_data = true;
break;
case 'v':
verbose = true;
break;
default:
abort();
}
if (optind >= argc) {
std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl;
std::cerr << "Or " << argv[0] << " -v <jsonfile>" << std::endl;
std::cerr << "The '-t' flag outputs a table." << std::endl;
std::cerr << "The '-r <N>' flag sets the repeat multiplier: set it above 1 to do more iterations, and below 1 to do fewer." << std::endl;
exit(1);
}
int result = EXIT_SUCCESS;
for (int fileind = optind; fileind < argc; fileind++) {
if (!bench(argv[fileind], verbose, just_data, repeat_multiplier)) { result = EXIT_FAILURE; }
printf("\n\n");
}
return result;
}
|
Add ability to run multiple files
|
Add ability to run multiple files
|
C++
|
apache-2.0
|
lemire/simdjson,lemire/simdjson,lemire/simdjson,lemire/simdjson,lemire/simdjson,lemire/simdjson
|
fac840b6a8740536212242dbf9ecf1d35df312a1
|
cores/esp8266/spiffs_hal.cpp
|
cores/esp8266/spiffs_hal.cpp
|
/*
spiffs_hal.cpp - SPI read/write/erase functions for SPIFFS.
Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <Arduino.h>
#include <stdlib.h>
#include <algorithm>
#include "spiffs/spiffs.h"
#include "debug.h"
#include "interrupts.h"
extern "C" {
#include "c_types.h"
#include "spi_flash.h"
}
static int spi_flash_read_locked(uint32_t addr, uint32_t* dst, uint32_t size) {
InterruptLock lock;
return spi_flash_read(addr, dst, size);
}
static int spi_flash_write_locked(uint32_t addr, const uint32_t* src, uint32_t size) {
InterruptLock lock;
return spi_flash_write(addr, (uint32_t*) src, size);
}
static int spi_flash_erase_sector_locked(uint32_t sector) {
optimistic_yield(10000);
InterruptLock lock;
return spi_flash_erase_sector(sector);
}
/*
spi_flash_read function requires flash address to be aligned on word boundary.
We take care of this by reading first and last words separately and memcpy
relevant bytes into result buffer.
alignment: 012301230123012301230123
bytes requested: -------***********------
read directly: --------xxxxxxxx--------
read pre: ----aaaa----------------
read post: ----------------bbbb----
alignedBegin: ^
alignedEnd: ^
*/
int32_t spiffs_hal_read(uint32_t addr, uint32_t size, uint8_t *dst) {
uint32_t result = SPIFFS_OK;
uint32_t alignedBegin = (addr + 3) & (~3);
uint32_t alignedEnd = (addr + size) & (~3);
if (addr < alignedBegin) {
uint32_t nb = alignedBegin - addr;
uint32_t tmp;
if (spi_flash_read_locked(alignedBegin - 4, &tmp, 4) != SPI_FLASH_RESULT_OK) {
DEBUGV("_spif_read(%d) addr=%x size=%x ab=%x ae=%x\r\n",
__LINE__, addr, size, alignedBegin, alignedEnd);
return SPIFFS_ERR_INTERNAL;
}
memcpy(dst, &tmp + 4 - nb, nb);
}
if (alignedEnd != alignedBegin) {
if (spi_flash_read_locked(alignedBegin, (uint32_t*) (dst + alignedBegin - addr),
alignedEnd - alignedBegin) != SPI_FLASH_RESULT_OK) {
DEBUGV("_spif_read(%d) addr=%x size=%x ab=%x ae=%x\r\n",
__LINE__, addr, size, alignedBegin, alignedEnd);
return SPIFFS_ERR_INTERNAL;
}
}
if (addr + size > alignedEnd) {
uint32_t nb = addr + size - alignedEnd;
uint32_t tmp;
if (spi_flash_read_locked(alignedEnd, &tmp, 4) != SPI_FLASH_RESULT_OK) {
DEBUGV("_spif_read(%d) addr=%x size=%x ab=%x ae=%x\r\n",
__LINE__, addr, size, alignedBegin, alignedEnd);
return SPIFFS_ERR_INTERNAL;
}
memcpy(dst + size - nb, &tmp, nb);
}
return result;
}
/*
Like spi_flash_read, spi_flash_write has a requirement for flash address to be
aligned. However it also requires RAM address to be aligned as it reads data
in 32-bit words. Flash address (mis-)alignment is handled much the same way
as for reads, but for RAM alignment we have to copy data into a temporary
buffer. The size of this buffer is a tradeoff between number of writes required
and amount of stack required. This is chosen to be 512 bytes here, but might
be adjusted in the future if there are good reasons to do so.
*/
static const int UNALIGNED_WRITE_BUFFER_SIZE = 512;
int32_t spiffs_hal_write(uint32_t addr, uint32_t size, uint8_t *src) {
uint32_t alignedBegin = (addr + 3) & (~3);
uint32_t alignedEnd = (addr + size) & (~3);
if (addr < alignedBegin) {
uint32_t nb = alignedBegin - addr;
uint32_t tmp = 0xffffffff;
memcpy(((uint8_t* )&tmp) + 4 - nb, src, nb);
if (spi_flash_write_locked(alignedBegin - 4, &tmp, 4) != SPI_FLASH_RESULT_OK) {
DEBUGV("_spif_write(%d) addr=%x size=%x ab=%x ae=%x\r\n",
__LINE__, addr, size, alignedBegin, alignedEnd);
return SPIFFS_ERR_INTERNAL;
}
}
if (alignedEnd != alignedBegin) {
uint32_t* srcLeftover = (uint32_t*) (src + alignedBegin - addr);
uint32_t srcAlign = ((uint32_t) srcLeftover) & 3;
if (!srcAlign) {
if (spi_flash_write_locked(alignedBegin, (uint32_t*) srcLeftover,
alignedEnd - alignedBegin) != SPI_FLASH_RESULT_OK) {
DEBUGV("_spif_write(%d) addr=%x size=%x ab=%x ae=%x\r\n",
__LINE__, addr, size, alignedBegin, alignedEnd);
return SPIFFS_ERR_INTERNAL;
}
}
else {
uint8_t buf[UNALIGNED_WRITE_BUFFER_SIZE];
for (uint32_t sizeLeft = alignedEnd - alignedBegin; sizeLeft; ) {
size_t willCopy = std::min(sizeLeft, sizeof(buf));
memcpy(buf, srcLeftover, willCopy);
if (spi_flash_write_locked(alignedBegin, (uint32_t*) buf,
willCopy) != SPI_FLASH_RESULT_OK) {
DEBUGV("_spif_write(%d) addr=%x size=%x ab=%x ae=%x\r\n",
__LINE__, addr, size, alignedBegin, alignedEnd);
return SPIFFS_ERR_INTERNAL;
}
sizeLeft -= willCopy;
srcLeftover += willCopy;
alignedBegin += willCopy;
}
}
}
if (addr + size > alignedEnd) {
uint32_t nb = addr + size - alignedEnd;
uint32_t tmp = 0xffffffff;
memcpy(&tmp, src + size - nb, nb);
if (spi_flash_write_locked(alignedEnd, &tmp, 4) != SPI_FLASH_RESULT_OK) {
DEBUGV("_spif_write(%d) addr=%x size=%x ab=%x ae=%x\r\n",
__LINE__, addr, size, alignedBegin, alignedEnd);
return SPIFFS_ERR_INTERNAL;
}
}
return SPIFFS_OK;
}
int32_t spiffs_hal_erase(uint32_t addr, uint32_t size) {
if ((size & (SPI_FLASH_SEC_SIZE - 1)) != 0 ||
(addr & (SPI_FLASH_SEC_SIZE - 1)) != 0) {
DEBUGV("_spif_erase called with addr=%x, size=%d\r\n", addr, size);
abort();
}
const uint32_t sector = addr / SPI_FLASH_SEC_SIZE;
const uint32_t sectorCount = size / SPI_FLASH_SEC_SIZE;
for (uint32_t i = 0; i < sectorCount; ++i) {
if (spi_flash_erase_sector_locked(sector + i) != 0) {
DEBUGV("_spif_erase addr=%x size=%d i=%d\r\n", addr, size, i);
return SPIFFS_ERR_INTERNAL;
}
}
return SPIFFS_OK;
}
|
/*
spiffs_hal.cpp - SPI read/write/erase functions for SPIFFS.
Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <Arduino.h>
#include <stdlib.h>
#include <algorithm>
#include "spiffs/spiffs.h"
#include "debug.h"
#include "interrupts.h"
extern "C" {
#include "c_types.h"
#include "spi_flash.h"
}
static int spi_flash_read_locked(uint32_t addr, uint32_t* dst, uint32_t size) {
optimistic_yield(10000);
AutoInterruptLock(5);
return spi_flash_read(addr, dst, size);
}
static int spi_flash_write_locked(uint32_t addr, const uint32_t* src, uint32_t size) {
optimistic_yield(10000);
AutoInterruptLock(5);
return spi_flash_write(addr, (uint32_t*) src, size);
}
static int spi_flash_erase_sector_locked(uint32_t sector) {
optimistic_yield(10000);
AutoInterruptLock(5);
return spi_flash_erase_sector(sector);
}
/*
spi_flash_read function requires flash address to be aligned on word boundary.
We take care of this by reading first and last words separately and memcpy
relevant bytes into result buffer.
alignment: 012301230123012301230123
bytes requested: -------***********------
read directly: --------xxxxxxxx--------
read pre: ----aaaa----------------
read post: ----------------bbbb----
alignedBegin: ^
alignedEnd: ^
*/
int32_t spiffs_hal_read(uint32_t addr, uint32_t size, uint8_t *dst) {
uint32_t result = SPIFFS_OK;
uint32_t alignedBegin = (addr + 3) & (~3);
uint32_t alignedEnd = (addr + size) & (~3);
if (addr < alignedBegin) {
uint32_t nb = alignedBegin - addr;
uint32_t tmp;
if (spi_flash_read_locked(alignedBegin - 4, &tmp, 4) != SPI_FLASH_RESULT_OK) {
DEBUGV("_spif_read(%d) addr=%x size=%x ab=%x ae=%x\r\n",
__LINE__, addr, size, alignedBegin, alignedEnd);
return SPIFFS_ERR_INTERNAL;
}
memcpy(dst, &tmp + 4 - nb, nb);
}
if (alignedEnd != alignedBegin) {
if (spi_flash_read_locked(alignedBegin, (uint32_t*) (dst + alignedBegin - addr),
alignedEnd - alignedBegin) != SPI_FLASH_RESULT_OK) {
DEBUGV("_spif_read(%d) addr=%x size=%x ab=%x ae=%x\r\n",
__LINE__, addr, size, alignedBegin, alignedEnd);
return SPIFFS_ERR_INTERNAL;
}
}
if (addr + size > alignedEnd) {
uint32_t nb = addr + size - alignedEnd;
uint32_t tmp;
if (spi_flash_read_locked(alignedEnd, &tmp, 4) != SPI_FLASH_RESULT_OK) {
DEBUGV("_spif_read(%d) addr=%x size=%x ab=%x ae=%x\r\n",
__LINE__, addr, size, alignedBegin, alignedEnd);
return SPIFFS_ERR_INTERNAL;
}
memcpy(dst + size - nb, &tmp, nb);
}
return result;
}
/*
Like spi_flash_read, spi_flash_write has a requirement for flash address to be
aligned. However it also requires RAM address to be aligned as it reads data
in 32-bit words. Flash address (mis-)alignment is handled much the same way
as for reads, but for RAM alignment we have to copy data into a temporary
buffer. The size of this buffer is a tradeoff between number of writes required
and amount of stack required. This is chosen to be 512 bytes here, but might
be adjusted in the future if there are good reasons to do so.
*/
static const int UNALIGNED_WRITE_BUFFER_SIZE = 512;
int32_t spiffs_hal_write(uint32_t addr, uint32_t size, uint8_t *src) {
uint32_t alignedBegin = (addr + 3) & (~3);
uint32_t alignedEnd = (addr + size) & (~3);
if (addr < alignedBegin) {
uint32_t nb = alignedBegin - addr;
uint32_t tmp = 0xffffffff;
memcpy(((uint8_t* )&tmp) + 4 - nb, src, nb);
if (spi_flash_write_locked(alignedBegin - 4, &tmp, 4) != SPI_FLASH_RESULT_OK) {
DEBUGV("_spif_write(%d) addr=%x size=%x ab=%x ae=%x\r\n",
__LINE__, addr, size, alignedBegin, alignedEnd);
return SPIFFS_ERR_INTERNAL;
}
}
if (alignedEnd != alignedBegin) {
uint32_t* srcLeftover = (uint32_t*) (src + alignedBegin - addr);
uint32_t srcAlign = ((uint32_t) srcLeftover) & 3;
if (!srcAlign) {
if (spi_flash_write_locked(alignedBegin, (uint32_t*) srcLeftover,
alignedEnd - alignedBegin) != SPI_FLASH_RESULT_OK) {
DEBUGV("_spif_write(%d) addr=%x size=%x ab=%x ae=%x\r\n",
__LINE__, addr, size, alignedBegin, alignedEnd);
return SPIFFS_ERR_INTERNAL;
}
}
else {
uint8_t buf[UNALIGNED_WRITE_BUFFER_SIZE];
for (uint32_t sizeLeft = alignedEnd - alignedBegin; sizeLeft; ) {
size_t willCopy = std::min(sizeLeft, sizeof(buf));
memcpy(buf, srcLeftover, willCopy);
if (spi_flash_write_locked(alignedBegin, (uint32_t*) buf,
willCopy) != SPI_FLASH_RESULT_OK) {
DEBUGV("_spif_write(%d) addr=%x size=%x ab=%x ae=%x\r\n",
__LINE__, addr, size, alignedBegin, alignedEnd);
return SPIFFS_ERR_INTERNAL;
}
sizeLeft -= willCopy;
srcLeftover += willCopy;
alignedBegin += willCopy;
}
}
}
if (addr + size > alignedEnd) {
uint32_t nb = addr + size - alignedEnd;
uint32_t tmp = 0xffffffff;
memcpy(&tmp, src + size - nb, nb);
if (spi_flash_write_locked(alignedEnd, &tmp, 4) != SPI_FLASH_RESULT_OK) {
DEBUGV("_spif_write(%d) addr=%x size=%x ab=%x ae=%x\r\n",
__LINE__, addr, size, alignedBegin, alignedEnd);
return SPIFFS_ERR_INTERNAL;
}
}
return SPIFFS_OK;
}
int32_t spiffs_hal_erase(uint32_t addr, uint32_t size) {
if ((size & (SPI_FLASH_SEC_SIZE - 1)) != 0 ||
(addr & (SPI_FLASH_SEC_SIZE - 1)) != 0) {
DEBUGV("_spif_erase called with addr=%x, size=%d\r\n", addr, size);
abort();
}
const uint32_t sector = addr / SPI_FLASH_SEC_SIZE;
const uint32_t sectorCount = size / SPI_FLASH_SEC_SIZE;
for (uint32_t i = 0; i < sectorCount; ++i) {
if (spi_flash_erase_sector_locked(sector + i) != 0) {
DEBUGV("_spif_erase addr=%x size=%d i=%d\r\n", addr, size, i);
return SPIFFS_ERR_INTERNAL;
}
}
return SPIFFS_OK;
}
|
Use optimistic_yield in FS read and write
|
Use optimistic_yield in FS read and write
|
C++
|
lgpl-2.1
|
jes/Arduino,hallard/Arduino,me-no-dev/Arduino,Juppit/Arduino,esp8266/Arduino,Lan-Hekary/Arduino,Cloudino/Cloudino-Arduino-IDE,esp8266/Arduino,Cloudino/Cloudino-Arduino-IDE,CanTireInnovations/Arduino,lrmoreno007/Arduino,esp8266/Arduino,Adam5Wu/Arduino,lrmoreno007/Arduino,quertenmont/Arduino,Cloudino/Cloudino-Arduino-IDE,CanTireInnovations/Arduino,sticilface/Arduino,Lan-Hekary/Arduino,sticilface/Arduino,Cloudino/Arduino,jes/Arduino,toastedcode/esp8266-Arduino,hallard/Arduino,chrisfraser/Arduino,Cloudino/Arduino,Lan-Hekary/Arduino,Juppit/Arduino,quertenmont/Arduino,Juppit/Arduino,NullMedia/Arduino,Cloudino/Arduino,NullMedia/Arduino,me-no-dev/Arduino,jes/Arduino,KaloNK/Arduino,martinayotte/ESP8266-Arduino,CanTireInnovations/Arduino,Cloudino/Cloudino-Arduino-IDE,toastedcode/esp8266-Arduino,edog1973/Arduino,edog1973/Arduino,esp8266/Arduino,jes/Arduino,gguuss/Arduino,quertenmont/Arduino,CanTireInnovations/Arduino,jes/Arduino,me-no-dev/Arduino,NextDevBoard/Arduino,NullMedia/Arduino,Links2004/Arduino,NextDevBoard/Arduino,martinayotte/ESP8266-Arduino,toastedcode/esp8266-Arduino,wemos/Arduino,KaloNK/Arduino,me-no-dev/Arduino,esp8266/Arduino,CanTireInnovations/Arduino,wemos/Arduino,wemos/Arduino,NextDevBoard/Arduino,Links2004/Arduino,quertenmont/Arduino,NextDevBoard/Arduino,quertenmont/Arduino,edog1973/Arduino,lrmoreno007/Arduino,toastedcode/esp8266-Arduino,martinayotte/ESP8266-Arduino,gguuss/Arduino,Adam5Wu/Arduino,Cloudino/Cloudino-Arduino-IDE,gguuss/Arduino,KaloNK/Arduino,NullMedia/Arduino,Adam5Wu/Arduino,KaloNK/Arduino,gguuss/Arduino,Cloudino/Arduino,Juppit/Arduino,Cloudino/Cloudino-Arduino-IDE,hallard/Arduino,NullMedia/Arduino,martinayotte/ESP8266-Arduino,wemos/Arduino,Cloudino/Arduino,Links2004/Arduino,sticilface/Arduino,CanTireInnovations/Arduino,toastedcode/esp8266-Arduino,sticilface/Arduino,Juppit/Arduino,chrisfraser/Arduino,martinayotte/ESP8266-Arduino,KaloNK/Arduino,lrmoreno007/Arduino,Adam5Wu/Arduino,Links2004/Arduino,Cloudino/Arduino,Links2004/Arduino,NextDevBoard/Arduino,Cloudino/Arduino,me-no-dev/Arduino,hallard/Arduino,Lan-Hekary/Arduino,edog1973/Arduino,hallard/Arduino,chrisfraser/Arduino,Lan-Hekary/Arduino,edog1973/Arduino,wemos/Arduino,Cloudino/Cloudino-Arduino-IDE,sticilface/Arduino,chrisfraser/Arduino,Adam5Wu/Arduino,chrisfraser/Arduino,gguuss/Arduino,lrmoreno007/Arduino,CanTireInnovations/Arduino
|
16cc09ce4a7c28a96e91054da362bfb247fb074a
|
tensorflow/compiler/mlir/tfrt/jit/python_binding/tf_cpurt_executor.cc
|
tensorflow/compiler/mlir/tfrt/jit/python_binding/tf_cpurt_executor.cc
|
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/tfrt/jit/python_binding/tf_cpurt_executor.h"
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include "mlir/ExecutionEngine/CRunnerUtils.h"
#include "mlir/Transforms/Bufferize.h"
#include "tensorflow/compiler/mlir/tensorflow/dialect_registration.h"
#include "tensorflow/compiler/mlir/tfrt/jit/tf_cpurt_pipeline.h"
#include "tensorflow/core/platform/dynamic_annotations.h"
#include "tfrt/cpu/jit/cpurt.h" // from @tf_runtime
#include "tfrt/dtype/dtype.h" // from @tf_runtime
#include "tfrt/host_context/async_value.h" // from @tf_runtime
#include "tfrt/host_context/concurrent_work_queue.h" // from @tf_runtime
#include "tfrt/host_context/execution_context.h" // from @tf_runtime
#include "tfrt/host_context/host_allocator.h" // from @tf_runtime
#include "tfrt/host_context/kernel_utils.h" // from @tf_runtime
#include "tfrt/support/ref_count.h" // from @tf_runtime
#include "tfrt/support/string_util.h" // from @tf_runtime
namespace py = pybind11;
using ::tfrt::AsyncValue;
using ::tfrt::AsyncValuePtr;
using ::tfrt::CreateMallocAllocator;
using ::tfrt::CreateMultiThreadedWorkQueue;
using ::tfrt::DecodedDiagnostic;
using ::tfrt::DType;
using ::tfrt::ExecutionContext;
using ::tfrt::GetDType;
using ::tfrt::RCReference;
using ::tfrt::RemainingResults;
using ::tfrt::RequestContext;
using ::tfrt::RequestContextBuilder;
using ::tfrt::StrCat;
using ::tfrt::cpu::jit::CompilationOptions;
using ::tfrt::cpu::jit::Executable;
using ::tfrt::cpu::jit::JitExecutable;
using ::tfrt::cpu::jit::MemrefDesc;
using ::tfrt::cpu::jit::ReturnStridedMemref;
using ::tfrt::cpu::jit::ReturnValueConverter;
namespace tensorflow {
TfCpurtExecutor::TfCpurtExecutor()
: host_context_(
[](const DecodedDiagnostic& diag) {
llvm::errs() << "Encountered runtime error: " << diag.message
<< "\n";
},
CreateMallocAllocator(), CreateMultiThreadedWorkQueue(4, 4)) {}
TfCpurtExecutor::Handle TfCpurtExecutor::Compile(
const std::string& mlir_module, const std::string& entrypoint,
Specialization specialization) {
CompilationOptions opts;
// Create an async task for each worker thread.
opts.num_worker_threads = 4;
opts.register_dialects = mlir::RegisterAllTensorFlowDialects;
opts.register_pass_pipeline = CreateTfCpuRtPipeline;
opts.specialization = specialization;
opts.type_converter = mlir::BufferizeTypeConverter();
// Instantiate new JitExecutable from the MLIR source.
llvm::Expected<JitExecutable> jit_executable =
JitExecutable::Instantiate(mlir_module, entrypoint, opts);
if (auto err = jit_executable.takeError())
throw std::runtime_error(
StrCat("Failed to instantiate JitExecutable: ", err));
Handle hdl = jit_executables_.size();
jit_executables_.insert({hdl, std::move(*jit_executable)});
return hdl;
}
// Returns Python buffer protocol's type string from TFRT's dtype.
static const char* ToPythonStructFormat(DType dtype_kind) {
// Reference: https://docs.python.org/3/library/struct.html
switch (dtype_kind) {
case DType::Invalid:
throw std::runtime_error("Invalid dtype.");
case DType::Unsupported:
throw std::runtime_error("Unsupported dtype.");
case DType::UI8:
throw std::runtime_error("Unimplemented.");
case DType::UI16:
return "H";
case DType::UI32:
return "I";
case DType::UI64:
return "Q";
case DType::I1:
return "?";
case DType::I8:
throw std::runtime_error("Unimplemented.");
case DType::I16:
return "h";
case DType::I32:
return "i";
case DType::I64:
return "q";
case DType::F32:
return "f";
case DType::F64:
return "d";
case DType::Complex64:
throw std::runtime_error("Unimplemented.");
case DType::Complex128:
throw std::runtime_error("Unimplemented.");
case DType::F16:
throw std::runtime_error("Unimplemented.");
case DType::BF16:
throw std::runtime_error("Unimplemented.");
case DType::String:
throw std::runtime_error("Unimplemented.");
default:
throw std::runtime_error("Unimplemented.");
}
}
// Returns TFRT's dtype for the Python buffer protocol's type string.
static DType FromPythonStructFormat(char dtype) {
// Reference: https://docs.python.org/3/library/struct.html
switch (dtype) {
case 'H':
return DType::UI16;
case 'I':
return DType::UI32;
case 'Q':
return DType::UI64;
case '?':
return DType::I1;
case 'h':
return DType::I16;
case 'i':
return DType::I32;
case 'q':
return DType::I64;
case 'f':
return DType::F32;
case 'd':
return DType::F64;
default:
throw std::runtime_error("Unsupported python dtype.");
}
}
// Converts Python array to the Memref Descriptor.
static void ConvertPyArrayMemrefDesc(const py::array& array,
MemrefDesc* memref) {
auto py_dtype = [](pybind11::dtype dtype) -> char {
// np.int64 array for some reason has `i` dtype, however according to the
// documentation it must be `q`.
if (dtype.kind() == 'i' && dtype.itemsize() == 8) return 'q';
return dtype.char_();
};
memref->dtype = DType(FromPythonStructFormat(py_dtype(array.dtype())));
memref->data = const_cast<void*>(array.data());
memref->offset = 0;
int rank = array.ndim();
memref->sizes.resize(rank);
memref->strides.resize(rank);
for (ssize_t d = 0; d < rank; ++d) {
memref->sizes[d] = array.shape(d);
memref->strides[d] = array.strides(d) / array.itemsize();
}
}
template <typename T, int rank>
static llvm::ArrayRef<int64_t> Sizes(StridedMemRefType<T, rank>* memref) {
return memref->sizes;
}
template <typename T, int rank>
static llvm::ArrayRef<int64_t> Strides(StridedMemRefType<T, rank>* memref) {
return memref->strides;
}
template <typename T>
static llvm::ArrayRef<int64_t> Sizes(StridedMemRefType<T, 0>* memref) {
return {};
}
template <typename T>
static llvm::ArrayRef<int64_t> Strides(StridedMemRefType<T, 0>* memref) {
return {};
}
namespace {
struct PyBindingConversionContext {};
using PyBindingReturnValueConverter =
ReturnValueConverter<PyBindingConversionContext>;
} // namespace
// Converts StridedMemrefType to the Python array. This struct satisfies
// ReturnStridedMemref's concept (see cpurt.h).
//
// TODO(ezhulenev): Currently this converter transfers ownership of the memref
// to the Python array. This is not correct in general, because memref does not
// imply ownership, for example it can be one of the forwarded inputs or a
// global memref that is owned by the compiled kernel.
struct MemrefToPyArray {
using ResultType = py::array;
using ConversionContext = PyBindingConversionContext;
template <typename T, int rank>
static py::array Convert(const ConversionContext&, void* memref_ptr) {
auto* memref = static_cast<StridedMemRefType<T, rank>*>(memref_ptr);
auto memref_sizes = Sizes(memref);
auto memref_strides = Strides(memref);
std::vector<ssize_t> sizes(memref_sizes.begin(), memref_sizes.end());
std::vector<ssize_t> strides(memref_strides.begin(), memref_strides.end());
// Python expects strides in bytes.
auto dtype = GetDType<T>();
for (size_t d = 0; d < strides.size(); ++d)
strides[d] *= GetHostSize(dtype);
return py::array(py::buffer_info(memref->data, GetHostSize(dtype),
ToPythonStructFormat(dtype), rank, sizes,
strides));
}
};
std::vector<py::array> TfCpurtExecutor::Execute(
Handle handle, const std::vector<py::array>& arguments) {
// Verify that we have a compilatio result for the handle.
auto it = jit_executables_.find(handle);
if (it == jit_executables_.end())
throw std::runtime_error(StrCat("Unknown jit executable handle: ", handle));
JitExecutable& jit_executable = it->getSecond();
// Build an ExecutionContext from the HostContext.
llvm::Expected<RCReference<RequestContext>> req_ctx =
RequestContextBuilder(&host_context_, /*resource_context=*/nullptr)
.build();
tfrt::ExecutionContext exec_ctx(std::move(*req_ctx));
// Convert arguments to memrefs.
std::vector<MemrefDesc> memrefs(arguments.size());
for (int i = 0; i < arguments.size(); ++i)
ConvertPyArrayMemrefDesc(arguments[i], &memrefs[i]);
// Get an executable that might be specialized to the operands.
AsyncValuePtr<Executable> executable =
jit_executable.GetExecutable(memrefs, exec_ctx);
// Wait for the compilation completion.
host_context_.Await({executable.CopyRef()});
if (executable.IsError())
throw std::runtime_error(
StrCat("Failed to get Executable: ", executable.GetError()));
// Prepare storage for returned values.
size_t num_results = executable->signature().num_results();
std::vector<RCReference<AsyncValue>> result_storage;
result_storage.reserve(num_results);
for (int i = 0; i < num_results; ++i) result_storage.emplace_back();
RemainingResults results(&host_context_, result_storage);
// Convert returned memrefs to Tensors.
PyBindingReturnValueConverter converter(results);
converter.AddConversion(ReturnStridedMemref<MemrefToPyArray>);
if (auto err = executable->Execute(memrefs, converter, exec_ctx))
throw std::runtime_error(StrCat("Unsupported argument: ", err));
// Pull Python arrays out of async values.
std::vector<py::array> ret_values;
ret_values.reserve(result_storage.size());
for (auto& result : result_storage) {
if (result->IsError())
throw std::runtime_error(StrCat("result error: ", result->GetError()));
ret_values.emplace_back(result->get<py::array>());
}
return ret_values;
}
} // namespace tensorflow
PYBIND11_MODULE(_tf_cpurt_executor, m) {
py::enum_<tensorflow::TfCpurtExecutor::Specialization>(m, "Specialization")
.value("ENABLED", tensorflow::TfCpurtExecutor::Specialization::kEnabled)
.value("DISABLED", tensorflow::TfCpurtExecutor::Specialization::kDisabled)
.value("ALWAYS", tensorflow::TfCpurtExecutor::Specialization::kAlways);
py::class_<tensorflow::TfCpurtExecutor>(m, "TfCpurtExecutor")
.def(py::init<>())
.def("compile", &tensorflow::TfCpurtExecutor::Compile,
py::arg("mlir_module"), py::arg("entrypoint"),
py::arg("specialization") =
tensorflow::TfCpurtExecutor::Specialization::kEnabled)
.def("execute", &tensorflow::TfCpurtExecutor::Execute);
}
|
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/tfrt/jit/python_binding/tf_cpurt_executor.h"
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include "mlir/ExecutionEngine/CRunnerUtils.h"
#include "mlir/Transforms/Bufferize.h"
#include "tensorflow/compiler/mlir/tensorflow/dialect_registration.h"
#include "tensorflow/compiler/mlir/tfrt/jit/tf_cpurt_pipeline.h"
#include "tensorflow/core/platform/dynamic_annotations.h"
#include "tfrt/cpu/jit/cpurt.h" // from @tf_runtime
#include "tfrt/dtype/dtype.h" // from @tf_runtime
#include "tfrt/host_context/async_value.h" // from @tf_runtime
#include "tfrt/host_context/concurrent_work_queue.h" // from @tf_runtime
#include "tfrt/host_context/execution_context.h" // from @tf_runtime
#include "tfrt/host_context/host_allocator.h" // from @tf_runtime
#include "tfrt/host_context/kernel_utils.h" // from @tf_runtime
#include "tfrt/support/ref_count.h" // from @tf_runtime
#include "tfrt/support/string_util.h" // from @tf_runtime
namespace py = pybind11;
using ::tfrt::AsyncValue;
using ::tfrt::AsyncValuePtr;
using ::tfrt::CreateMallocAllocator;
using ::tfrt::CreateMultiThreadedWorkQueue;
using ::tfrt::DecodedDiagnostic;
using ::tfrt::DType;
using ::tfrt::ExecutionContext;
using ::tfrt::GetDType;
using ::tfrt::RCReference;
using ::tfrt::RemainingResults;
using ::tfrt::RequestContext;
using ::tfrt::RequestContextBuilder;
using ::tfrt::StrCat;
using ::tfrt::cpu::jit::CompilationOptions;
using ::tfrt::cpu::jit::Executable;
using ::tfrt::cpu::jit::JitExecutable;
using ::tfrt::cpu::jit::MemrefDesc;
using ::tfrt::cpu::jit::ReturnStridedMemref;
using ::tfrt::cpu::jit::ReturnValueConverter;
namespace tensorflow {
TfCpurtExecutor::TfCpurtExecutor()
: host_context_(
[](const DecodedDiagnostic& diag) {
llvm::errs() << "Encountered runtime error: " << diag.message
<< "\n";
},
CreateMallocAllocator(), CreateMultiThreadedWorkQueue(4, 4)) {}
TfCpurtExecutor::Handle TfCpurtExecutor::Compile(
const std::string& mlir_module, const std::string& entrypoint,
Specialization specialization) {
CompilationOptions opts;
// Create an async task for each worker thread.
opts.num_worker_threads = 4;
opts.register_dialects = mlir::RegisterAllTensorFlowDialects;
opts.register_pass_pipeline = CreateTfCpuRtPipeline;
opts.specialization = specialization;
opts.type_converter = mlir::BufferizeTypeConverter();
// Instantiate new JitExecutable from the MLIR source.
llvm::Expected<JitExecutable> jit_executable =
JitExecutable::Instantiate(mlir_module, entrypoint, opts);
if (auto err = jit_executable.takeError())
throw std::runtime_error(
StrCat("Failed to instantiate JitExecutable: ", err));
Handle hdl = jit_executables_.size();
jit_executables_.insert({hdl, std::move(*jit_executable)});
return hdl;
}
// Returns Python buffer protocol's type string from TFRT's dtype.
static const char* ToPythonStructFormat(DType dtype_kind) {
// Reference: https://docs.python.org/3/library/struct.html
switch (dtype_kind) {
case DType::Invalid:
throw std::runtime_error("Invalid dtype.");
case DType::Unsupported:
throw std::runtime_error("Unsupported dtype.");
case DType::UI8:
throw std::runtime_error("Unimplemented.");
case DType::UI16:
return "H";
case DType::UI32:
return "I";
case DType::UI64:
return "Q";
case DType::I1:
return "?";
case DType::I8:
throw std::runtime_error("Unimplemented.");
case DType::I16:
return "h";
case DType::I32:
return "i";
case DType::I64:
return "q";
case DType::F32:
return "f";
case DType::F64:
return "d";
case DType::Complex64:
throw std::runtime_error("Unimplemented.");
case DType::Complex128:
throw std::runtime_error("Unimplemented.");
case DType::F16:
throw std::runtime_error("Unimplemented.");
case DType::BF16:
throw std::runtime_error("Unimplemented.");
case DType::String:
throw std::runtime_error("Unimplemented.");
default:
throw std::runtime_error("Unimplemented.");
}
}
// Returns TFRT's dtype for the Python buffer protocol's type string.
static DType FromPythonStructFormat(char dtype) {
// Reference: https://docs.python.org/3/library/struct.html
switch (dtype) {
case 'H':
return DType::UI16;
case 'I':
return DType::UI32;
case 'Q':
return DType::UI64;
case '?':
return DType::I1;
case 'h':
return DType::I16;
case 'i':
return DType::I32;
case 'q':
return DType::I64;
case 'f':
return DType::F32;
case 'd':
return DType::F64;
default:
throw std::runtime_error("Unsupported python dtype.");
}
}
// Converts Python array to the Memref Descriptor.
static void ConvertPyArrayMemrefDesc(const py::array& array,
MemrefDesc* memref) {
auto py_dtype = [](pybind11::dtype dtype) -> char {
// np.int64 array for some reason has `i` dtype, however according to the
// documentation it must be `q`.
if (dtype.kind() == 'i' && dtype.itemsize() == 8) return 'q';
return dtype.char_();
};
memref->dtype = DType(FromPythonStructFormat(py_dtype(array.dtype())));
memref->data = const_cast<void*>(array.data());
memref->offset = 0;
int rank = array.ndim();
memref->sizes.resize(rank);
memref->strides.resize(rank);
for (ssize_t d = 0; d < rank; ++d) {
memref->sizes[d] = array.shape(d);
memref->strides[d] = array.strides(d) / array.itemsize();
}
}
template <typename T, int rank>
static llvm::ArrayRef<int64_t> Sizes(StridedMemRefType<T, rank>* memref) {
return memref->sizes;
}
template <typename T, int rank>
static llvm::ArrayRef<int64_t> Strides(StridedMemRefType<T, rank>* memref) {
return memref->strides;
}
template <typename T>
static llvm::ArrayRef<int64_t> Sizes(StridedMemRefType<T, 0>* memref) {
return {};
}
template <typename T>
static llvm::ArrayRef<int64_t> Strides(StridedMemRefType<T, 0>* memref) {
return {};
}
namespace {
struct PyBindingConversionContext {};
using PyBindingReturnValueConverter =
ReturnValueConverter<PyBindingConversionContext>;
} // namespace
// Converts StridedMemrefType to the Python array. This struct satisfies
// ReturnStridedMemref's concept (see cpurt.h).
//
// TODO(ezhulenev): Currently this converter transfers ownership of the memref
// to the Python array. This is not correct in general, because memref does not
// imply ownership, for example it can be one of the forwarded inputs or a
// global memref that is owned by the compiled kernel.
struct MemrefToPyArray {
using ResultType = py::array;
using ConversionContext = PyBindingConversionContext;
template <typename T, int rank>
static py::array Convert(const ConversionContext&, void* memref_ptr) {
auto* memref = static_cast<StridedMemRefType<T, rank>*>(memref_ptr);
auto memref_sizes = Sizes(memref);
auto memref_strides = Strides(memref);
std::vector<ssize_t> sizes(memref_sizes.begin(), memref_sizes.end());
std::vector<ssize_t> strides(memref_strides.begin(), memref_strides.end());
// Python expects strides in bytes.
auto dtype = GetDType<T>();
for (size_t d = 0; d < strides.size(); ++d)
strides[d] *= GetHostSize(dtype);
return py::array(py::buffer_info(memref->data, GetHostSize(dtype),
ToPythonStructFormat(dtype), rank, sizes,
strides));
}
};
std::vector<py::array> TfCpurtExecutor::Execute(
Handle handle, const std::vector<py::array>& arguments) {
// Verify that we have a compilatio result for the handle.
auto it = jit_executables_.find(handle);
if (it == jit_executables_.end())
throw std::runtime_error(StrCat("Unknown jit executable handle: ", handle));
JitExecutable& jit_executable = it->getSecond();
// Build an ExecutionContext from the HostContext.
llvm::Expected<RCReference<RequestContext>> req_ctx =
RequestContextBuilder(&host_context_, /*resource_context=*/nullptr)
.build();
tfrt::ExecutionContext exec_ctx(std::move(*req_ctx));
// Convert arguments to memrefs.
std::vector<MemrefDesc> memrefs(arguments.size());
for (int i = 0; i < arguments.size(); ++i)
ConvertPyArrayMemrefDesc(arguments[i], &memrefs[i]);
// Get an executable that might be specialized to the operands.
AsyncValuePtr<Executable> executable =
jit_executable.GetExecutable(memrefs, exec_ctx);
// Wait for the compilation completion.
host_context_.Await({executable.CopyRef()});
if (executable.IsError())
throw std::runtime_error(
StrCat("Failed to get Executable: ", executable.GetError()));
// Prepare storage for returned values.
size_t num_results = executable->signature().num_results();
std::vector<RCReference<AsyncValue>> result_storage;
result_storage.reserve(num_results);
for (int i = 0; i < num_results; ++i) result_storage.emplace_back();
RemainingResults results(&host_context_, result_storage);
// Convert returned memrefs to Tensors.
PyBindingReturnValueConverter converter(results);
converter.AddConversion(ReturnStridedMemref<MemrefToPyArray>);
if (auto err = executable->Execute(memrefs, converter, exec_ctx))
throw std::runtime_error(StrCat("Unsupported argument: ", err));
// Pull Python arrays out of async values.
std::vector<py::array> ret_values;
ret_values.reserve(result_storage.size());
for (auto& result : result_storage) {
if (result->IsError())
throw std::runtime_error(StrCat("result error: ", result->GetError()));
py::array& result_array = result->get<py::array>();
TF_ANNOTATE_MEMORY_IS_INITIALIZED(result_array.data(),
result_array.nbytes());
ret_values.emplace_back(result_array);
}
return ret_values;
}
} // namespace tensorflow
PYBIND11_MODULE(_tf_cpurt_executor, m) {
py::enum_<tensorflow::TfCpurtExecutor::Specialization>(m, "Specialization")
.value("ENABLED", tensorflow::TfCpurtExecutor::Specialization::kEnabled)
.value("DISABLED", tensorflow::TfCpurtExecutor::Specialization::kDisabled)
.value("ALWAYS", tensorflow::TfCpurtExecutor::Specialization::kAlways);
py::class_<tensorflow::TfCpurtExecutor>(m, "TfCpurtExecutor")
.def(py::init<>())
.def("compile", &tensorflow::TfCpurtExecutor::Compile,
py::arg("mlir_module"), py::arg("entrypoint"),
py::arg("specialization") =
tensorflow::TfCpurtExecutor::Specialization::kEnabled)
.def("execute", &tensorflow::TfCpurtExecutor::Execute);
}
|
Mark result arrays in `TfCpurtExecutor::Execute` as initialized memory.
|
Mark result arrays in `TfCpurtExecutor::Execute` as initialized memory.
PiperOrigin-RevId: 393217575
Change-Id: Ibefd76913a0e97d4fc4f3b93ee947510a432460e
|
C++
|
apache-2.0
|
Intel-tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,gautam1858/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,karllessard/tensorflow,yongtang/tensorflow,karllessard/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,Intel-Corporation/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,yongtang/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once
|
e61381ed2f4dc1cf4c86e3a5299ef2a087feb472
|
Modules/Learning/Sampling/src/otbPolygonClassStatisticsAccumulator.cxx
|
Modules/Learning/Sampling/src/otbPolygonClassStatisticsAccumulator.cxx
|
/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbPolygonClassStatisticsAccumulator.h"
namespace otb
{
template <typename TIterator>
void
PolygonClassStatisticsAccumulator
::Add(otb::ogr::Layer::const_iterator& featIt,
TIterator& imgIt)
{
// Get class name
std::string className(featIt->ogr().GetFieldAsString(this->m_FieldIndex));
// Get Feature Id
unsigned long featureId = featIt->ogr().GetFID();
if (m_ElmtsInClass.count(className) == 0)
{
m_ElmtsInClass[className] = 0UL;
}
if (m_Polygon.count(featureId) == 0)
{
m_Polygon[featureId] = 0UL;
}
typename TIterator::ImageType::PointType imgPoint;
typename TIterator::IndexType imgIndex;
OGRPoint tmpPoint(0.0,0.0,0.0);
imgIt.GoToBegin();
OGRGeometry * geom = featIt->ogr().GetGeometryRef();
switch (geom->getGeometryType())
{
case wkbPoint:
case wkbPoint25D:
{
OGRPoint* castPoint = dynamic_cast<OGRPoint*>(geom);
if (castPoint == NULL)
{
// Wrong Type !
break;
}
imgPoint[0] = castPoint->getX();
imgPoint[1] = castPoint->getY();
imgIt.GetImage()->TransformPhysicalPointToIndex(imgPoint,imgIndex);
while (!imgIt.IsAtEnd())
{
if (imgIndex == imgIt.GetIndex())
{
m_NbPixelsGlobal++;
m_ElmtsInClass[className]++;
m_Polygon[featureId]++;
break;
}
}
break;
}
case wkbLineString:
case wkbLineString25D:
{
// TODO
break;
}
case wkbPolygon:
case wkbPolygon25D:
{
while (!imgIt.IsAtEnd())
{
imgIt.GetImage()->TransformIndexToPhysicalPoint(imgIt.GetIndex(),imgPoint);
tmpPoint.setX(imgPoint[0]);
tmpPoint.setY(imgPoint[1]);
if (geom->Contains(&tmpPoint))
{
m_NbPixelsGlobal++;
m_ElmtsInClass[className]++;
m_Polygon[featureId]++;
}
++imgIt;
}
break;
}
case wkbMultiPoint:
case wkbMultiPoint25D:
case wkbMultiLineString:
case wkbMultiLineString25D:
case wkbMultiPolygon:
case wkbMultiPolygon25D:
case wkbGeometryCollection:
case wkbGeometryCollection25D:
{
//otbWarningMacro("Geometry not handled: " << geom->getGeometryName());
break;
}
default:
{
//otbWarningMacro("Geometry not handled: " << geom->getGeometryName());
break;
}
}
// Count increments
// m_NbPixelsGlobal++;
// m_ElmtsInClass[className]++;
// m_Polygon[featureId]++;
//Generation of a random number for the sampling in a polygon where we only need one pixel, it's choosen randomly
//elmtsInClass[className] = elmtsInClass[className] + nbOfPixelsInGeom;
//OGRPolygon* inPolygon = dynamic_cast<OGRPolygon *>(geom);
//OGRLinearRing* exteriorRing = inPolygon->getExteriorRing();
//itk::Point<double, 2> point;
//inputImage->TransformIndexToPhysicalPoint(it.GetIndex(), point);
// ->Test if the current pixel is in a polygon hole
// If point is in feature
//if(exteriorRing->isPointInRing(&pointOGR, TRUE) && isNotInHole)
//{
//}
}
void
PolygonClassStatisticsAccumulator
::Reset()
{
m_NbPixelsGlobal = 0UL;
m_ElmtsInClass.clear();
m_Polygon.clear();
}
} // end of namespace otb
|
/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbPolygonClassStatisticsAccumulator.h"
namespace otb
{
template <typename TIterator>
void
PolygonClassStatisticsAccumulator
::Add(otb::ogr::Layer::const_iterator& featIt,
TIterator& imgIt)
{
// Get class name
std::string className(featIt->ogr().GetFieldAsString(this->m_FieldIndex));
// Get Feature Id
unsigned long featureId = featIt->ogr().GetFID();
if (m_ElmtsInClass.count(className) == 0)
{
m_ElmtsInClass[className] = 0UL;
}
if (m_Polygon.count(featureId) == 0)
{
m_Polygon[featureId] = 0UL;
}
typename TIterator::ImageType::PointType imgPoint;
typename TIterator::IndexType imgIndex;
OGRPoint tmpPoint(0.0,0.0,0.0);
imgIt.GoToBegin();
OGRGeometry * geom = featIt->ogr().GetGeometryRef();
switch (geom->getGeometryType())
{
case wkbPoint:
case wkbPoint25D:
{
OGRPoint* castPoint = dynamic_cast<OGRPoint*>(geom);
if (castPoint == NULL)
{
// Wrong Type !
break;
}
imgPoint[0] = castPoint->getX();
imgPoint[1] = castPoint->getY();
imgIt.GetImage()->TransformPhysicalPointToIndex(imgPoint,imgIndex);
while (!imgIt.IsAtEnd())
{
if (imgIndex == imgIt.GetIndex())
{
m_NbPixelsGlobal++;
m_ElmtsInClass[className]++;
m_Polygon[featureId]++;
break;
}
}
break;
}
case wkbLineString:
case wkbLineString25D:
{
OGRPolygon tmpPolygon;
tmpPolygon.getExteriorRing()->addPoint(0.0,0.0,0.0);
tmpPolygon.getExteriorRing()->addPoint(1.0,0.0,0.0);
tmpPolygon.getExteriorRing()->addPoint(1.0,1.0,0.0);
tmpPolygon.getExteriorRing()->addPoint(0.0,1.0,0.0);
tmpPolygon.getExteriorRing()->addPoint(0.0,0.0,0.0);
typename TIterator::ImageType::SpacingType imgAbsSpacing;
imgAbsSpacing = imgIt.GetImage()->GetSpacing();
if (imgAbsSpacing[0] < 0) imgAbsSpacing[0] = -imgAbsSpacing[0];
if (imgAbsSpacing[1] < 0) imgAbsSpacing[1] = -imgAbsSpacing[1];
while (!imgIt.IsAtEnd())
{
imgIt.GetImage()->TransformIndexToPhysicalPoint(imgIt.GetIndex(),imgPoint);
tmpPolygon.getExteriorRing()->setPoint(
imgPoint[0]-0.5*imgAbsSpacing[0],
imgPoint[1]-0.5*imgAbsSpacing[1]
,0.0);
tmpPolygon.getExteriorRing()->setPoint(
imgPoint[0]+0.5*imgAbsSpacing[0],
imgPoint[1]-0.5*imgAbsSpacing[1]
,0.0);
tmpPolygon.getExteriorRing()->setPoint(
imgPoint[0]+0.5*imgAbsSpacing[0],
imgPoint[1]+0.5*imgAbsSpacing[1]
,0.0);
tmpPolygon.getExteriorRing()->setPoint(
imgPoint[0]-0.5*imgAbsSpacing[0],
imgPoint[1]+0.5*imgAbsSpacing[1]
,0.0);
tmpPolygon.getExteriorRing()->setPoint(
imgPoint[0]-0.5*imgAbsSpacing[0],
imgPoint[1]-0.5*imgAbsSpacing[1]
,0.0);
if (geom->Intersects(&tmpPolygon))
{
m_NbPixelsGlobal++;
m_ElmtsInClass[className]++;
m_Polygon[featureId]++;
}
++imgIt;
}
break;
}
case wkbPolygon:
case wkbPolygon25D:
{
while (!imgIt.IsAtEnd())
{
imgIt.GetImage()->TransformIndexToPhysicalPoint(imgIt.GetIndex(),imgPoint);
tmpPoint.setX(imgPoint[0]);
tmpPoint.setY(imgPoint[1]);
if (geom->Contains(&tmpPoint))
{
m_NbPixelsGlobal++;
m_ElmtsInClass[className]++;
m_Polygon[featureId]++;
}
++imgIt;
}
break;
}
case wkbMultiPoint:
case wkbMultiPoint25D:
case wkbMultiLineString:
case wkbMultiLineString25D:
case wkbMultiPolygon:
case wkbMultiPolygon25D:
case wkbGeometryCollection:
case wkbGeometryCollection25D:
{
//otbWarningMacro("Geometry not handled: " << geom->getGeometryName());
break;
}
default:
{
//otbWarningMacro("Geometry not handled: " << geom->getGeometryName());
break;
}
}
}
void
PolygonClassStatisticsAccumulator
::Reset()
{
m_NbPixelsGlobal = 0UL;
m_ElmtsInClass.clear();
m_Polygon.clear();
}
} // end of namespace otb
|
implement statistics for wkbLineString objects
|
ENH: implement statistics for wkbLineString objects
|
C++
|
apache-2.0
|
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
|
3531ecbcbddc6165618f9f5f0acb4fbc75eb476f
|
gdk-pixbuf-pvr.cc
|
gdk-pixbuf-pvr.cc
|
/*
* gdk-pixbuf-pvr - A gdk-pixbuf loader for PVR textures
*
* Copyright © 2011 Intel Corporation
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 Lesser General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>
*
* Authors: Damien Lespiau <[email protected]>
*
*/
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#define GDK_PIXBUF_ENABLE_BACKEND
#include <gdk-pixbuf/gdk-pixbuf.h>
#include "PVRTexLib.h"
using namespace pvrtexlib;
/*
* Note: The library provided by Imagination does not seem to provide anything
* that would allow us to support "incremental loading".
*/
typedef struct
{
CPVRTexture *decompressed;
} PvrContext;
static const gchar *
standard_pixel_type_to_string (PixelType pixel_type)
{
switch (pixel_type)
{
case eInt8StandardPixelType:
return "R8G8B8A8";
case eInt16StandardPixelType:
return "A16B16G16R16";
case eInt32StandardPixelType:
return "R32G32B32A32";
case eFloatStandardPixelType:
return "R32G32B32A32 (float)";
/* should not happen as we should only be given standard pixel types */
default:
return "Other";
}
}
static void
on_pixbuf_destroyed (guchar *pixels,
gpointer data)
{
PvrContext *context = (PvrContext *) data;
delete context->decompressed;
g_free (context);
}
static GdkPixbuf *
gdk_pixbuf__pvr_image_load (FILE *f,
GError **error)
{
GdkPixbuf *pixbuf;
unsigned char *content;
CPVRTexture *decompressed;
PvrContext *context;
struct stat st;
int fd;
PVRTRY
{
PVRTextureUtilities utils;
PixelType pixel_type;
fd = fileno (f);
if (fd == -1)
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
"Invalid FILE object");
return NULL;
}
if (fstat (fd, &st) == -1)
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
"Failed to get attributes");
return NULL;
}
if (st.st_size == 0 || st.st_size > G_MAXSIZE)
{
content = NULL;
}
else
{
content = (unsigned char *) mmap (NULL, st.st_size, PROT_READ,
MAP_PRIVATE, fd, 0);
}
if (content == NULL || content == MAP_FAILED)
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
"Failed to map file");
return NULL;
}
CPVRTexture compressed (content);
decompressed = new CPVRTexture();
utils.DecompressPVR (compressed, *decompressed);
pixel_type = decompressed->getPixelType ();
if (pixel_type != eInt8StandardPixelType)
{
const gchar *type;
type = standard_pixel_type_to_string (pixel_type);
g_set_error (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
"Image type currently not supported (%s)", type);
return NULL;
}
CPVRTextureData& data = decompressed->getData();
context = g_new0 (PvrContext, 1);
context->decompressed = decompressed;
/* FIXME: The data resulting of the decompression will always have alpha.
* might worth repacking the pixbuf to RGB if the original texture did
* not have any alpha before handing the pixbuf back to the user */
pixbuf = gdk_pixbuf_new_from_data (data.getData(),
GDK_COLORSPACE_RGB,
TRUE,
8,
decompressed->getWidth (),
decompressed->getHeight (),
decompressed->getWidth () * 4,
on_pixbuf_destroyed,
context);
if (compressed.isFlipped ())
{
GdkPixbuf *flipped;
flipped = gdk_pixbuf_flip (pixbuf, FALSE);
g_object_unref (pixbuf);
pixbuf = flipped;
}
}
PVRCATCH(aaaahhh)
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
aaaahhh.what());
return NULL;
}
return pixbuf;
}
bool is_p2 (unsigned int x)
{
return ((x != 0) && !(x & (x - 1)));
}
static gboolean
gdk_pixbuf__pvr_image_save (FILE *f,
GdkPixbuf *pixbuf,
gchar **param_keys,
gchar **param_values,
GError **error)
{
GdkPixbuf *with_alpha = NULL;
PVRTRY
{
PVRTextureUtilities utils;
int width, height;
guchar *pixels;
width = gdk_pixbuf_get_width (pixbuf);
height = gdk_pixbuf_get_height (pixbuf);
if (!is_p2 (width))
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
"Width needs to be a power of 2");
return FALSE;
}
if (!is_p2 (height))
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
"Height needs to be a power of 2");
return FALSE;
}
/* The standard format that PVRTexLib takes is RGBA 8888 so we need
* to add an alpha channel if the original image does not have one */
if (!gdk_pixbuf_get_has_alpha (pixbuf))
{
with_alpha = gdk_pixbuf_add_alpha (pixbuf, FALSE, 0, 0, 0);
pixbuf = with_alpha;
}
if (gdk_pixbuf_get_rowstride (pixbuf) != 4 * width)
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
"A row stride larger than the width is not "
"allowed");
if (with_alpha)
g_object_unref (with_alpha);
return FALSE;
}
/* make a CPVRTexture instance from the GdkPixbuf */
pixels = gdk_pixbuf_get_pixels (pixbuf);
CPVRTexture uncompressed (width,
height,
0, /* u32MipMapCount */
1, /* u32NumSurfaces */
false, /* bBorder */
false, /* bTwiddled */
false, /* bCubeMap */
false, /* bVolume */
false, /* bFalseMips */
true, /* bHasAlpha */
false, /* bFlipped */
eInt8StandardPixelType, /* ePixelType */
0.0f, /* fNormalMap */
pixels); /* pPixelData */
/* create texture to encode to */
CPVRTexture compressed (uncompressed.getHeader());
/* FIXME: Remove the alpha channel from the compressed texture is the
* original GdkPixbuf does not have alpha (But we still need to create
* the uncompressed texture with hasAlpha to TRUE as the pixbuf is 4
* bytes per pixel anyway */
/* TODO: Add support for generating the mipmaps */
/* TODO: Add support for selection with compression we want */
/* set required encoded pixel type */
compressed.setPixelType (OGL_PVRTC4);
/* encode texture */
utils.CompressPVR (uncompressed, compressed);
/* write to file */
compressed.getHeader().writeToFile (f);
compressed.getData().writeToFile (f);
}
PVRCATCH(aaaahhh)
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
aaaahhh.what());
if (with_alpha)
g_object_unref (with_alpha);
return FALSE;
}
if (with_alpha)
g_object_unref (with_alpha);
return TRUE;
}
extern "C" {
G_MODULE_EXPORT void
fill_vtable (GdkPixbufModule *module)
{
module->load = gdk_pixbuf__pvr_image_load;
module->save = gdk_pixbuf__pvr_image_save;
}
G_MODULE_EXPORT void
fill_info (GdkPixbufFormat *info)
{
static GdkPixbufModulePattern signature_new[] = {
{ NULL, NULL, 0 }
};
static gchar *mime_types[] =
{
"image/x-pvr",
NULL
};
static gchar *extensions[] =
{
"pvr",
NULL
};
info->name = "pvr";
info->description = "PVR image";
info->signature = signature_new;
info->mime_types = mime_types;
info->extensions = extensions;
info->flags = GDK_PIXBUF_FORMAT_WRITABLE;
info->license = "LGPL";
}
} /* extern "C" */
|
/*
* gdk-pixbuf-pvr - A gdk-pixbuf loader for PVR textures
*
* Copyright © 2011 Intel Corporation
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 Lesser General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>
*
* Authors: Damien Lespiau <[email protected]>
*
*/
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#define GDK_PIXBUF_ENABLE_BACKEND
#include <gdk-pixbuf/gdk-pixbuf.h>
#include "PVRTexLib.h"
using namespace pvrtexlib;
/*
* Note: The library provided by Imagination does not seem to provide anything
* that would allow us to support "incremental loading".
*/
typedef struct
{
CPVRTexture *decompressed;
} PvrContext;
static const gchar *
standard_pixel_type_to_string (PixelType pixel_type)
{
switch (pixel_type)
{
case eInt8StandardPixelType:
return "R8G8B8A8";
case eInt16StandardPixelType:
return "A16B16G16R16";
case eInt32StandardPixelType:
return "R32G32B32A32";
case eFloatStandardPixelType:
return "R32G32B32A32 (float)";
/* should not happen as we should only be given standard pixel types */
default:
return "Other";
}
}
static void
on_pixbuf_destroyed (guchar *pixels,
gpointer data)
{
PvrContext *context = (PvrContext *) data;
delete context->decompressed;
g_free (context);
}
static GdkPixbuf *
gdk_pixbuf__pvr_image_load (FILE *f,
GError **error)
{
GdkPixbuf *pixbuf;
unsigned char *content;
CPVRTexture *decompressed;
PvrContext *context;
struct stat st;
int fd;
PVRTRY
{
PVRTextureUtilities utils;
PixelType pixel_type;
fd = fileno (f);
if (fd == -1)
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
"Invalid FILE object");
return NULL;
}
if (fstat (fd, &st) == -1)
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
"Failed to get attributes");
return NULL;
}
if (st.st_size == 0 || st.st_size > G_MAXSIZE)
{
content = NULL;
}
else
{
content = (unsigned char *) mmap (NULL, st.st_size, PROT_READ,
MAP_PRIVATE, fd, 0);
}
if (content == NULL || content == MAP_FAILED)
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
"Failed to map file");
return NULL;
}
CPVRTexture compressed (content);
decompressed = new CPVRTexture();
utils.DecompressPVR (compressed, *decompressed);
pixel_type = decompressed->getPixelType ();
if (pixel_type != eInt8StandardPixelType)
{
const gchar *type;
type = standard_pixel_type_to_string (pixel_type);
g_set_error (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
"Image type currently not supported (%s)", type);
return NULL;
}
CPVRTextureData& data = decompressed->getData();
context = g_new0 (PvrContext, 1);
context->decompressed = decompressed;
/* FIXME: The data resulting of the decompression will always have alpha.
* might worth repacking the pixbuf to RGB if the original texture did
* not have any alpha before handing the pixbuf back to the user */
pixbuf = gdk_pixbuf_new_from_data (data.getData(),
GDK_COLORSPACE_RGB,
TRUE,
8,
decompressed->getWidth (),
decompressed->getHeight (),
decompressed->getWidth () * 4,
on_pixbuf_destroyed,
context);
if (compressed.isFlipped ())
{
GdkPixbuf *flipped;
flipped = gdk_pixbuf_flip (pixbuf, FALSE);
g_object_unref (pixbuf);
pixbuf = flipped;
}
}
PVRCATCH(aaaahhh)
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
aaaahhh.what());
return NULL;
}
return pixbuf;
}
static bool
is_p2 (unsigned int x)
{
return ((x != 0) && !(x & (x - 1)));
}
static gboolean
gdk_pixbuf__pvr_image_save (FILE *f,
GdkPixbuf *pixbuf,
gchar **param_keys,
gchar **param_values,
GError **error)
{
GdkPixbuf *with_alpha = NULL;
PVRTRY
{
PVRTextureUtilities utils;
int width, height;
guchar *pixels;
width = gdk_pixbuf_get_width (pixbuf);
height = gdk_pixbuf_get_height (pixbuf);
if (!is_p2 (width))
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
"Width needs to be a power of 2");
return FALSE;
}
if (!is_p2 (height))
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
"Height needs to be a power of 2");
return FALSE;
}
/* The standard format that PVRTexLib takes is RGBA 8888 so we need
* to add an alpha channel if the original image does not have one */
if (!gdk_pixbuf_get_has_alpha (pixbuf))
{
with_alpha = gdk_pixbuf_add_alpha (pixbuf, FALSE, 0, 0, 0);
pixbuf = with_alpha;
}
if (gdk_pixbuf_get_rowstride (pixbuf) != 4 * width)
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
"A row stride larger than the width is not "
"allowed");
if (with_alpha)
g_object_unref (with_alpha);
return FALSE;
}
/* make a CPVRTexture instance from the GdkPixbuf */
pixels = gdk_pixbuf_get_pixels (pixbuf);
CPVRTexture uncompressed (width,
height,
0, /* u32MipMapCount */
1, /* u32NumSurfaces */
false, /* bBorder */
false, /* bTwiddled */
false, /* bCubeMap */
false, /* bVolume */
false, /* bFalseMips */
true, /* bHasAlpha */
false, /* bFlipped */
eInt8StandardPixelType, /* ePixelType */
0.0f, /* fNormalMap */
pixels); /* pPixelData */
/* create texture to encode to */
CPVRTexture compressed (uncompressed.getHeader());
/* FIXME: Remove the alpha channel from the compressed texture is the
* original GdkPixbuf does not have alpha (But we still need to create
* the uncompressed texture with hasAlpha to TRUE as the pixbuf is 4
* bytes per pixel anyway */
/* TODO: Add support for generating the mipmaps */
/* TODO: Add support for selection with compression we want */
/* set required encoded pixel type */
compressed.setPixelType (OGL_PVRTC4);
/* encode texture */
utils.CompressPVR (uncompressed, compressed);
/* write to file */
compressed.getHeader().writeToFile (f);
compressed.getData().writeToFile (f);
}
PVRCATCH(aaaahhh)
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_FAILED,
aaaahhh.what());
if (with_alpha)
g_object_unref (with_alpha);
return FALSE;
}
if (with_alpha)
g_object_unref (with_alpha);
return TRUE;
}
extern "C" {
G_MODULE_EXPORT void
fill_vtable (GdkPixbufModule *module)
{
module->load = gdk_pixbuf__pvr_image_load;
module->save = gdk_pixbuf__pvr_image_save;
}
G_MODULE_EXPORT void
fill_info (GdkPixbufFormat *info)
{
static GdkPixbufModulePattern signature_new[] = {
{ NULL, NULL, 0 }
};
static gchar *mime_types[] =
{
"image/x-pvr",
NULL
};
static gchar *extensions[] =
{
"pvr",
NULL
};
info->name = "pvr";
info->description = "PVR image";
info->signature = signature_new;
info->mime_types = mime_types;
info->extensions = extensions;
info->flags = GDK_PIXBUF_FORMAT_WRITABLE;
info->license = "LGPL";
}
} /* extern "C" */
|
Make is_p2() static
|
loader: Make is_p2() static
We don't want to expose that in the .so.
|
C++
|
bsd-3-clause
|
media-explorer/gdk-pixbuf-texture-tool,media-explorer/gdk-pixbuf-texture-tool
|
cd758986fc5359ceeef1c9299dcbd2afce34f9e7
|
glretrace_egl.cpp
|
glretrace_egl.cpp
|
/**************************************************************************
*
* Copyright 2011 LunarG, Inc.
* All Rights Reserved.
*
* Based on glretrace_glx.cpp, which has
*
* Copyright 2011 Jose Fonseca
*
* 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 "glproc.hpp"
#include "retrace.hpp"
#include "glretrace.hpp"
#include "os.hpp"
#ifndef EGL_OPENGL_ES_API
#define EGL_OPENGL_ES_API 0x30A0
#define EGL_OPENVG_API 0x30A1
#define EGL_OPENGL_API 0x30A2
#define EGL_CONTEXT_CLIENT_VERSION 0x3098
#endif
using namespace glretrace;
typedef std::map<unsigned long long, glws::Drawable *> DrawableMap;
typedef std::map<unsigned long long, glws::Context *> ContextMap;
typedef std::map<unsigned long long, glws::Profile> ProfileMap;
static DrawableMap drawable_map;
static ContextMap context_map;
static ProfileMap profile_map;
static unsigned int current_api = EGL_OPENGL_ES_API;
static glws::Profile last_profile = glws::PROFILE_COMPAT;
static void
createDrawable(unsigned long long orig_config, unsigned long long orig_surface);
static glws::Drawable *
getDrawable(unsigned long long surface_ptr) {
if (surface_ptr == 0) {
return NULL;
}
DrawableMap::const_iterator it;
it = drawable_map.find(surface_ptr);
if (it == drawable_map.end()) {
// In Fennec we get the egl window surface from Java which isn't
// traced, so just create a drawable if it doesn't exist in here
createDrawable(0, surface_ptr);
it = drawable_map.find(surface_ptr);
assert(it != drawable_map.end());
}
return (it != drawable_map.end()) ? it->second : NULL;
}
static glws::Context *
getContext(unsigned long long context_ptr) {
if (context_ptr == 0) {
return NULL;
}
ContextMap::const_iterator it;
it = context_map.find(context_ptr);
return (it != context_map.end()) ? it->second : NULL;
}
static void createDrawable(unsigned long long orig_config, unsigned long long orig_surface)
{
ProfileMap::iterator it = profile_map.find(orig_config);
glws::Profile profile;
// If the requested config is associated with a profile, use that
// profile. Otherwise, assume that the last used profile is what
// the user wants.
if (it != profile_map.end()) {
profile = it->second;
} else {
profile = last_profile;
}
glws::Visual *visual = glretrace::visual[profile];
glws::Drawable *drawable = glws::createDrawable(visual);
drawable_map[orig_surface] = drawable;
}
static void retrace_eglCreateWindowSurface(trace::Call &call) {
unsigned long long orig_config = call.arg(1).toUIntPtr();
unsigned long long orig_surface = call.ret->toUIntPtr();
createDrawable(orig_config, orig_surface);
}
static void retrace_eglCreatePbufferSurface(trace::Call &call) {
unsigned long long orig_config = call.arg(1).toUIntPtr();
unsigned long long orig_surface = call.ret->toUIntPtr();
createDrawable(orig_config, orig_surface);
// TODO: Respect the pbuffer dimensions too
}
static void retrace_eglDestroySurface(trace::Call &call) {
unsigned long long orig_surface = call.arg(1).toUIntPtr();
DrawableMap::iterator it;
it = drawable_map.find(orig_surface);
if (it != drawable_map.end()) {
if (it->second != drawable) {
// TODO: reference count
delete it->second;
}
drawable_map.erase(it);
}
}
static void retrace_eglBindAPI(trace::Call &call) {
current_api = call.arg(0).toUInt();
}
static void retrace_eglCreateContext(trace::Call &call) {
unsigned long long orig_context = call.ret->toUIntPtr();
unsigned long long orig_config = call.arg(1).toUIntPtr();
glws::Context *share_context = getContext(call.arg(2).toUIntPtr());
trace::Array *attrib_array = dynamic_cast<trace::Array *>(&call.arg(3));
glws::Profile profile;
switch (current_api) {
case EGL_OPENGL_API:
profile = glws::PROFILE_COMPAT;
break;
case EGL_OPENGL_ES_API:
default:
profile = glws::PROFILE_ES1;
if (attrib_array) {
for (int i = 0; i < attrib_array->values.size(); i += 2) {
int v = attrib_array->values[i]->toSInt();
if (v == EGL_CONTEXT_CLIENT_VERSION) {
v = attrib_array->values[i + 1]->toSInt();
if (v == 2)
profile = glws::PROFILE_ES2;
break;
}
}
}
break;
}
glws::Context *context = glws::createContext(glretrace::visual[profile], share_context, profile);
if (!context) {
const char *name;
switch (profile) {
case glws::PROFILE_COMPAT:
name = "OpenGL";
break;
case glws::PROFILE_ES1:
name = "OpenGL ES 1.1";
break;
case glws::PROFILE_ES2:
name = "OpenGL ES 2.0";
break;
default:
name = "unknown";
break;
}
retrace::warning(call) << "Failed to create " << name << " context.\n";
os::abort();
}
context_map[orig_context] = context;
profile_map[orig_config] = profile;
last_profile = profile;
}
static void retrace_eglDestroyContext(trace::Call &call) {
unsigned long long orig_context = call.arg(1).toUIntPtr();
ContextMap::iterator it;
it = context_map.find(orig_context);
if (it != context_map.end()) {
delete it->second;
context_map.erase(it);
}
}
static void retrace_eglMakeCurrent(trace::Call &call) {
glws::Drawable *new_drawable = getDrawable(call.arg(1).toUIntPtr());
glws::Context *new_context = getContext(call.arg(3).toUIntPtr());
if (new_drawable == drawable && new_context == context) {
return;
}
if (drawable && context) {
glFlush();
if (!double_buffer) {
frame_complete(call);
}
}
bool result = glws::makeCurrent(new_drawable, new_context);
if (new_drawable && new_context && result) {
drawable = new_drawable;
context = new_context;
} else {
drawable = NULL;
context = NULL;
}
}
static void retrace_eglSwapBuffers(trace::Call &call) {
frame_complete(call);
if (double_buffer) {
drawable->swapBuffers();
} else {
glFlush();
}
}
const retrace::Entry glretrace::egl_callbacks[] = {
{"eglGetError", &retrace::ignore},
{"eglGetDisplay", &retrace::ignore},
{"eglInitialize", &retrace::ignore},
{"eglTerminate", &retrace::ignore},
{"eglQueryString", &retrace::ignore},
{"eglGetConfigs", &retrace::ignore},
{"eglChooseConfig", &retrace::ignore},
{"eglGetConfigAttrib", &retrace::ignore},
{"eglCreateWindowSurface", &retrace_eglCreateWindowSurface},
{"eglCreatePbufferSurface", &retrace_eglCreatePbufferSurface},
//{"eglCreatePixmapSurface", &retrace::ignore},
{"eglDestroySurface", &retrace_eglDestroySurface},
{"eglQuerySurface", &retrace::ignore},
{"eglBindAPI", &retrace_eglBindAPI},
{"eglQueryAPI", &retrace::ignore},
//{"eglWaitClient", &retrace::ignore},
//{"eglReleaseThread", &retrace::ignore},
//{"eglCreatePbufferFromClientBuffer", &retrace::ignore},
//{"eglSurfaceAttrib", &retrace::ignore},
//{"eglBindTexImage", &retrace::ignore},
//{"eglReleaseTexImage", &retrace::ignore},
{"eglSwapInterval", &retrace::ignore},
{"eglCreateContext", &retrace_eglCreateContext},
{"eglDestroyContext", &retrace_eglDestroyContext},
{"eglMakeCurrent", &retrace_eglMakeCurrent},
{"eglGetCurrentContext", &retrace::ignore},
{"eglGetCurrentSurface", &retrace::ignore},
{"eglGetCurrentDisplay", &retrace::ignore},
{"eglQueryContext", &retrace::ignore},
{"eglWaitGL", &retrace::ignore},
{"eglWaitNative", &retrace::ignore},
{"eglSwapBuffers", &retrace_eglSwapBuffers},
//{"eglCopyBuffers", &retrace::ignore},
{"eglGetProcAddress", &retrace::ignore},
{NULL, NULL},
};
|
/**************************************************************************
*
* Copyright 2011 LunarG, Inc.
* All Rights Reserved.
*
* Based on glretrace_glx.cpp, which has
*
* Copyright 2011 Jose Fonseca
*
* 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 "glproc.hpp"
#include "retrace.hpp"
#include "glretrace.hpp"
#include "os.hpp"
#ifndef EGL_OPENGL_ES_API
#define EGL_OPENGL_ES_API 0x30A0
#define EGL_OPENVG_API 0x30A1
#define EGL_OPENGL_API 0x30A2
#define EGL_CONTEXT_CLIENT_VERSION 0x3098
#endif
using namespace glretrace;
typedef std::map<unsigned long long, glws::Drawable *> DrawableMap;
typedef std::map<unsigned long long, glws::Context *> ContextMap;
typedef std::map<unsigned long long, glws::Profile> ProfileMap;
static DrawableMap drawable_map;
static ContextMap context_map;
static ProfileMap profile_map;
static unsigned int current_api = EGL_OPENGL_ES_API;
static glws::Profile last_profile = glws::PROFILE_COMPAT;
static void
createDrawable(unsigned long long orig_config, unsigned long long orig_surface);
static glws::Drawable *
getDrawable(unsigned long long surface_ptr) {
if (surface_ptr == 0) {
return NULL;
}
DrawableMap::const_iterator it;
it = drawable_map.find(surface_ptr);
if (it == drawable_map.end()) {
// In Fennec we get the egl window surface from Java which isn't
// traced, so just create a drawable if it doesn't exist in here
createDrawable(0, surface_ptr);
it = drawable_map.find(surface_ptr);
assert(it != drawable_map.end());
}
return (it != drawable_map.end()) ? it->second : NULL;
}
static glws::Context *
getContext(unsigned long long context_ptr) {
if (context_ptr == 0) {
return NULL;
}
ContextMap::const_iterator it;
it = context_map.find(context_ptr);
return (it != context_map.end()) ? it->second : NULL;
}
static void createDrawable(unsigned long long orig_config, unsigned long long orig_surface)
{
ProfileMap::iterator it = profile_map.find(orig_config);
glws::Profile profile;
// If the requested config is associated with a profile, use that
// profile. Otherwise, assume that the last used profile is what
// the user wants.
if (it != profile_map.end()) {
profile = it->second;
} else {
profile = last_profile;
}
glws::Visual *visual = glretrace::visual[profile];
glws::Drawable *drawable = glws::createDrawable(visual);
drawable_map[orig_surface] = drawable;
}
static void retrace_eglCreateWindowSurface(trace::Call &call) {
unsigned long long orig_config = call.arg(1).toUIntPtr();
unsigned long long orig_surface = call.ret->toUIntPtr();
createDrawable(orig_config, orig_surface);
}
static void retrace_eglCreatePbufferSurface(trace::Call &call) {
unsigned long long orig_config = call.arg(1).toUIntPtr();
unsigned long long orig_surface = call.ret->toUIntPtr();
createDrawable(orig_config, orig_surface);
// TODO: Respect the pbuffer dimensions too
}
static void retrace_eglDestroySurface(trace::Call &call) {
unsigned long long orig_surface = call.arg(1).toUIntPtr();
DrawableMap::iterator it;
it = drawable_map.find(orig_surface);
if (it != drawable_map.end()) {
if (it->second != drawable) {
// TODO: reference count
delete it->second;
}
drawable_map.erase(it);
}
}
static void retrace_eglBindAPI(trace::Call &call) {
current_api = call.arg(0).toUInt();
}
static void retrace_eglCreateContext(trace::Call &call) {
unsigned long long orig_context = call.ret->toUIntPtr();
unsigned long long orig_config = call.arg(1).toUIntPtr();
glws::Context *share_context = getContext(call.arg(2).toUIntPtr());
trace::Array *attrib_array = dynamic_cast<trace::Array *>(&call.arg(3));
glws::Profile profile;
switch (current_api) {
case EGL_OPENGL_API:
profile = glws::PROFILE_COMPAT;
break;
case EGL_OPENGL_ES_API:
default:
profile = glws::PROFILE_ES1;
if (attrib_array) {
for (int i = 0; i < attrib_array->values.size(); i += 2) {
int v = attrib_array->values[i]->toSInt();
if (v == EGL_CONTEXT_CLIENT_VERSION) {
v = attrib_array->values[i + 1]->toSInt();
if (v == 2)
profile = glws::PROFILE_ES2;
break;
}
}
}
break;
}
glws::Context *context = glws::createContext(glretrace::visual[profile], share_context, profile);
if (!context) {
const char *name;
switch (profile) {
case glws::PROFILE_COMPAT:
name = "OpenGL";
break;
case glws::PROFILE_ES1:
name = "OpenGL ES 1.1";
break;
case glws::PROFILE_ES2:
name = "OpenGL ES 2.0";
break;
default:
name = "unknown";
break;
}
retrace::warning(call) << "Failed to create " << name << " context.\n";
os::abort();
}
context_map[orig_context] = context;
profile_map[orig_config] = profile;
last_profile = profile;
}
static void retrace_eglDestroyContext(trace::Call &call) {
unsigned long long orig_context = call.arg(1).toUIntPtr();
ContextMap::iterator it;
it = context_map.find(orig_context);
if (it != context_map.end()) {
delete it->second;
context_map.erase(it);
}
}
static void retrace_eglMakeCurrent(trace::Call &call) {
glws::Drawable *new_drawable = getDrawable(call.arg(1).toUIntPtr());
glws::Context *new_context = getContext(call.arg(3).toUIntPtr());
if (new_drawable == drawable && new_context == context) {
return;
}
if (drawable && context) {
glFlush();
if (!double_buffer) {
frame_complete(call);
}
}
bool result = glws::makeCurrent(new_drawable, new_context);
if (new_drawable && new_context && result) {
drawable = new_drawable;
context = new_context;
} else {
drawable = NULL;
context = NULL;
}
}
static void retrace_eglSwapBuffers(trace::Call &call) {
frame_complete(call);
if (double_buffer && drawable) {
drawable->swapBuffers();
} else {
glFlush();
}
}
const retrace::Entry glretrace::egl_callbacks[] = {
{"eglGetError", &retrace::ignore},
{"eglGetDisplay", &retrace::ignore},
{"eglInitialize", &retrace::ignore},
{"eglTerminate", &retrace::ignore},
{"eglQueryString", &retrace::ignore},
{"eglGetConfigs", &retrace::ignore},
{"eglChooseConfig", &retrace::ignore},
{"eglGetConfigAttrib", &retrace::ignore},
{"eglCreateWindowSurface", &retrace_eglCreateWindowSurface},
{"eglCreatePbufferSurface", &retrace_eglCreatePbufferSurface},
//{"eglCreatePixmapSurface", &retrace::ignore},
{"eglDestroySurface", &retrace_eglDestroySurface},
{"eglQuerySurface", &retrace::ignore},
{"eglBindAPI", &retrace_eglBindAPI},
{"eglQueryAPI", &retrace::ignore},
//{"eglWaitClient", &retrace::ignore},
//{"eglReleaseThread", &retrace::ignore},
//{"eglCreatePbufferFromClientBuffer", &retrace::ignore},
//{"eglSurfaceAttrib", &retrace::ignore},
//{"eglBindTexImage", &retrace::ignore},
//{"eglReleaseTexImage", &retrace::ignore},
{"eglSwapInterval", &retrace::ignore},
{"eglCreateContext", &retrace_eglCreateContext},
{"eglDestroyContext", &retrace_eglDestroyContext},
{"eglMakeCurrent", &retrace_eglMakeCurrent},
{"eglGetCurrentContext", &retrace::ignore},
{"eglGetCurrentSurface", &retrace::ignore},
{"eglGetCurrentDisplay", &retrace::ignore},
{"eglQueryContext", &retrace::ignore},
{"eglWaitGL", &retrace::ignore},
{"eglWaitNative", &retrace::ignore},
{"eglSwapBuffers", &retrace_eglSwapBuffers},
//{"eglCopyBuffers", &retrace::ignore},
{"eglGetProcAddress", &retrace::ignore},
{NULL, NULL},
};
|
Fix minor crash : due to call eglSwapBuffers after eglDestroyContext
|
Fix minor crash : due to call eglSwapBuffers after eglDestroyContext
|
C++
|
mit
|
swq0553/apitrace,PeterLValve/apitrace,surround-io/apitrace,swq0553/apitrace,swq0553/apitrace,schulmar/apitrace,tuanthng/apitrace,surround-io/apitrace,joshua5201/apitrace,apitrace/apitrace,trtt/apitrace,surround-io/apitrace,swq0553/apitrace,EoD/apitrace,PeterLValve/apitrace,joshua5201/apitrace,surround-io/apitrace,apitrace/apitrace,tuanthng/apitrace,schulmar/apitrace,EoD/apitrace,EoD/apitrace,tuanthng/apitrace,trtt/apitrace,schulmar/apitrace,joshua5201/apitrace,tuanthng/apitrace,swq0553/apitrace,trtt/apitrace,tuanthng/apitrace,EoD/apitrace,trtt/apitrace,apitrace/apitrace,apitrace/apitrace,joshua5201/apitrace,trtt/apitrace,schulmar/apitrace,EoD/apitrace,PeterLValve/apitrace,schulmar/apitrace,surround-io/apitrace,PeterLValve/apitrace,joshua5201/apitrace
|
457993f836338aa0c13a32af803fcbc5227c81f3
|
dbus/dbuspassive.hpp
|
dbus/dbuspassive.hpp
|
#pragma once
#include "conf.hpp"
#include "dbushelper_interface.hpp"
#include "dbuspassiveredundancy.hpp"
#include "interfaces.hpp"
#include "util.hpp"
#include <sdbusplus/bus.hpp>
#include <sdbusplus/message.hpp>
#include <sdbusplus/server.hpp>
#include <chrono>
#include <cmath>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <tuple>
#include <vector>
namespace pid_control
{
int dbusHandleSignal(sd_bus_message* msg, void* data, sd_bus_error* err);
/*
* This ReadInterface will passively listen for Value updates from whomever
* owns the associated dbus object.
*
* This requires another modification in phosphor-dbus-interfaces that will
* signal a value update every time it's read instead of only when it changes
* to help us:
* - ensure we're still receiving data (since we don't control the reader)
* - simplify stale data detection
* - simplify error detection
*/
class DbusPassive : public ReadInterface
{
public:
static std::unique_ptr<ReadInterface> createDbusPassive(
sdbusplus::bus::bus& bus, const std::string& type,
const std::string& id, std::unique_ptr<DbusHelperInterface> helper,
const conf::SensorConfig* info,
const std::shared_ptr<DbusPassiveRedundancy>& redundancy);
DbusPassive(sdbusplus::bus::bus& bus, const std::string& type,
const std::string& id,
std::unique_ptr<DbusHelperInterface> helper,
const SensorProperties& settings, bool failed,
const std::string& path,
const std::shared_ptr<DbusPassiveRedundancy>& redundancy);
ReadReturn read(void) override;
bool getFailed(void) const override;
void updateValue(double value, bool force);
void setValue(double value);
void setFailed(bool value);
void setFunctional(bool value);
int64_t getScale(void);
std::string getID(void);
double getMax(void);
double getMin(void);
private:
sdbusplus::server::match::match _signal;
int64_t _scale;
std::string _id; // for debug identification
std::unique_ptr<DbusHelperInterface> _helper;
std::mutex _lock;
double _value = 0;
double _max = 0;
double _min = 0;
bool _failed = false;
bool _functional = true;
bool _typeMargin = false;
bool _badReading = false;
bool _marginHot = false;
std::string path;
std::shared_ptr<DbusPassiveRedundancy> redundancy;
/* The last time the value was refreshed, not necessarily changed. */
std::chrono::high_resolution_clock::time_point _updated;
};
int handleSensorValue(sdbusplus::message::message& msg, DbusPassive* owner);
} // namespace pid_control
|
#pragma once
#include "conf.hpp"
#include "dbushelper_interface.hpp"
#include "dbuspassiveredundancy.hpp"
#include "interfaces.hpp"
#include "util.hpp"
#include <sdbusplus/bus.hpp>
#include <sdbusplus/bus/match.hpp>
#include <sdbusplus/message.hpp>
#include <chrono>
#include <cmath>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <tuple>
#include <vector>
namespace pid_control
{
int dbusHandleSignal(sd_bus_message* msg, void* data, sd_bus_error* err);
/*
* This ReadInterface will passively listen for Value updates from whomever
* owns the associated dbus object.
*
* This requires another modification in phosphor-dbus-interfaces that will
* signal a value update every time it's read instead of only when it changes
* to help us:
* - ensure we're still receiving data (since we don't control the reader)
* - simplify stale data detection
* - simplify error detection
*/
class DbusPassive : public ReadInterface
{
public:
static std::unique_ptr<ReadInterface> createDbusPassive(
sdbusplus::bus::bus& bus, const std::string& type,
const std::string& id, std::unique_ptr<DbusHelperInterface> helper,
const conf::SensorConfig* info,
const std::shared_ptr<DbusPassiveRedundancy>& redundancy);
DbusPassive(sdbusplus::bus::bus& bus, const std::string& type,
const std::string& id,
std::unique_ptr<DbusHelperInterface> helper,
const SensorProperties& settings, bool failed,
const std::string& path,
const std::shared_ptr<DbusPassiveRedundancy>& redundancy);
ReadReturn read(void) override;
bool getFailed(void) const override;
void updateValue(double value, bool force);
void setValue(double value);
void setFailed(bool value);
void setFunctional(bool value);
int64_t getScale(void);
std::string getID(void);
double getMax(void);
double getMin(void);
private:
sdbusplus::bus::match_t _signal;
int64_t _scale;
std::string _id; // for debug identification
std::unique_ptr<DbusHelperInterface> _helper;
std::mutex _lock;
double _value = 0;
double _max = 0;
double _min = 0;
bool _failed = false;
bool _functional = true;
bool _typeMargin = false;
bool _badReading = false;
bool _marginHot = false;
std::string path;
std::shared_ptr<DbusPassiveRedundancy> redundancy;
/* The last time the value was refreshed, not necessarily changed. */
std::chrono::high_resolution_clock::time_point _updated;
};
int handleSensorValue(sdbusplus::message::message& msg, DbusPassive* owner);
} // namespace pid_control
|
remove usage of deprecated alias
|
sdbusplus: remove usage of deprecated alias
The alias `server::match` has been deprecated since 2016. Use the new
alias under bus.
Signed-off-by: Patrick Williams <[email protected]>
Change-Id: Ibccf347f7016b69f78f74b8debe714b8a0c30ba5
|
C++
|
apache-2.0
|
openbmc/phosphor-pid-control,openbmc/phosphor-pid-control
|
401b31b57ade33371db13b77ccdc9c90df38fac6
|
source/core/mining-manager/product-scorer/ProductScorerFactory.cpp
|
source/core/mining-manager/product-scorer/ProductScorerFactory.cpp
|
#include "ProductScorerFactory.h"
#include "ProductScoreSum.h"
#include "CustomScorer.h"
#include "CategoryScorer.h"
#include "../MiningManager.h"
#include "../custom-rank-manager/CustomRankManager.h"
#include "../group-label-logger/GroupLabelLogger.h"
#include "../group-label-logger/BackendLabel2FrontendLabel.h"
#include "../group-manager/PropSharedLockSet.h"
#include "../product-score-manager/ProductScoreManager.h"
#include "../util/split_ustr.h"
#include <configuration-manager/ProductRankingConfig.h>
#include <memory> // auto_ptr
#include <glog/logging.h>
using namespace sf1r;
namespace
{
/**
* in order to make the category score less than 10 (the minimum custom
* score), we would select at most 9 top labels.
*/
const score_t kTopLabelLimit = 9;
}
ProductScorerFactory::ProductScorerFactory(
const ProductRankingConfig& config,
MiningManager& miningManager)
: config_(config)
, miningManager_(&miningManager)
, customRankManager_(miningManager.GetCustomRankManager())
, categoryClickLogger_(NULL)
, categoryValueTable_(NULL)
, productScoreManager_(miningManager.GetProductScoreManager())
{
const ProductScoreConfig& categoryScoreConfig =
config.scores[CATEGORY_SCORE];
const std::string& categoryProp = categoryScoreConfig.propName;
categoryClickLogger_ = miningManager.GetGroupLabelLogger(categoryProp);
categoryValueTable_ = miningManager.GetPropValueTable(categoryProp);
}
ProductScorer* ProductScorerFactory::createScorer(
const std::string& query,
faceted::PropSharedLockSet& propSharedLockSet,
ProductScorer* relevanceScorer)
{
std::auto_ptr<ProductScoreSum> scoreSum(new ProductScoreSum);
bool isany = false;
for (int i = 0; i < PRODUCT_SCORE_NUM; ++i)
{
ProductScorer* scorer = createScorerImpl_(config_.scores[i],
query,
propSharedLockSet,
relevanceScorer);
if (scorer)
{
scoreSum->addScorer(scorer);
isany = true;
}
}
if(!isany)
return NULL;
return scoreSum.release();
}
ProductScorer* ProductScorerFactory::createScorerImpl_(
const ProductScoreConfig& scoreConfig,
const std::string& query,
faceted::PropSharedLockSet& propSharedLockSet,
ProductScorer* relevanceScorer)
{
if (scoreConfig.weight == 0)
return NULL;
switch(scoreConfig.type)
{
case CUSTOM_SCORE:
return createCustomScorer_(scoreConfig, query);
case CATEGORY_SCORE:
return createCategoryScorer_(scoreConfig, query, propSharedLockSet);
case RELEVANCE_SCORE:
return createRelevanceScorer_(scoreConfig, relevanceScorer);
case POPULARITY_SCORE:
return createPopularityScorer_(scoreConfig);
default:
return NULL;
}
}
ProductScorer* ProductScorerFactory::createCustomScorer_(
const ProductScoreConfig& scoreConfig,
const std::string& query)
{
if (customRankManager_ == NULL)
return NULL;
CustomRankDocId customDocId;
bool result = customRankManager_->getCustomValue(query, customDocId);
if (result && !customDocId.topIds.empty())
return new CustomScorer(scoreConfig, customDocId.topIds);
return NULL;
}
ProductScorer* ProductScorerFactory::createCategoryScorer_(
const ProductScoreConfig& scoreConfig,
const std::string& query,
faceted::PropSharedLockSet& propSharedLockSet)
{
if (categoryClickLogger_ == NULL ||
categoryValueTable_ == NULL)
return NULL;
std::vector<faceted::PropValueTable::pvid_t> topLabels;
std::vector<int> topFreqs;
bool result = categoryClickLogger_->getFreqLabel(query, kTopLabelLimit,
topLabels, topFreqs);
if(topLabels.empty())
{
UString ustrQuery(query, UString::UTF_8);
UString backendCategory;
if(miningManager_->GetProductCategory(ustrQuery, backendCategory))
{
UString frontendCategory;
if(BackendLabelToFrontendLabel::Get()->Map(backendCategory,frontendCategory))
{
std::vector<std::vector<izenelib::util::UString> > groupPaths;
split_group_path(frontendCategory, groupPaths);
if(1 == groupPaths.size())
{
faceted::PropValueTable::pvid_t topLabel = categoryValueTable_->propValueId(groupPaths[0]);
topLabels.push_back(topLabel);
}
}
}
}
if (!topLabels.empty())
{
propSharedLockSet.insertSharedLock(categoryValueTable_);
return new CategoryScorer(scoreConfig, *categoryValueTable_, topLabels);
}
return NULL;
}
ProductScorer* ProductScorerFactory::createRelevanceScorer_(
const ProductScoreConfig& scoreConfig,
ProductScorer* relevanceScorer)
{
if (!relevanceScorer)
return NULL;
relevanceScorer->setWeight(scoreConfig.weight);
return relevanceScorer;
}
ProductScorer* ProductScorerFactory::createPopularityScorer_(
const ProductScoreConfig& scoreConfig)
{
if (!productScoreManager_)
return NULL;
return productScoreManager_->createProductScorer(scoreConfig);
}
|
#include "ProductScorerFactory.h"
#include "ProductScoreSum.h"
#include "CustomScorer.h"
#include "CategoryScorer.h"
#include "../MiningManager.h"
#include "../custom-rank-manager/CustomRankManager.h"
#include "../group-label-logger/GroupLabelLogger.h"
#include "../group-label-logger/BackendLabel2FrontendLabel.h"
#include "../group-manager/PropSharedLockSet.h"
#include "../product-score-manager/ProductScoreManager.h"
#include "../util/split_ustr.h"
#include <configuration-manager/ProductRankingConfig.h>
#include <memory> // auto_ptr
#include <glog/logging.h>
using namespace sf1r;
namespace
{
/**
* in order to make the category score less than 10 (the minimum custom
* score), we would select at most 9 top labels.
*/
const score_t kTopLabelLimit = 9;
}
ProductScorerFactory::ProductScorerFactory(
const ProductRankingConfig& config,
MiningManager& miningManager)
: config_(config)
, miningManager_(&miningManager)
, customRankManager_(miningManager.GetCustomRankManager())
, categoryClickLogger_(NULL)
, categoryValueTable_(NULL)
, productScoreManager_(miningManager.GetProductScoreManager())
{
const ProductScoreConfig& categoryScoreConfig =
config.scores[CATEGORY_SCORE];
const std::string& categoryProp = categoryScoreConfig.propName;
categoryClickLogger_ = miningManager.GetGroupLabelLogger(categoryProp);
categoryValueTable_ = miningManager.GetPropValueTable(categoryProp);
}
ProductScorer* ProductScorerFactory::createScorer(
const std::string& query,
faceted::PropSharedLockSet& propSharedLockSet,
ProductScorer* relevanceScorer)
{
std::auto_ptr<ProductScoreSum> scoreSum(new ProductScoreSum);
bool isany = false;
for (int i = 0; i < PRODUCT_SCORE_NUM; ++i)
{
ProductScorer* scorer = createScorerImpl_(config_.scores[i],
query,
propSharedLockSet,
relevanceScorer);
if (scorer)
{
scoreSum->addScorer(scorer);
isany = true;
}
}
if(!isany)
return NULL;
return scoreSum.release();
}
ProductScorer* ProductScorerFactory::createScorerImpl_(
const ProductScoreConfig& scoreConfig,
const std::string& query,
faceted::PropSharedLockSet& propSharedLockSet,
ProductScorer* relevanceScorer)
{
if (scoreConfig.weight == 0)
return NULL;
switch(scoreConfig.type)
{
case CUSTOM_SCORE:
return createCustomScorer_(scoreConfig, query);
case CATEGORY_SCORE:
return createCategoryScorer_(scoreConfig, query, propSharedLockSet);
case RELEVANCE_SCORE:
return createRelevanceScorer_(scoreConfig, relevanceScorer);
case POPULARITY_SCORE:
return createPopularityScorer_(scoreConfig);
default:
return NULL;
}
}
ProductScorer* ProductScorerFactory::createCustomScorer_(
const ProductScoreConfig& scoreConfig,
const std::string& query)
{
if (customRankManager_ == NULL)
return NULL;
CustomRankDocId customDocId;
bool result = customRankManager_->getCustomValue(query, customDocId);
if (result && !customDocId.topIds.empty())
return new CustomScorer(scoreConfig, customDocId.topIds);
return NULL;
}
ProductScorer* ProductScorerFactory::createCategoryScorer_(
const ProductScoreConfig& scoreConfig,
const std::string& query,
faceted::PropSharedLockSet& propSharedLockSet)
{
if (categoryClickLogger_ == NULL ||
categoryValueTable_ == NULL)
return NULL;
std::vector<faceted::PropValueTable::pvid_t> topLabels;
std::vector<int> topFreqs;
categoryClickLogger_->getFreqLabel(query, kTopLabelLimit,
topLabels, topFreqs);
if(topLabels.empty())
{
UString ustrQuery(query, UString::UTF_8);
UString backendCategory;
if(miningManager_->GetProductCategory(ustrQuery, backendCategory))
{
UString frontendCategory;
if(BackendLabelToFrontendLabel::Get()->Map(backendCategory,frontendCategory))
{
std::vector<std::vector<izenelib::util::UString> > groupPaths;
split_group_path(frontendCategory, groupPaths);
if(1 == groupPaths.size())
{
faceted::PropValueTable::pvid_t topLabel = categoryValueTable_->propValueId(groupPaths[0]);
topLabels.push_back(topLabel);
}
}
}
}
if (!topLabels.empty())
{
propSharedLockSet.insertSharedLock(categoryValueTable_);
return new CategoryScorer(scoreConfig, *categoryValueTable_, topLabels);
}
return NULL;
}
ProductScorer* ProductScorerFactory::createRelevanceScorer_(
const ProductScoreConfig& scoreConfig,
ProductScorer* relevanceScorer)
{
if (!relevanceScorer)
return NULL;
relevanceScorer->setWeight(scoreConfig.weight);
return relevanceScorer;
}
ProductScorer* ProductScorerFactory::createPopularityScorer_(
const ProductScoreConfig& scoreConfig)
{
if (!productScoreManager_)
return NULL;
return productScoreManager_->createProductScorer(scoreConfig);
}
|
fix compile warning "unused variable" in ProductScorerFactory.cpp
|
fix compile warning "unused variable" in ProductScorerFactory.cpp
|
C++
|
apache-2.0
|
pombredanne/sf1r-lite,izenecloud/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-ad-delivery,pombredanne/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-ad-delivery
|
dbdcf11778ac9500ce55affae8db89ac868c42da
|
src/blockchain_converter/blockchain_converter.cpp
|
src/blockchain_converter/blockchain_converter.cpp
|
// Copyright (c) 2014-2015, The Monero Project
//
// 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.
#include "include_base_utils.h"
#include "common/util.h"
#include "warnings.h"
#include "crypto/crypto.h"
#include "cryptonote_config.h"
#include "cryptonote_core/cryptonote_format_utils.h"
#include "misc_language.h"
#include "cryptonote_core/blockchain_storage.h"
#include "blockchain_db/blockchain_db.h"
#include "cryptonote_core/blockchain.h"
#include "blockchain_db/lmdb/db_lmdb.h"
#include "cryptonote_core/tx_pool.h"
#include "common/command_line.h"
#include "serialization/json_utils.h"
#include "include_base_utils.h"
#include "version.h"
#include <iostream>
// CONFIG
static bool opt_batch = true;
static bool opt_testnet = false;
// number of blocks per batch transaction
// adjustable through command-line argument according to available RAM
static uint64_t db_batch_size = 20000;
namespace po = boost::program_options;
using namespace cryptonote;
using namespace epee;
struct fake_core
{
Blockchain dummy;
tx_memory_pool m_pool;
blockchain_storage m_storage;
#if !defined(BLOCKCHAIN_DB)
// for multi_db_runtime:
fake_core(const boost::filesystem::path &path, const bool use_testnet) : dummy(m_pool), m_pool(&dummy), m_storage(m_pool)
#else
// for multi_db_compile:
fake_core(const boost::filesystem::path &path, const bool use_testnet) : dummy(m_pool), m_pool(dummy), m_storage(&m_pool)
#endif
{
m_pool.init(path.string());
m_storage.init(path.string(), use_testnet);
}
};
int main(int argc, char* argv[])
{
uint64_t height = 0;
uint64_t start_block = 0;
uint64_t end_block = 0;
uint64_t num_blocks = 0;
boost::filesystem::path default_data_path {tools::get_default_data_dir()};
boost::filesystem::path default_testnet_data_path {default_data_path / "testnet"};
po::options_description desc_cmd_only("Command line options");
po::options_description desc_cmd_sett("Command line options and settings options");
const command_line::arg_descriptor<uint32_t> arg_log_level = {"log-level", "", LOG_LEVEL_0};
const command_line::arg_descriptor<uint64_t> arg_batch_size = {"batch-size", "", db_batch_size};
const command_line::arg_descriptor<bool> arg_testnet_on = {
"testnet"
, "Run on testnet."
, opt_testnet
};
const command_line::arg_descriptor<uint64_t> arg_block_number =
{"block-number", "Number of blocks (default: use entire source blockchain)",
0};
command_line::add_arg(desc_cmd_sett, command_line::arg_data_dir, default_data_path.string());
command_line::add_arg(desc_cmd_sett, command_line::arg_testnet_data_dir, default_testnet_data_path.string());
command_line::add_arg(desc_cmd_sett, arg_log_level);
command_line::add_arg(desc_cmd_sett, arg_batch_size);
command_line::add_arg(desc_cmd_sett, arg_testnet_on);
command_line::add_arg(desc_cmd_sett, arg_block_number);
command_line::add_arg(desc_cmd_only, command_line::arg_help);
const command_line::arg_descriptor<bool> arg_batch = {"batch",
"Batch transactions for faster import", true};
// call add_options() directly for these arguments since command_line helpers
// support only boolean switch, not boolean argument
desc_cmd_sett.add_options()
(arg_batch.name, make_semantic(arg_batch), arg_batch.description)
;
po::options_description desc_options("Allowed options");
desc_options.add(desc_cmd_only).add(desc_cmd_sett);
po::variables_map vm;
bool r = command_line::handle_error_helper(desc_options, [&]()
{
po::store(po::parse_command_line(argc, argv, desc_options), vm);
po::notify(vm);
return true;
});
if (!r)
return 1;
int log_level = command_line::get_arg(vm, arg_log_level);
opt_batch = command_line::get_arg(vm, arg_batch);
db_batch_size = command_line::get_arg(vm, arg_batch_size);
if (command_line::get_arg(vm, command_line::arg_help))
{
std::cout << CRYPTONOTE_NAME << " v" << MONERO_VERSION_FULL << ENDL << ENDL;
std::cout << desc_options << std::endl;
return 1;
}
if (! opt_batch && ! vm["batch-size"].defaulted())
{
std::cerr << "Error: batch-size set, but batch option not enabled" << ENDL;
return 1;
}
if (! db_batch_size)
{
std::cerr << "Error: batch-size must be > 0" << ENDL;
return 1;
}
log_space::get_set_log_detalisation_level(true, log_level);
log_space::log_singletone::add_logger(LOGGER_CONSOLE, NULL, NULL);
LOG_PRINT_L0("Starting...");
std::string src_folder;
opt_testnet = command_line::get_arg(vm, arg_testnet_on);
auto data_dir_arg = opt_testnet ? command_line::arg_testnet_data_dir : command_line::arg_data_dir;
src_folder = command_line::get_arg(vm, data_dir_arg);
boost::filesystem::path dest_folder(src_folder);
num_blocks = command_line::get_arg(vm, arg_block_number);
if (opt_batch)
{
LOG_PRINT_L0("batch: " << std::boolalpha << opt_batch << std::noboolalpha
<< " batch size: " << db_batch_size);
}
else
{
LOG_PRINT_L0("batch: " << std::boolalpha << opt_batch << std::noboolalpha);
}
LOG_PRINT_L0("testnet: " << std::boolalpha << opt_testnet << std::noboolalpha);
fake_core c(src_folder, opt_testnet);
height = c.m_storage.get_current_blockchain_height();
if (! num_blocks || num_blocks > height)
end_block = height - 1;
else
end_block = start_block + num_blocks - 1;
BlockchainDB *blockchain;
blockchain = new BlockchainLMDB(opt_batch);
dest_folder /= blockchain->get_db_name();
LOG_PRINT_L0("Source blockchain: " << src_folder);
LOG_PRINT_L0("Dest blockchain: " << dest_folder.string());
LOG_PRINT_L0("Opening LMDB: " << dest_folder.string());
blockchain->open(dest_folder.string());
if (opt_batch)
blockchain->batch_start();
uint64_t i = 0;
for (i = start_block; i < end_block + 1; ++i)
{
// block: i height: i+1 end height: end_block + 1
if ((i+1) % 10 == 0)
{
std::cout << "\r \r" << "height " << i+1 << "/" <<
end_block+1 << " (" << (i+1)*100/(end_block+1)<< "%)" << std::flush;
}
// for debugging:
// std::cout << "height " << i+1 << "/" << end_block+1
// << " ((" << i+1 << ")*100/(end_block+1))" << "%)" << ENDL;
block b = c.m_storage.get_block(i);
size_t bsize = c.m_storage.get_block_size(i);
difficulty_type bdiff = c.m_storage.get_block_cumulative_difficulty(i);
uint64_t bcoins = c.m_storage.get_block_coins_generated(i);
std::vector<transaction> txs;
std::vector<crypto::hash> missed;
c.m_storage.get_transactions(b.tx_hashes, txs, missed);
if (missed.size())
{
std::cout << ENDL;
std::cerr << "Missed transaction(s) for block at height " << i + 1 << ", exiting" << ENDL;
delete blockchain;
return 1;
}
try
{
blockchain->add_block(b, bsize, bdiff, bcoins, txs);
if (opt_batch)
{
if ((i < end_block) && ((i + 1) % db_batch_size == 0))
{
std::cout << "\r \r";
std::cout << "[- batch commit at height " << i + 1 << " -]" << ENDL;
blockchain->batch_stop();
blockchain->batch_start();
std::cout << ENDL;
blockchain->show_stats();
}
}
}
catch (const std::exception& e)
{
std::cout << ENDL;
std::cerr << "Error adding block to new blockchain: " << e.what() << ENDL;
delete blockchain;
return 2;
}
}
if (opt_batch)
{
std::cout << "\r \r" << "height " << i << "/" <<
end_block+1 << " (" << (i)*100/(end_block+1)<< "%)" << std::flush;
std::cout << ENDL;
std::cout << "[- batch commit at height " << i << " -]" << ENDL;
blockchain->batch_stop();
}
std::cout << ENDL;
blockchain->show_stats();
std::cout << "Finished at height: " << i << " block: " << i-1 << ENDL;
delete blockchain;
return 0;
}
|
// Copyright (c) 2014-2015, The Monero Project
//
// 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.
#include "include_base_utils.h"
#include "common/util.h"
#include "warnings.h"
#include "crypto/crypto.h"
#include "cryptonote_config.h"
#include "cryptonote_core/cryptonote_format_utils.h"
#include "misc_language.h"
#include "cryptonote_core/blockchain_storage.h"
#include "blockchain_db/blockchain_db.h"
#include "cryptonote_core/blockchain.h"
#include "blockchain_db/lmdb/db_lmdb.h"
#include "cryptonote_core/tx_pool.h"
#include "common/command_line.h"
#include "serialization/json_utils.h"
#include "include_base_utils.h"
#include "version.h"
#include <iostream>
namespace
{
// CONFIG
bool opt_batch = true;
bool opt_resume = true;
bool opt_testnet = false;
// number of blocks per batch transaction
// adjustable through command-line argument according to available RAM
uint64_t db_batch_size = 20000;
}
namespace po = boost::program_options;
using namespace cryptonote;
using namespace epee;
struct fake_core
{
Blockchain dummy;
tx_memory_pool m_pool;
blockchain_storage m_storage;
#if !defined(BLOCKCHAIN_DB)
// for multi_db_runtime:
fake_core(const boost::filesystem::path &path, const bool use_testnet) : dummy(m_pool), m_pool(&dummy), m_storage(m_pool)
#else
// for multi_db_compile:
fake_core(const boost::filesystem::path &path, const bool use_testnet) : dummy(m_pool), m_pool(dummy), m_storage(&m_pool)
#endif
{
m_pool.init(path.string());
m_storage.init(path.string(), use_testnet);
}
};
int main(int argc, char* argv[])
{
uint64_t height = 0;
uint64_t start_block = 0;
uint64_t end_block = 0;
uint64_t num_blocks = 0;
boost::filesystem::path default_data_path {tools::get_default_data_dir()};
boost::filesystem::path default_testnet_data_path {default_data_path / "testnet"};
po::options_description desc_cmd_only("Command line options");
po::options_description desc_cmd_sett("Command line options and settings options");
const command_line::arg_descriptor<uint32_t> arg_log_level = {"log-level", "", LOG_LEVEL_0};
const command_line::arg_descriptor<uint64_t> arg_batch_size = {"batch-size", "", db_batch_size};
const command_line::arg_descriptor<bool> arg_testnet_on = {
"testnet"
, "Run on testnet."
, opt_testnet
};
const command_line::arg_descriptor<uint64_t> arg_block_number =
{"block-number", "Number of blocks (default: use entire source blockchain)",
0};
command_line::add_arg(desc_cmd_sett, command_line::arg_data_dir, default_data_path.string());
command_line::add_arg(desc_cmd_sett, command_line::arg_testnet_data_dir, default_testnet_data_path.string());
command_line::add_arg(desc_cmd_sett, arg_log_level);
command_line::add_arg(desc_cmd_sett, arg_batch_size);
command_line::add_arg(desc_cmd_sett, arg_testnet_on);
command_line::add_arg(desc_cmd_sett, arg_block_number);
command_line::add_arg(desc_cmd_only, command_line::arg_help);
const command_line::arg_descriptor<bool> arg_batch = {"batch",
"Batch transactions for faster import", true};
const command_line::arg_descriptor<bool> arg_resume = {"resume",
"Resume from current height if output database already exists", true};
// call add_options() directly for these arguments since command_line helpers
// support only boolean switch, not boolean argument
desc_cmd_sett.add_options()
(arg_batch.name, make_semantic(arg_batch), arg_batch.description)
(arg_resume.name, make_semantic(arg_resume), arg_resume.description)
;
po::options_description desc_options("Allowed options");
desc_options.add(desc_cmd_only).add(desc_cmd_sett);
po::variables_map vm;
bool r = command_line::handle_error_helper(desc_options, [&]()
{
po::store(po::parse_command_line(argc, argv, desc_options), vm);
po::notify(vm);
return true;
});
if (!r)
return 1;
int log_level = command_line::get_arg(vm, arg_log_level);
opt_batch = command_line::get_arg(vm, arg_batch);
opt_resume = command_line::get_arg(vm, arg_resume);
db_batch_size = command_line::get_arg(vm, arg_batch_size);
if (command_line::get_arg(vm, command_line::arg_help))
{
std::cout << CRYPTONOTE_NAME << " v" << MONERO_VERSION_FULL << ENDL << ENDL;
std::cout << desc_options << std::endl;
return 1;
}
if (! opt_batch && ! vm["batch-size"].defaulted())
{
std::cerr << "Error: batch-size set, but batch option not enabled" << ENDL;
return 1;
}
if (! db_batch_size)
{
std::cerr << "Error: batch-size must be > 0" << ENDL;
return 1;
}
log_space::get_set_log_detalisation_level(true, log_level);
log_space::log_singletone::add_logger(LOGGER_CONSOLE, NULL, NULL);
LOG_PRINT_L0("Starting...");
std::string src_folder;
opt_testnet = command_line::get_arg(vm, arg_testnet_on);
auto data_dir_arg = opt_testnet ? command_line::arg_testnet_data_dir : command_line::arg_data_dir;
src_folder = command_line::get_arg(vm, data_dir_arg);
boost::filesystem::path dest_folder(src_folder);
num_blocks = command_line::get_arg(vm, arg_block_number);
if (opt_batch)
{
LOG_PRINT_L0("batch: " << std::boolalpha << opt_batch << std::noboolalpha
<< " batch size: " << db_batch_size);
}
else
{
LOG_PRINT_L0("batch: " << std::boolalpha << opt_batch << std::noboolalpha);
}
LOG_PRINT_L0("resume: " << std::boolalpha << opt_resume << std::noboolalpha);
LOG_PRINT_L0("testnet: " << std::boolalpha << opt_testnet << std::noboolalpha);
fake_core c(src_folder, opt_testnet);
height = c.m_storage.get_current_blockchain_height();
BlockchainDB *blockchain;
blockchain = new BlockchainLMDB(opt_batch);
dest_folder /= blockchain->get_db_name();
LOG_PRINT_L0("Source blockchain: " << src_folder);
LOG_PRINT_L0("Dest blockchain: " << dest_folder.string());
LOG_PRINT_L0("Opening dest blockchain (BlockchainDB " << blockchain->get_db_name() << ")");
blockchain->open(dest_folder.string());
LOG_PRINT_L0("Source blockchain height: " << height);
LOG_PRINT_L0("Dest blockchain height: " << blockchain->height());
if (opt_resume)
// next block number to add is same as current height
start_block = blockchain->height();
if (! num_blocks || (start_block + num_blocks > height))
end_block = height - 1;
else
end_block = start_block + num_blocks - 1;
LOG_PRINT_L0("start height: " << start_block+1 << " stop height: " <<
end_block+1);
if (start_block > end_block)
{
LOG_PRINT_L0("Finished: no blocks to add");
delete blockchain;
return 0;
}
if (opt_batch)
blockchain->batch_start();
uint64_t i = 0;
for (i = start_block; i < end_block + 1; ++i)
{
// block: i height: i+1 end height: end_block + 1
if ((i+1) % 10 == 0)
{
std::cout << "\r \r" << "height " << i+1 << "/" <<
end_block+1 << " (" << (i+1)*100/(end_block+1)<< "%)" << std::flush;
}
// for debugging:
// std::cout << "height " << i+1 << "/" << end_block+1
// << " ((" << i+1 << ")*100/(end_block+1))" << "%)" << ENDL;
block b = c.m_storage.get_block(i);
size_t bsize = c.m_storage.get_block_size(i);
difficulty_type bdiff = c.m_storage.get_block_cumulative_difficulty(i);
uint64_t bcoins = c.m_storage.get_block_coins_generated(i);
std::vector<transaction> txs;
std::vector<crypto::hash> missed;
c.m_storage.get_transactions(b.tx_hashes, txs, missed);
if (missed.size())
{
std::cout << ENDL;
std::cerr << "Missed transaction(s) for block at height " << i + 1 << ", exiting" << ENDL;
delete blockchain;
return 1;
}
try
{
blockchain->add_block(b, bsize, bdiff, bcoins, txs);
if (opt_batch)
{
if ((i < end_block) && ((i + 1) % db_batch_size == 0))
{
std::cout << "\r \r";
std::cout << "[- batch commit at height " << i + 1 << " -]" << ENDL;
blockchain->batch_stop();
blockchain->batch_start();
std::cout << ENDL;
blockchain->show_stats();
}
}
}
catch (const std::exception& e)
{
std::cout << ENDL;
std::cerr << "Error adding block " << i << " to new blockchain: " << e.what() << ENDL;
delete blockchain;
return 2;
}
}
if (opt_batch)
{
std::cout << "\r \r" << "height " << i << "/" <<
end_block+1 << " (" << (i)*100/(end_block+1)<< "%)" << std::flush;
std::cout << ENDL;
std::cout << "[- batch commit at height " << i << " -]" << ENDL;
blockchain->batch_stop();
}
std::cout << ENDL;
blockchain->show_stats();
std::cout << "Finished at height: " << i << " block: " << i-1 << ENDL;
delete blockchain;
return 0;
}
|
Add support for resume from last block
|
blockchain_converter: Add support for resume from last block
Add option "--resume <on|off>" where default is on.
|
C++
|
bsd-3-clause
|
ranok/bitmonero,eiabea/bitmonero,eiabea/bitmonero,ranok/bitmonero,ranok/bitmonero,eiabea/bitmonero,eiabea/bitmonero,eiabea/bitmonero,ranok/bitmonero,ranok/bitmonero,eiabea/bitmonero,ranok/bitmonero
|
efac2170ca53586e6cd34e7ec7da88e7747f6d70
|
content/browser/accessibility/browser_accessibility_manager.cc
|
content/browser/accessibility/browser_accessibility_manager.cc
|
// 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 "content/browser/accessibility/browser_accessibility_manager.h"
#include "base/logging.h"
#include "content/browser/accessibility/browser_accessibility.h"
#include "content/common/accessibility_messages.h"
using content::AccessibilityNodeData;
BrowserAccessibility* BrowserAccessibilityFactory::Create() {
return BrowserAccessibility::Create();
}
// Start child IDs at -1 and decrement each time, because clients use
// child IDs of 1, 2, 3, ... to access the children of an object by
// index, so we use negative IDs to clearly distinguish between indices
// and unique IDs.
// static
int32 BrowserAccessibilityManager::next_child_id_ = -1;
#if !defined(OS_MACOSX) && \
!(defined(OS_WIN) && !defined(USE_AURA)) && \
!defined(TOOLKIT_GTK)
// We have subclassess of BrowserAccessibilityManager on Mac, Linux/GTK,
// and non-Aura Win. For any other platform, instantiate the base class.
// static
BrowserAccessibilityManager* BrowserAccessibilityManager::Create(
gfx::NativeView parent_view,
const AccessibilityNodeData& src,
BrowserAccessibilityDelegate* delegate,
BrowserAccessibilityFactory* factory) {
return new BrowserAccessibilityManager(
parent_view, src, delegate, factory);
}
#endif
// static
BrowserAccessibilityManager* BrowserAccessibilityManager::CreateEmptyDocument(
gfx::NativeView parent_view,
AccessibilityNodeData::State state,
BrowserAccessibilityDelegate* delegate,
BrowserAccessibilityFactory* factory) {
// Use empty document to process notifications
AccessibilityNodeData empty_document;
empty_document.id = 0;
empty_document.role = AccessibilityNodeData::ROLE_ROOT_WEB_AREA;
empty_document.state = state | (1 << AccessibilityNodeData::STATE_READONLY);
return BrowserAccessibilityManager::Create(
parent_view, empty_document, delegate, factory);
}
BrowserAccessibilityManager::BrowserAccessibilityManager(
gfx::NativeView parent_view,
const AccessibilityNodeData& src,
BrowserAccessibilityDelegate* delegate,
BrowserAccessibilityFactory* factory)
: parent_view_(parent_view),
delegate_(delegate),
factory_(factory),
focus_(NULL) {
root_ = CreateAccessibilityTree(NULL, src, 0, false);
if (!focus_)
SetFocus(root_, false);
}
// static
int32 BrowserAccessibilityManager::GetNextChildID() {
// Get the next child ID, and wrap around when we get near the end
// of a 32-bit integer range. It's okay to wrap around; we just want
// to avoid it as long as possible because clients may cache the ID of
// an object for a while to determine if they've seen it before.
next_child_id_--;
if (next_child_id_ == -2000000000)
next_child_id_ = -1;
return next_child_id_;
}
BrowserAccessibilityManager::~BrowserAccessibilityManager() {
// Clients could still hold references to some nodes of the tree, so
// calling InternalReleaseReference will make sure that as many nodes
// as possible are released now, and remaining nodes are marked as
// inactive so that calls to any methods on them will fail gracefully.
focus_->InternalReleaseReference(false);
root_->InternalReleaseReference(true);
}
BrowserAccessibility* BrowserAccessibilityManager::GetRoot() {
return root_;
}
BrowserAccessibility* BrowserAccessibilityManager::GetFromChildID(
int32 child_id) {
base::hash_map<int32, BrowserAccessibility*>::iterator iter =
child_id_map_.find(child_id);
if (iter != child_id_map_.end()) {
return iter->second;
} else {
return NULL;
}
}
BrowserAccessibility* BrowserAccessibilityManager::GetFromRendererID(
int32 renderer_id) {
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(renderer_id);
if (iter == renderer_id_to_child_id_map_.end())
return NULL;
int32 child_id = iter->second;
return GetFromChildID(child_id);
}
void BrowserAccessibilityManager::GotFocus() {
if (!focus_)
return;
NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);
}
void BrowserAccessibilityManager::Remove(int32 child_id, int32 renderer_id) {
child_id_map_.erase(child_id);
// TODO(ctguil): Investigate if hit. We should never have a newer entry.
DCHECK(renderer_id_to_child_id_map_[renderer_id] == child_id);
// Make sure we don't overwrite a newer entry (see UpdateNode for a possible
// corner case).
if (renderer_id_to_child_id_map_[renderer_id] == child_id)
renderer_id_to_child_id_map_.erase(renderer_id);
}
void BrowserAccessibilityManager::OnAccessibilityNotifications(
const std::vector<AccessibilityHostMsg_NotificationParams>& params) {
for (uint32 index = 0; index < params.size(); index++) {
const AccessibilityHostMsg_NotificationParams& param = params[index];
// Update the tree.
UpdateNode(param.acc_tree, param.includes_children);
// Find the node corresponding to the id that's the target of the
// notification (which may not be the root of the update tree).
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(param.id);
if (iter == renderer_id_to_child_id_map_.end()) {
continue;
}
int32 child_id = iter->second;
BrowserAccessibility* node = GetFromChildID(child_id);
if (!node) {
NOTREACHED();
continue;
}
int notification_type = param.notification_type;
if (notification_type == AccessibilityNotificationFocusChanged ||
notification_type == AccessibilityNotificationBlur) {
SetFocus(node, false);
// Don't send a native focus event if the window itself doesn't
// have focus.
if (delegate_ && !delegate_->HasFocus())
continue;
}
// Send the notification event to the operating system.
NotifyAccessibilityEvent(notification_type, node);
// Set initial focus when a page is loaded.
if (notification_type == AccessibilityNotificationLoadComplete) {
if (!focus_)
SetFocus(root_, false);
if (!delegate_ || delegate_->HasFocus())
NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);
}
}
}
gfx::NativeView BrowserAccessibilityManager::GetParentView() {
return parent_view_;
}
BrowserAccessibility* BrowserAccessibilityManager::GetFocus(
BrowserAccessibility* root) {
if (focus_ && (!root || focus_->IsDescendantOf(root)))
return focus_;
return NULL;
}
void BrowserAccessibilityManager::SetFocus(
BrowserAccessibility* node, bool notify) {
if (focus_ != node) {
if (focus_)
focus_->InternalReleaseReference(false);
focus_ = node;
if (focus_)
focus_->InternalAddReference();
}
if (notify && node && delegate_)
delegate_->SetAccessibilityFocus(node->renderer_id());
}
void BrowserAccessibilityManager::DoDefaultAction(
const BrowserAccessibility& node) {
if (delegate_)
delegate_->AccessibilityDoDefaultAction(node.renderer_id());
}
void BrowserAccessibilityManager::ScrollToMakeVisible(
const BrowserAccessibility& node, gfx::Rect subfocus) {
if (delegate_) {
delegate_->AccessibilityScrollToMakeVisible(node.renderer_id(), subfocus);
}
}
void BrowserAccessibilityManager::ScrollToPoint(
const BrowserAccessibility& node, gfx::Point point) {
if (delegate_) {
delegate_->AccessibilityScrollToPoint(node.renderer_id(), point);
}
}
void BrowserAccessibilityManager::SetTextSelection(
const BrowserAccessibility& node, int start_offset, int end_offset) {
if (delegate_) {
delegate_->AccessibilitySetTextSelection(
node.renderer_id(), start_offset, end_offset);
}
}
gfx::Rect BrowserAccessibilityManager::GetViewBounds() {
if (delegate_)
return delegate_->GetViewBounds();
return gfx::Rect();
}
void BrowserAccessibilityManager::UpdateNode(
const AccessibilityNodeData& src,
bool include_children) {
BrowserAccessibility* current = NULL;
// Look for the node to replace. Either we're replacing the whole tree
// (role is ROOT_WEB_AREA) or we look it up based on its renderer ID.
if (src.role == AccessibilityNodeData::ROLE_ROOT_WEB_AREA) {
current = root_;
} else {
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(src.id);
if (iter != renderer_id_to_child_id_map_.end()) {
int32 child_id = iter->second;
current = GetFromChildID(child_id);
}
}
// If we can't find the node to replace, we're out of sync with the
// renderer (this would be a bug).
DCHECK(current);
if (!current)
return;
// If this update is just for a single node (|include_children| is false),
// modify |current| directly and return - no tree changes are needed.
if (!include_children) {
DCHECK_EQ(0U, src.children.size());
current->PreInitialize(
this,
current->parent(),
current->child_id(),
current->index_in_parent(),
src);
current->PostInitialize();
return;
}
BrowserAccessibility* current_parent = current->parent();
int current_index_in_parent = current->index_in_parent();
// Detach all of the nodes in the old tree and get a single flat vector
// of all node pointers.
std::vector<BrowserAccessibility*> old_tree_nodes;
current->DetachTree(&old_tree_nodes);
// Build a new tree, reusing old nodes if possible. Each node that's
// reused will have its reference count incremented by one.
current = CreateAccessibilityTree(
current_parent, src, current_index_in_parent, true);
// Decrement the reference count of all nodes in the old tree, which will
// delete any nodes no longer needed.
for (int i = 0; i < static_cast<int>(old_tree_nodes.size()); i++)
old_tree_nodes[i]->InternalReleaseReference(false);
// If the only reference to the focused node is focus_ itself, then the
// focused node is no longer in the tree, so set the focus to the root.
if (focus_ && focus_->ref_count() == 1) {
SetFocus(root_, false);
if (delegate_ && delegate_->HasFocus())
NotifyAccessibilityEvent(AccessibilityNotificationBlur, focus_);
}
}
BrowserAccessibility* BrowserAccessibilityManager::CreateAccessibilityTree(
BrowserAccessibility* parent,
const AccessibilityNodeData& src,
int index_in_parent,
bool send_show_events) {
BrowserAccessibility* instance = NULL;
int32 child_id = 0;
bool children_can_send_show_events = send_show_events;
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(src.id);
// If a BrowserAccessibility instance for this ID already exists, add a
// new reference to it and retrieve its children vector.
if (iter != renderer_id_to_child_id_map_.end()) {
child_id = iter->second;
instance = GetFromChildID(child_id);
}
// If the node has changed roles, don't reuse a BrowserAccessibility
// object, that could confuse a screen reader.
// TODO(dtseng): Investigate when this gets hit; See crbug.com/93095.
DCHECK(!instance || instance->role() == src.role);
// If we're reusing a node, it should already be detached from a parent
// and any children. If not, that means we have a serious bug somewhere,
// like the same child is reachable from two places in the same tree.
if (instance && (instance->parent() != NULL || instance->child_count() > 0)) {
NOTREACHED();
instance = NULL;
}
if (instance) {
// If we're reusing a node, update its parent and increment its
// reference count.
instance->UpdateParent(parent, index_in_parent);
instance->InternalAddReference();
send_show_events = false;
} else {
// Otherwise, create a new instance.
instance = factory_->Create();
child_id = GetNextChildID();
children_can_send_show_events = false;
}
instance->PreInitialize(this, parent, child_id, index_in_parent, src);
child_id_map_[child_id] = instance;
renderer_id_to_child_id_map_[src.id] = child_id;
if ((src.state >> AccessibilityNodeData::STATE_FOCUSED) & 1)
SetFocus(instance, false);
for (int i = 0; i < static_cast<int>(src.children.size()); ++i) {
BrowserAccessibility* child = CreateAccessibilityTree(
instance, src.children[i], i, children_can_send_show_events);
instance->AddChild(child);
}
if (src.role == AccessibilityNodeData::ROLE_ROOT_WEB_AREA)
root_ = instance;
// Note: the purpose of send_show_events and children_can_send_show_events
// is so that we send a single ObjectShow event for the root of a subtree
// that just appeared for the first time, but not on any descendant of
// that subtree.
if (send_show_events)
NotifyAccessibilityEvent(AccessibilityNotificationObjectShow, instance);
instance->PostInitialize();
return instance;
}
|
// 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 "content/browser/accessibility/browser_accessibility_manager.h"
#include "base/logging.h"
#include "content/browser/accessibility/browser_accessibility.h"
#include "content/common/accessibility_messages.h"
using content::AccessibilityNodeData;
BrowserAccessibility* BrowserAccessibilityFactory::Create() {
return BrowserAccessibility::Create();
}
// Start child IDs at -1 and decrement each time, because clients use
// child IDs of 1, 2, 3, ... to access the children of an object by
// index, so we use negative IDs to clearly distinguish between indices
// and unique IDs.
// static
int32 BrowserAccessibilityManager::next_child_id_ = -1;
#if !defined(OS_MACOSX) && \
!(defined(OS_WIN) && !defined(USE_AURA)) && \
!defined(TOOLKIT_GTK)
// We have subclassess of BrowserAccessibilityManager on Mac, Linux/GTK,
// and non-Aura Win. For any other platform, instantiate the base class.
// static
BrowserAccessibilityManager* BrowserAccessibilityManager::Create(
gfx::NativeView parent_view,
const AccessibilityNodeData& src,
BrowserAccessibilityDelegate* delegate,
BrowserAccessibilityFactory* factory) {
return new BrowserAccessibilityManager(
parent_view, src, delegate, factory);
}
#endif
// static
BrowserAccessibilityManager* BrowserAccessibilityManager::CreateEmptyDocument(
gfx::NativeView parent_view,
AccessibilityNodeData::State state,
BrowserAccessibilityDelegate* delegate,
BrowserAccessibilityFactory* factory) {
// Use empty document to process notifications
AccessibilityNodeData empty_document;
empty_document.id = 0;
empty_document.role = AccessibilityNodeData::ROLE_ROOT_WEB_AREA;
empty_document.state = state | (1 << AccessibilityNodeData::STATE_READONLY);
return BrowserAccessibilityManager::Create(
parent_view, empty_document, delegate, factory);
}
BrowserAccessibilityManager::BrowserAccessibilityManager(
gfx::NativeView parent_view,
const AccessibilityNodeData& src,
BrowserAccessibilityDelegate* delegate,
BrowserAccessibilityFactory* factory)
: parent_view_(parent_view),
delegate_(delegate),
factory_(factory),
focus_(NULL) {
root_ = CreateAccessibilityTree(NULL, src, 0, false);
if (!focus_)
SetFocus(root_, false);
}
// static
int32 BrowserAccessibilityManager::GetNextChildID() {
// Get the next child ID, and wrap around when we get near the end
// of a 32-bit integer range. It's okay to wrap around; we just want
// to avoid it as long as possible because clients may cache the ID of
// an object for a while to determine if they've seen it before.
next_child_id_--;
if (next_child_id_ == -2000000000)
next_child_id_ = -1;
return next_child_id_;
}
BrowserAccessibilityManager::~BrowserAccessibilityManager() {
// Clients could still hold references to some nodes of the tree, so
// calling InternalReleaseReference will make sure that as many nodes
// as possible are released now, and remaining nodes are marked as
// inactive so that calls to any methods on them will fail gracefully.
focus_->InternalReleaseReference(false);
root_->InternalReleaseReference(true);
}
BrowserAccessibility* BrowserAccessibilityManager::GetRoot() {
return root_;
}
BrowserAccessibility* BrowserAccessibilityManager::GetFromChildID(
int32 child_id) {
base::hash_map<int32, BrowserAccessibility*>::iterator iter =
child_id_map_.find(child_id);
if (iter != child_id_map_.end()) {
return iter->second;
} else {
return NULL;
}
}
BrowserAccessibility* BrowserAccessibilityManager::GetFromRendererID(
int32 renderer_id) {
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(renderer_id);
if (iter == renderer_id_to_child_id_map_.end())
return NULL;
int32 child_id = iter->second;
return GetFromChildID(child_id);
}
void BrowserAccessibilityManager::GotFocus() {
if (!focus_)
return;
NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);
}
void BrowserAccessibilityManager::Remove(int32 child_id, int32 renderer_id) {
child_id_map_.erase(child_id);
// TODO(ctguil): Investigate if hit. We should never have a newer entry.
DCHECK(renderer_id_to_child_id_map_[renderer_id] == child_id);
// Make sure we don't overwrite a newer entry (see UpdateNode for a possible
// corner case).
if (renderer_id_to_child_id_map_[renderer_id] == child_id)
renderer_id_to_child_id_map_.erase(renderer_id);
}
void BrowserAccessibilityManager::OnAccessibilityNotifications(
const std::vector<AccessibilityHostMsg_NotificationParams>& params) {
for (uint32 index = 0; index < params.size(); index++) {
const AccessibilityHostMsg_NotificationParams& param = params[index];
// Update the tree.
UpdateNode(param.acc_tree, param.includes_children);
// Find the node corresponding to the id that's the target of the
// notification (which may not be the root of the update tree).
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(param.id);
if (iter == renderer_id_to_child_id_map_.end()) {
continue;
}
int32 child_id = iter->second;
BrowserAccessibility* node = GetFromChildID(child_id);
if (!node) {
NOTREACHED();
continue;
}
int notification_type = param.notification_type;
if (notification_type == AccessibilityNotificationFocusChanged ||
notification_type == AccessibilityNotificationBlur) {
SetFocus(node, false);
// Don't send a native focus event if the window itself doesn't
// have focus.
if (delegate_ && !delegate_->HasFocus())
continue;
}
// Send the notification event to the operating system.
NotifyAccessibilityEvent(notification_type, node);
// Set initial focus when a page is loaded.
if (notification_type == AccessibilityNotificationLoadComplete) {
if (!focus_)
SetFocus(root_, false);
if (!delegate_ || delegate_->HasFocus())
NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);
}
}
}
gfx::NativeView BrowserAccessibilityManager::GetParentView() {
return parent_view_;
}
BrowserAccessibility* BrowserAccessibilityManager::GetFocus(
BrowserAccessibility* root) {
if (focus_ && (!root || focus_->IsDescendantOf(root)))
return focus_;
return NULL;
}
void BrowserAccessibilityManager::SetFocus(
BrowserAccessibility* node, bool notify) {
if (focus_ != node) {
if (focus_)
focus_->InternalReleaseReference(false);
focus_ = node;
if (focus_)
focus_->InternalAddReference();
}
if (notify && node && delegate_)
delegate_->SetAccessibilityFocus(node->renderer_id());
}
void BrowserAccessibilityManager::DoDefaultAction(
const BrowserAccessibility& node) {
if (delegate_)
delegate_->AccessibilityDoDefaultAction(node.renderer_id());
}
void BrowserAccessibilityManager::ScrollToMakeVisible(
const BrowserAccessibility& node, gfx::Rect subfocus) {
if (delegate_) {
delegate_->AccessibilityScrollToMakeVisible(node.renderer_id(), subfocus);
}
}
void BrowserAccessibilityManager::ScrollToPoint(
const BrowserAccessibility& node, gfx::Point point) {
if (delegate_) {
delegate_->AccessibilityScrollToPoint(node.renderer_id(), point);
}
}
void BrowserAccessibilityManager::SetTextSelection(
const BrowserAccessibility& node, int start_offset, int end_offset) {
if (delegate_) {
delegate_->AccessibilitySetTextSelection(
node.renderer_id(), start_offset, end_offset);
}
}
gfx::Rect BrowserAccessibilityManager::GetViewBounds() {
if (delegate_)
return delegate_->GetViewBounds();
return gfx::Rect();
}
void BrowserAccessibilityManager::UpdateNode(
const AccessibilityNodeData& src,
bool include_children) {
BrowserAccessibility* current = NULL;
// Look for the node to replace. Either we're replacing the whole tree
// (role is ROOT_WEB_AREA) or we look it up based on its renderer ID.
if (src.role == AccessibilityNodeData::ROLE_ROOT_WEB_AREA) {
current = root_;
} else {
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(src.id);
if (iter != renderer_id_to_child_id_map_.end()) {
int32 child_id = iter->second;
current = GetFromChildID(child_id);
}
}
// If we can't find the node to replace, we're out of sync with the
// renderer (this would be a bug).
DCHECK(current);
if (!current)
return;
// If this update is just for a single node (|include_children| is false),
// modify |current| directly and return - no tree changes are needed.
if (!include_children) {
DCHECK_EQ(0U, src.children.size());
current->PreInitialize(
this,
current->parent(),
current->child_id(),
current->index_in_parent(),
src);
current->PostInitialize();
return;
}
BrowserAccessibility* current_parent = current->parent();
int current_index_in_parent = current->index_in_parent();
// Detach all of the nodes in the old tree and get a single flat vector
// of all node pointers.
std::vector<BrowserAccessibility*> old_tree_nodes;
current->DetachTree(&old_tree_nodes);
// Build a new tree, reusing old nodes if possible. Each node that's
// reused will have its reference count incremented by one.
CreateAccessibilityTree(current_parent, src, current_index_in_parent, true);
// Decrement the reference count of all nodes in the old tree, which will
// delete any nodes no longer needed.
for (int i = 0; i < static_cast<int>(old_tree_nodes.size()); i++)
old_tree_nodes[i]->InternalReleaseReference(false);
// If the only reference to the focused node is focus_ itself, then the
// focused node is no longer in the tree, so set the focus to the root.
if (focus_ && focus_->ref_count() == 1) {
SetFocus(root_, false);
if (delegate_ && delegate_->HasFocus())
NotifyAccessibilityEvent(AccessibilityNotificationBlur, focus_);
}
}
BrowserAccessibility* BrowserAccessibilityManager::CreateAccessibilityTree(
BrowserAccessibility* parent,
const AccessibilityNodeData& src,
int index_in_parent,
bool send_show_events) {
BrowserAccessibility* instance = NULL;
int32 child_id = 0;
bool children_can_send_show_events = send_show_events;
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(src.id);
// If a BrowserAccessibility instance for this ID already exists, add a
// new reference to it and retrieve its children vector.
if (iter != renderer_id_to_child_id_map_.end()) {
child_id = iter->second;
instance = GetFromChildID(child_id);
}
// If the node has changed roles, don't reuse a BrowserAccessibility
// object, that could confuse a screen reader.
// TODO(dtseng): Investigate when this gets hit; See crbug.com/93095.
DCHECK(!instance || instance->role() == src.role);
// If we're reusing a node, it should already be detached from a parent
// and any children. If not, that means we have a serious bug somewhere,
// like the same child is reachable from two places in the same tree.
if (instance && (instance->parent() != NULL || instance->child_count() > 0)) {
NOTREACHED();
instance = NULL;
}
if (instance) {
// If we're reusing a node, update its parent and increment its
// reference count.
instance->UpdateParent(parent, index_in_parent);
instance->InternalAddReference();
send_show_events = false;
} else {
// Otherwise, create a new instance.
instance = factory_->Create();
child_id = GetNextChildID();
children_can_send_show_events = false;
}
instance->PreInitialize(this, parent, child_id, index_in_parent, src);
child_id_map_[child_id] = instance;
renderer_id_to_child_id_map_[src.id] = child_id;
if ((src.state >> AccessibilityNodeData::STATE_FOCUSED) & 1)
SetFocus(instance, false);
for (int i = 0; i < static_cast<int>(src.children.size()); ++i) {
BrowserAccessibility* child = CreateAccessibilityTree(
instance, src.children[i], i, children_can_send_show_events);
instance->AddChild(child);
}
if (src.role == AccessibilityNodeData::ROLE_ROOT_WEB_AREA)
root_ = instance;
// Note: the purpose of send_show_events and children_can_send_show_events
// is so that we send a single ObjectShow event for the root of a subtree
// that just appeared for the first time, but not on any descendant of
// that subtree.
if (send_show_events)
NotifyAccessibilityEvent(AccessibilityNotificationObjectShow, instance);
instance->PostInitialize();
return instance;
}
|
Remove an unused return value.
|
Coverity: Remove an unused return value.
CID_COUNT=1
CID=104219
BUG=none
TEST=none
R=groby
TBR=dmazzoni
Review URL: https://chromiumcodereview.appspot.com/10576007
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@143199 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
keishi/chromium,bright-sparks/chromium-spacewalk,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,hujiajie/pa-chromium,Just-D/chromium-1,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,jaruba/chromium.src,zcbenz/cefode-chromium,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,littlstar/chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,patrickm/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,chuan9/chromium-crosswalk,keishi/chromium,M4sse/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,dednal/chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,zcbenz/cefode-chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk,ondra-novak/chromium.src,Jonekee/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,Fireblend/chromium-crosswalk,ltilve/chromium,keishi/chromium,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,ltilve/chromium,hujiajie/pa-chromium,timopulkkinen/BubbleFish,ltilve/chromium,mogoweb/chromium-crosswalk,keishi/chromium,PeterWangIntel/chromium-crosswalk,keishi/chromium,ondra-novak/chromium.src,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,Chilledheart/chromium,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,timopulkkinen/BubbleFish,dushu1203/chromium.src,nacl-webkit/chrome_deps,littlstar/chromium.src,markYoungH/chromium.src,patrickm/chromium.src,keishi/chromium,ltilve/chromium,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,Just-D/chromium-1,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,jaruba/chromium.src,Chilledheart/chromium,M4sse/chromium.src,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,anirudhSK/chromium,timopulkkinen/BubbleFish,ondra-novak/chromium.src,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,Chilledheart/chromium,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,jaruba/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,littlstar/chromium.src,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,M4sse/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,Jonekee/chromium.src,jaruba/chromium.src,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,dushu1203/chromium.src,axinging/chromium-crosswalk,zcbenz/cefode-chromium,dednal/chromium.src,ltilve/chromium,fujunwei/chromium-crosswalk,keishi/chromium,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,patrickm/chromium.src,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,jaruba/chromium.src,dednal/chromium.src,ChromiumWebApps/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,anirudhSK/chromium,M4sse/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk,jaruba/chromium.src,Jonekee/chromium.src,mogoweb/chromium-crosswalk,Jonekee/chromium.src,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,keishi/chromium,nacl-webkit/chrome_deps,dednal/chromium.src,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,keishi/chromium,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,jaruba/chromium.src,anirudhSK/chromium,dushu1203/chromium.src,littlstar/chromium.src,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,keishi/chromium,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,markYoungH/chromium.src,M4sse/chromium.src,hujiajie/pa-chromium,Just-D/chromium-1,anirudhSK/chromium,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,patrickm/chromium.src,keishi/chromium,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.