text stringlengths 54 60.6k |
|---|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <libxml/xmlstring.h>
#include <string.h>
#include <resourcemodel/TagLogger.hxx>
#include <resourcemodel/util.hxx>
#include <resourcemodel/QNameToString.hxx>
#include <boost/unordered_map.hpp>
using namespace css;
namespace writerfilter
{
TagLogger::TagLogger(const char* name)
: pWriter( nullptr ), pName( name )
{
}
TagLogger::~TagLogger()
{
pWriter = nullptr;
pName = nullptr;
}
#ifdef DEBUG_WRITERFILTER
void TagLogger::setFileName( const std::string & filename )
{
if ( pWriter )
endDocument();
std::string fileName;
char * temp = getenv("TAGLOGGERTMP");
if (temp != nullptr)
fileName += temp;
else
fileName += "/tmp";
std::string sPrefix = filename;
size_t nLastSlash = sPrefix.find_last_of('/');
size_t nLastBackslash = sPrefix.find_last_of('\\');
size_t nCutPos = nLastSlash;
if (nLastBackslash < nCutPos)
nCutPos = nLastBackslash;
if (nCutPos < sPrefix.size())
sPrefix = sPrefix.substr(nCutPos + 1);
fileName += "/";
fileName += sPrefix;
fileName += ".";
fileName += pName;
fileName += ".xml";
pWriter = xmlNewTextWriterFilename( fileName.c_str(), 0 );
xmlTextWriterSetIndent( pWriter, 4 );
}
void TagLogger::startDocument()
{
if (!pWriter)
return;
xmlTextWriterStartDocument( pWriter, nullptr, nullptr, nullptr );
xmlTextWriterStartElement( pWriter, BAD_CAST( "root" ) );
}
void TagLogger::endDocument()
{
if (!pWriter)
return;
xmlTextWriterEndDocument( pWriter );
xmlFreeTextWriter( pWriter );
pWriter = nullptr;
}
#endif
TagLogger::Pointer_t TagLogger::getInstance(const char * name)
{
typedef boost::unordered_map<std::string, TagLogger::Pointer_t> TagLoggerHashMap_t;
static TagLoggerHashMap_t tagLoggers;
TagLoggerHashMap_t::iterator aIt = tagLoggers.end();
std::string sName = name;
if (! tagLoggers.empty())
aIt = tagLoggers.find(sName);
if (aIt == tagLoggers.end())
{
TagLogger::Pointer_t pTagLogger(new TagLogger(name));
std::pair<std::string, TagLogger::Pointer_t> entry(sName, pTagLogger);
aIt = tagLoggers.insert(entry).first;
}
return aIt->second;
}
#ifdef DEBUG_WRITERFILTER
void TagLogger::element(const std::string & name)
{
startElement(name);
endElement();
}
void TagLogger::unoPropertySet(uno::Reference<beans::XPropertySet> rPropSet)
{
uno::Reference<beans::XPropertySetInfo> xPropSetInfo(rPropSet->getPropertySetInfo());
uno::Sequence<beans::Property> aProps(xPropSetInfo->getProperties());
startElement( "unoPropertySet" );
for (int i = 0; i < aProps.getLength(); ++i)
{
startElement( "property" );
OUString sName(aProps[i].Name);
attribute( "name", sName );
try
{
attribute( "value", rPropSet->getPropertyValue( sName ) );
}
catch (const uno::Exception &)
{
startElement( "exception" );
chars(std::string("getPropertyValue(\""));
chars(sName);
chars(std::string("\")"));
endElement( );
}
endElement( );
}
endElement( );
}
void TagLogger::startElement(const std::string & name)
{
if (!pWriter)
return;
xmlChar* xmlName = xmlCharStrdup( name.c_str() );
xmlTextWriterStartElement( pWriter, xmlName );
xmlFree( xmlName );
}
#endif
void TagLogger::attribute(const std::string & name, const std::string & value)
{
if (!pWriter)
return;
xmlChar* xmlName = xmlCharStrdup( name.c_str() );
xmlChar* xmlValue = xmlCharStrdup( value.c_str() );
xmlTextWriterWriteAttribute( pWriter, xmlName, xmlValue );
xmlFree( xmlValue );
xmlFree( xmlName );
}
#ifdef DEBUG_WRITERFILTER
void TagLogger::attribute(const std::string & name, const OUString & value)
{
attribute( name, OUStringToOString( value, RTL_TEXTENCODING_ASCII_US ).getStr() );
}
void TagLogger::attribute(const std::string & name, sal_uInt32 value)
{
if (!pWriter)
return;
xmlChar* xmlName = xmlCharStrdup( name.c_str() );
xmlTextWriterWriteFormatAttribute( pWriter, xmlName,
"%" SAL_PRIuUINT32, value );
xmlFree( xmlName );
}
void TagLogger::attribute(const std::string & name, const uno::Any aAny)
{
if (!pWriter)
return;
sal_Int32 nInt = 0;
float nFloat = 0.0;
OUString aStr;
xmlChar* xmlName = xmlCharStrdup( name.c_str() );
if ( aAny >>= nInt )
{
xmlTextWriterWriteFormatAttribute( pWriter, xmlName,
"%" SAL_PRIdINT32, nInt );
}
else if ( aAny >>= nFloat )
{
xmlTextWriterWriteFormatAttribute( pWriter, xmlName,
"%f", nFloat );
}
else if ( aAny >>= aStr )
{
attribute( name, aStr );
}
xmlFree( xmlName );
}
void TagLogger::chars(const std::string & rChars)
{
if (!pWriter)
return;
xmlChar* xmlChars = xmlCharStrdup( rChars.c_str() );
xmlTextWriterWriteString( pWriter, xmlChars );
xmlFree( xmlChars );
}
void TagLogger::chars(const OUString & rChars)
{
chars(OUStringToOString(rChars, RTL_TEXTENCODING_ASCII_US).getStr());
}
void TagLogger::endElement()
{
if (!pWriter)
return;
xmlTextWriterEndElement( pWriter );
}
class PropertySetDumpHandler : public Properties
{
IdToString::Pointer_t mpIdToString;
TagLogger* m_pLogger;
public:
PropertySetDumpHandler(TagLogger* pLogger,
IdToString::Pointer_t pIdToString);
virtual ~PropertySetDumpHandler();
void resolve(writerfilter::Reference<Properties>::Pointer_t props);
virtual void attribute(Id name, Value & val) SAL_OVERRIDE;
virtual void sprm(Sprm & sprm) SAL_OVERRIDE;
};
PropertySetDumpHandler::PropertySetDumpHandler(TagLogger* pLogger,
IdToString::Pointer_t pIdToString) :
mpIdToString(pIdToString),
m_pLogger(pLogger)
{
}
PropertySetDumpHandler::~PropertySetDumpHandler()
{
}
void PropertySetDumpHandler::resolve(
writerfilter::Reference<Properties>::Pointer_t pProps)
{
if (pProps.get() != nullptr)
pProps->resolve( *this );
}
void PropertySetDumpHandler::attribute(Id name, Value & val)
{
m_pLogger->startElement( "attribute" );
m_pLogger->attribute("name", (*QNameToString::Instance())(name));
m_pLogger->attribute("value", val.toString());
resolve(val.getProperties());
m_pLogger->endElement();
}
void PropertySetDumpHandler::sprm(Sprm & rSprm)
{
m_pLogger->startElement( "sprm" );
std::string sName;
if (mpIdToString != IdToString::Pointer_t())
sName = mpIdToString->toString(rSprm.getId());
m_pLogger->attribute( "name", sName );
m_pLogger->attribute( "id", rSprm.getId() );
m_pLogger->attribute( "value", rSprm.getValue()->toString() );
resolve( rSprm.getProps() );
m_pLogger->endElement();
}
#endif
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>loplugin:unreffun: PropertySetDumpHandler<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <libxml/xmlstring.h>
#include <string.h>
#include <resourcemodel/TagLogger.hxx>
#include <resourcemodel/util.hxx>
#include <resourcemodel/QNameToString.hxx>
#include <boost/unordered_map.hpp>
using namespace css;
namespace writerfilter
{
TagLogger::TagLogger(const char* name)
: pWriter( nullptr ), pName( name )
{
}
TagLogger::~TagLogger()
{
pWriter = nullptr;
pName = nullptr;
}
#ifdef DEBUG_WRITERFILTER
void TagLogger::setFileName( const std::string & filename )
{
if ( pWriter )
endDocument();
std::string fileName;
char * temp = getenv("TAGLOGGERTMP");
if (temp != nullptr)
fileName += temp;
else
fileName += "/tmp";
std::string sPrefix = filename;
size_t nLastSlash = sPrefix.find_last_of('/');
size_t nLastBackslash = sPrefix.find_last_of('\\');
size_t nCutPos = nLastSlash;
if (nLastBackslash < nCutPos)
nCutPos = nLastBackslash;
if (nCutPos < sPrefix.size())
sPrefix = sPrefix.substr(nCutPos + 1);
fileName += "/";
fileName += sPrefix;
fileName += ".";
fileName += pName;
fileName += ".xml";
pWriter = xmlNewTextWriterFilename( fileName.c_str(), 0 );
xmlTextWriterSetIndent( pWriter, 4 );
}
void TagLogger::startDocument()
{
if (!pWriter)
return;
xmlTextWriterStartDocument( pWriter, nullptr, nullptr, nullptr );
xmlTextWriterStartElement( pWriter, BAD_CAST( "root" ) );
}
void TagLogger::endDocument()
{
if (!pWriter)
return;
xmlTextWriterEndDocument( pWriter );
xmlFreeTextWriter( pWriter );
pWriter = nullptr;
}
#endif
TagLogger::Pointer_t TagLogger::getInstance(const char * name)
{
typedef boost::unordered_map<std::string, TagLogger::Pointer_t> TagLoggerHashMap_t;
static TagLoggerHashMap_t tagLoggers;
TagLoggerHashMap_t::iterator aIt = tagLoggers.end();
std::string sName = name;
if (! tagLoggers.empty())
aIt = tagLoggers.find(sName);
if (aIt == tagLoggers.end())
{
TagLogger::Pointer_t pTagLogger(new TagLogger(name));
std::pair<std::string, TagLogger::Pointer_t> entry(sName, pTagLogger);
aIt = tagLoggers.insert(entry).first;
}
return aIt->second;
}
#ifdef DEBUG_WRITERFILTER
void TagLogger::element(const std::string & name)
{
startElement(name);
endElement();
}
void TagLogger::unoPropertySet(uno::Reference<beans::XPropertySet> rPropSet)
{
uno::Reference<beans::XPropertySetInfo> xPropSetInfo(rPropSet->getPropertySetInfo());
uno::Sequence<beans::Property> aProps(xPropSetInfo->getProperties());
startElement( "unoPropertySet" );
for (int i = 0; i < aProps.getLength(); ++i)
{
startElement( "property" );
OUString sName(aProps[i].Name);
attribute( "name", sName );
try
{
attribute( "value", rPropSet->getPropertyValue( sName ) );
}
catch (const uno::Exception &)
{
startElement( "exception" );
chars(std::string("getPropertyValue(\""));
chars(sName);
chars(std::string("\")"));
endElement( );
}
endElement( );
}
endElement( );
}
void TagLogger::startElement(const std::string & name)
{
if (!pWriter)
return;
xmlChar* xmlName = xmlCharStrdup( name.c_str() );
xmlTextWriterStartElement( pWriter, xmlName );
xmlFree( xmlName );
}
#endif
void TagLogger::attribute(const std::string & name, const std::string & value)
{
if (!pWriter)
return;
xmlChar* xmlName = xmlCharStrdup( name.c_str() );
xmlChar* xmlValue = xmlCharStrdup( value.c_str() );
xmlTextWriterWriteAttribute( pWriter, xmlName, xmlValue );
xmlFree( xmlValue );
xmlFree( xmlName );
}
#ifdef DEBUG_WRITERFILTER
void TagLogger::attribute(const std::string & name, const OUString & value)
{
attribute( name, OUStringToOString( value, RTL_TEXTENCODING_ASCII_US ).getStr() );
}
void TagLogger::attribute(const std::string & name, sal_uInt32 value)
{
if (!pWriter)
return;
xmlChar* xmlName = xmlCharStrdup( name.c_str() );
xmlTextWriterWriteFormatAttribute( pWriter, xmlName,
"%" SAL_PRIuUINT32, value );
xmlFree( xmlName );
}
void TagLogger::attribute(const std::string & name, const uno::Any aAny)
{
if (!pWriter)
return;
sal_Int32 nInt = 0;
float nFloat = 0.0;
OUString aStr;
xmlChar* xmlName = xmlCharStrdup( name.c_str() );
if ( aAny >>= nInt )
{
xmlTextWriterWriteFormatAttribute( pWriter, xmlName,
"%" SAL_PRIdINT32, nInt );
}
else if ( aAny >>= nFloat )
{
xmlTextWriterWriteFormatAttribute( pWriter, xmlName,
"%f", nFloat );
}
else if ( aAny >>= aStr )
{
attribute( name, aStr );
}
xmlFree( xmlName );
}
void TagLogger::chars(const std::string & rChars)
{
if (!pWriter)
return;
xmlChar* xmlChars = xmlCharStrdup( rChars.c_str() );
xmlTextWriterWriteString( pWriter, xmlChars );
xmlFree( xmlChars );
}
void TagLogger::chars(const OUString & rChars)
{
chars(OUStringToOString(rChars, RTL_TEXTENCODING_ASCII_US).getStr());
}
void TagLogger::endElement()
{
if (!pWriter)
return;
xmlTextWriterEndElement( pWriter );
}
#endif
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// Allpass filter implementation
//
// Written by Jezar at Dreampoint, June 2000
// http://www.dreampoint.co.uk
// This code is public domain
#include "allpass.hpp"
allpass::allpass()
{
bufidx = 0;
}
void allpass::setbuffer(float *buf, int size)
{
buffer = buf;
bufsize = size;
}
void allpass::mute()
{
for (int i=0; i<bufsize; i++)
buffer[i]=0;
}
void allpass::setfeedback(float val)
{
feedback = val;
}
float allpass::getfeedback()
{
return feedback;
}
//ends
<commit_msg>Spatializer: init pointer member in constructor<commit_after>// Allpass filter implementation
//
// Written by Jezar at Dreampoint, June 2000
// http://www.dreampoint.co.uk
// This code is public domain
#include "allpass.hpp"
#include <stddef.h>
allpass::allpass()
{
bufidx = 0;
buffer = NULL;
}
void allpass::setbuffer(float *buf, int size)
{
buffer = buf;
bufsize = size;
}
void allpass::mute()
{
for (int i=0; i<bufsize; i++)
buffer[i]=0;
}
void allpass::setfeedback(float val)
{
feedback = val;
}
float allpass::getfeedback()
{
return feedback;
}
//ends
<|endoftext|> |
<commit_before>/*****************************************************************************
* cmd_playlist.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id$
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulière <ipkiss@via.ecp.fr>
*
* 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 "cmd_playlist.hpp"
#include <vlc_playlist.h>
#include "../src/vlcproc.hpp"
#include "../utils/var_bool.hpp"
void CmdPlaylistDel::execute()
{
m_rList.delSelected();
}
void CmdPlaylistNext::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist != NULL )
{
playlist_Next( pPlaylist );
}
}
void CmdPlaylistPrevious::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist != NULL )
{
playlist_Prev( pPlaylist );
}
}
void CmdPlaylistRandom::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist != NULL )
{
vlc_value_t val;
val.b_bool = m_value;
var_Set( pPlaylist , "random", val);
}
}
void CmdPlaylistLoop::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist != NULL )
{
vlc_value_t val;
val.b_bool = m_value;
var_Set( pPlaylist , "loop", val);
}
}
void CmdPlaylistRepeat::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist != NULL )
{
vlc_value_t val;
val.b_bool = m_value;
var_Set( pPlaylist , "repeat", val);
}
}
void CmdPlaylistLoad::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist != NULL )
playlist_Import( pPlaylist, m_file.c_str() );
}
void CmdPlaylistSave::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist != NULL )
{
static const char psz_xspf[] = "export-xspf",
psz_m3u[] = "export-m3u",
psz_html[] = "export-html";
const char *psz_module;
if( m_file.find( ".xsp", 0 ) != string::npos )
psz_module = psz_xspf;
else if( m_file.find( "m3u", 0 ) != string::npos )
psz_module = psz_m3u;
else if( m_file.find( "html", 0 ) != string::npos )
psz_module = psz_html;
else
{
msg_Err( getIntf(), "Impossible to recognise the file type" );
return;
}
playlist_Export( pPlaylist, m_file.c_str(), pPlaylist->p_local_category, psz_module );
}
}
void CmdPlaylistFirst::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
playlist_Lock( pPlaylist );
playlist_Control( pPlaylist, PLAYLIST_PLAY, pl_Locked );
playlist_Unlock( pPlaylist );
}
<commit_msg>skins2: factorize.<commit_after>/*****************************************************************************
* cmd_playlist.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id$
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulière <ipkiss@via.ecp.fr>
*
* 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 "cmd_playlist.hpp"
#include <vlc_playlist.h>
#include "../src/vlcproc.hpp"
#include "../utils/var_bool.hpp"
void CmdPlaylistDel::execute()
{
m_rList.delSelected();
}
void CmdPlaylistNext::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist != NULL )
{
playlist_Next( pPlaylist );
}
}
void CmdPlaylistPrevious::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist != NULL )
{
playlist_Prev( pPlaylist );
}
}
void CmdPlaylistRandom::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist != NULL )
var_SetBool( pPlaylist , "random", m_value );
}
void CmdPlaylistLoop::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist != NULL )
var_SetBool( pPlaylist , "loop", m_value );
}
void CmdPlaylistRepeat::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist != NULL )
var_SetBool( pPlaylist , "repeat", m_value );
}
void CmdPlaylistLoad::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist != NULL )
playlist_Import( pPlaylist, m_file.c_str() );
}
void CmdPlaylistSave::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
if( pPlaylist != NULL )
{
static const char psz_xspf[] = "export-xspf",
psz_m3u[] = "export-m3u",
psz_html[] = "export-html";
const char *psz_module;
if( m_file.find( ".xsp", 0 ) != string::npos )
psz_module = psz_xspf;
else if( m_file.find( "m3u", 0 ) != string::npos )
psz_module = psz_m3u;
else if( m_file.find( "html", 0 ) != string::npos )
psz_module = psz_html;
else
{
msg_Err( getIntf(), "Impossible to recognise the file type" );
return;
}
playlist_Export( pPlaylist, m_file.c_str(), pPlaylist->p_local_category, psz_module );
}
}
void CmdPlaylistFirst::execute()
{
playlist_t *pPlaylist = getIntf()->p_sys->p_playlist;
playlist_Control( pPlaylist, PLAYLIST_PLAY, pl_Unlocked );
}
<|endoftext|> |
<commit_before>#include "boost/filesystem.hpp"
#include "boost/program_options.hpp"
namespace fs = boost::filesystem;
namespace po = boost::program_options;
#include "opencv2/core.hpp"
using namespace cv;
#include "saliency/saliency.hpp"
#include "features/feature.hpp"
#include "util/opencv.hpp"
#include "util/file.hpp"
int main(int argc, char** argv)
{
/*
* Argument parsing
*/
po::options_description desc("Available options");
desc.add_options()
("help", "Show this message")
("input-path,i", po::value<std::string>(), "Input file path")
("output-file,o", po::value<std::string>(), "Output file path")
("output-dir,d", po::value<std::string>(), "Output directory")
("headless,hl", po::bool_switch()->default_value(false), "Run without graphical output")
;
po::positional_options_description p;
p.add("input-path", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.size() == 0 || vm.count("help") || !vm.count("input-path")) {
std::cout << "Usage: " << argv[0]
<< " [options] input-path" << std::endl
<< desc;
return 1;
}
if (vm["headless"].as<bool>()) GRAPHICAL = false;
/*
* Read image file
*
* - If input-path is a file, load image and create saliency map.
* Save output if output-file specified.
*
* - If input-path is a directory, load images and save output to
* output-dir if specified.
*/
fs::path in_path = fs::path(vm["input-path"].as<std::string>());
if (fs::is_regular_file(in_path))
{
// Load Image
Mat const img = imread(in_path.native(), CV_LOAD_IMAGE_COLOR);
if (!img.data)
{
throw std::runtime_error("Invalid input file: " + in_path.native());
return -1;
}
// Calculate saliency map
Mat out = getSaliency(img);
// Show input and output image side-by-side
showImageAndWait("Input - Output", {img, out});
// Save output if necessary
if (vm.count("output-file"))
{
Mat out_norm;
normalize(out, out_norm, 0.f, 255.f, NORM_MINMAX);
imwrite(vm["output-file"].as<std::string>(), out_norm);
}
}
else if (fs::is_directory(in_path))
{
paths ins = getUnprocessedImagePaths(in_path);
// If output-dir specified, write output files
// Also, calculate gradient image for constructing features
if (vm.count("output-dir"))
{
#pragma omp parallel for
for (int i = 0; i < ins.size(); i++)
{
path ipath = ins[i];
std::string osali = vm["output-dir"].as<std::string>() + "/" +
setSuffix(ins[i], "saliency").filename().string(),
ograd = vm["output-dir"].as<std::string>() + "/" +
setSuffix(ins[i], "grad").filename().string();
if (fs::exists(osali)) continue;
// Load Image
Mat const img = imread(ins[i].string(), CV_LOAD_IMAGE_COLOR);
if (!img.data)
{
std::cout << ins[i] << " is not a valid image." << std::endl;
continue;
}
std::cout << "> Processing\t" << i << "/" << ins.size()
<< ": " << ins[i] << "..." << std::endl;
// Calculate saliency and gradient map
Mat sali, grad, grey;
cvtColor(img, grey, CV_BGR2GRAY);
sali = getSaliency(img);
grad = getGradient(grey);
// Save calculated maps
std::cout << "> Writing\t" << i << "/" << ins.size()
<< ": " << osali << "..." << std::endl;
imwrite(osali, sali);
imwrite(ograd, grad);
}
}
else
{
Mat sali;
for (int i = 0; i < ins.size(); i++)
{
path ipath = ins[i];
// Load Image
Mat const img = imread(ins[i].string(), CV_LOAD_IMAGE_COLOR);
if (!img.data)
{
std::cout << ins[i] << " is not a valid image." << std::endl;
continue;
}
std::cout << "Processing " << ins[i] << "..." << std::endl;
// Calculate saliency map
sali = getSaliency(img);
// Show saliency map
showImageAndWait("Saliency: " + ipath.string(), sali);
}
}
}
return 0;
}
<commit_msg>Show input image for saliency bin<commit_after>#include "boost/filesystem.hpp"
#include "boost/program_options.hpp"
namespace fs = boost::filesystem;
namespace po = boost::program_options;
#include "opencv2/core.hpp"
using namespace cv;
#include "saliency/saliency.hpp"
#include "features/feature.hpp"
#include "util/opencv.hpp"
#include "util/file.hpp"
int main(int argc, char** argv)
{
/*
* Argument parsing
*/
po::options_description desc("Available options");
desc.add_options()
("help", "Show this message")
("input-path,i", po::value<std::string>(), "Input file path")
("output-file,o", po::value<std::string>(), "Output file path")
("output-dir,d", po::value<std::string>(), "Output directory")
("headless,hl", po::bool_switch()->default_value(false), "Run without graphical output")
;
po::positional_options_description p;
p.add("input-path", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.size() == 0 || vm.count("help") || !vm.count("input-path")) {
std::cout << "Usage: " << argv[0]
<< " [options] input-path" << std::endl
<< desc;
return 1;
}
if (vm["headless"].as<bool>()) GRAPHICAL = false;
/*
* Read image file
*
* - If input-path is a file, load image and create saliency map.
* Save output if output-file specified.
*
* - If input-path is a directory, load images and save output to
* output-dir if specified.
*/
fs::path in_path = fs::path(vm["input-path"].as<std::string>());
if (fs::is_regular_file(in_path))
{
// Load Image
Mat const img = imread(in_path.native(), CV_LOAD_IMAGE_COLOR);
if (!img.data)
{
throw std::runtime_error("Invalid input file: " + in_path.native());
return -1;
}
// Calculate saliency map
Mat out = getSaliency(img);
// Show input and output image side-by-side
showImageAndWait("Input - Output", {img, out});
// Save output if necessary
if (vm.count("output-file"))
{
Mat out_norm;
normalize(out, out_norm, 0.f, 255.f, NORM_MINMAX);
imwrite(vm["output-file"].as<std::string>(), out_norm);
}
}
else if (fs::is_directory(in_path))
{
paths ins = getUnprocessedImagePaths(in_path);
// If output-dir specified, write output files
// Also, calculate gradient image for constructing features
if (vm.count("output-dir"))
{
#pragma omp parallel for
for (int i = 0; i < ins.size(); i++)
{
path ipath = ins[i];
std::string osali = vm["output-dir"].as<std::string>() + "/" +
setSuffix(ins[i], "saliency").filename().string(),
ograd = vm["output-dir"].as<std::string>() + "/" +
setSuffix(ins[i], "grad").filename().string();
if (fs::exists(osali)) continue;
// Load Image
Mat const img = imread(ins[i].string(), CV_LOAD_IMAGE_COLOR);
if (!img.data)
{
std::cout << ins[i] << " is not a valid image." << std::endl;
continue;
}
std::cout << "> Processing\t" << i << "/" << ins.size()
<< ": " << ins[i] << "..." << std::endl;
// Calculate saliency and gradient map
Mat sali, grad, grey;
cvtColor(img, grey, CV_BGR2GRAY);
sali = getSaliency(img);
grad = getGradient(grey);
// Save calculated maps
std::cout << "> Writing\t" << i << "/" << ins.size()
<< ": " << osali << "..." << std::endl;
imwrite(osali, sali);
imwrite(ograd, grad);
}
}
else
{
Mat sali;
for (int i = 0; i < ins.size(); i++)
{
path ipath = ins[i];
// Load Image
Mat const img = imread(ins[i].string(), CV_LOAD_IMAGE_COLOR);
if (!img.data)
{
std::cout << ins[i] << " is not a valid image." << std::endl;
continue;
}
std::cout << "Processing " << ins[i] << "..." << std::endl;
// Calculate saliency map
sali = getSaliency(img);
// Show saliency map
showImageAndWait("Input - Saliency", {img, sali});
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>// Cellular Automata with * in terminal
// Sammy Hasan
// 2017
/*
rule 30 for chaos
*/
# include <iostream>
# include <cstdlib>
# include <algorithm>
# include <vector>
# include <bitset>
# include <thread>
# include <chrono>
using namespace std;
int g(){
return rand()%2;
}
int t(int i,int j, int k,const int rule){
string result = " ";
// cout << j << " : "<< i << " : " << k << endl;
string binary;
binary = to_string(j) + to_string(i) + to_string(k);
unsigned int ix = bitset<32>(binary).to_ulong();
string rule_str = bitset<8>(rule).to_string();
result = rule_str[rule_str.length()-ix-1];
// cout << "Rule: " << rule_str << " Result: " << result << " ix: " << ix << endl;
return stoi(result);
}
int main(int argc, const char** argv){
int rule = 30;
if (argc >= 2){
rule = atoi (argv[1]);
}
cout << "Using Rule: " << rule << endl;
vector<int> stream(70);
vector<int> padded;
generate(stream.begin(),stream.end(),g);
generate(stream.begin(),stream.end(),[](){return rand()%2;});
for(int x = 0;x<5000;x++){
this_thread::sleep_for(chrono::milliseconds(100));
padded = stream;
padded.insert(padded.begin(),stream.front());
padded.insert(padded.end(),stream.back());
stream.clear();
for(auto i = padded.begin()+1; i != padded.end()-1;i++){
// t(*i,*(i-1),*(i+1),rule);
stream.push_back(t(*i,*(i-1),*(i+1),rule));
}
for(int i : stream){
cout << ((i == 1)? "\u25A0" : " ");
}
cout << endl;
}
return 0;
}
<commit_msg>update<commit_after>// Cellular Automata with * in terminal
// Sammy Hasan
// 2017
/*
rule 30 for chaos
*/
# include <iostream>
# include <cstdlib>
# include <algorithm>
# include <vector>
# include <bitset>
# include <thread>
# include <chrono>
using namespace std;
int t(int i,int j, int k,const int rule){
string result = " ";
// cout << j << " : "<< i << " : " << k << endl;
string binary;
binary = to_string(j) + to_string(i) + to_string(k);
unsigned int ix = bitset<32>(binary).to_ulong();
string rule_str = bitset<8>(rule).to_string();
result = rule_str[rule_str.length()-ix-1];
// cout << "Rule: " << rule_str << " Result: " << result << " ix: " << ix << endl;
return stoi(result);
}
int main(int argc, const char** argv){
int rule = 30;
if (argc >= 2){
rule = atoi (argv[1]);
}
cout << "Using Rule: " << rule << endl;
vector<int> stream(70);
vector<int> padded;
generate(stream.begin(),stream.end(),[](){return rand()%2;});
for(int x = 0;x<5000;x++){
this_thread::sleep_for(chrono::milliseconds(100));
padded = stream;
padded.insert(padded.begin(),stream.front());
padded.insert(padded.end(),stream.back());
stream.clear();
for(auto i = padded.begin()+1; i != padded.end()-1;i++){
// t(*i,*(i-1),*(i+1),rule);
stream.push_back(t(*i,*(i-1),*(i+1),rule));
}
for(int i : stream){
cout << ((i == 1)? "\u25A0" : " ");
}
cout << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* DOMParser.cpp
*****************************************************************************
* Copyright (C) 2010 - 2011 Klagenfurt University
*
* Created on: Aug 10, 2010
* Authors: Christopher Mueller <christopher.mueller@itec.uni-klu.ac.at>
* Christian Timmerer <christian.timmerer@itec.uni-klu.ac.at>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 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 Lesser 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.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "DOMParser.h"
using namespace dash::xml;
using namespace dash::http;
using namespace dash::mpd;
DOMParser::DOMParser (stream_t *stream) :
root( NULL ),
stream( stream ),
vlc_xml( NULL ),
vlc_reader( NULL )
{
}
DOMParser::~DOMParser ()
{
delete this->root;
if(this->vlc_reader)
xml_ReaderDelete(this->vlc_reader);
if ( this->vlc_xml )
xml_Delete( this->vlc_xml );
}
Node* DOMParser::getRootNode ()
{
return this->root;
}
bool DOMParser::parse ()
{
this->vlc_xml = xml_Create(this->stream);
if(!this->vlc_xml)
return false;
this->vlc_reader = xml_ReaderCreate(this->vlc_xml, this->stream);
if(!this->vlc_reader)
return false;
this->root = this->processNode();
return true;
}
Node* DOMParser::processNode ()
{
const char *data;
int type = xml_ReaderNextNode(this->vlc_reader, &data);
if(type != -1 && type != XML_READER_TEXT && type != XML_READER_NONE && type != XML_READER_ENDELEM)
{
Node *node = new Node();
std::string name = data;
bool isEmpty = xml_ReaderIsEmptyElement(this->vlc_reader);
node->setName(name);
this->addAttributesToNode(node);
if(isEmpty)
return node;
Node *subnode = NULL;
while((subnode = this->processNode()) != NULL)
node->addSubNode(subnode);
return node;
}
return NULL;
}
void DOMParser::addAttributesToNode (Node *node)
{
const char *attrValue;
const char *attrName;
while((attrName = xml_ReaderNextAttr(this->vlc_reader, &attrValue)) != NULL)
{
std::string key = attrName;
std::string value = attrValue;
node->addAttribute(key, value);
}
}
void DOMParser::print (Node *node, int offset)
{
for(int i = 0; i < offset; i++)
msg_Dbg(this->stream, " ");
msg_Dbg(this->stream, "%s", node->getName().c_str());
std::vector<std::string> keys = node->getAttributeKeys();
for(size_t i = 0; i < keys.size(); i++)
msg_Dbg(this->stream, " %s=%s", keys.at(i).c_str(), node->getAttributeValue(keys.at(i)).c_str());
msg_Dbg(this->stream, "\n");
offset++;
for(size_t i = 0; i < node->getSubNodes().size(); i++)
{
this->print(node->getSubNodes().at(i), offset);
}
}
void DOMParser::print ()
{
this->print(this->root, 0);
}
Profile DOMParser::getProfile (dash::xml::Node *node)
{
std::string profile = node->getAttributeValue("profiles");
if(!profile.compare("urn:mpeg:mpegB:profile:dash:isoff-basic-on-demand:cm"))
return dash::mpd::BasicCM;
return dash::mpd::NotValid;
}
bool DOMParser::isDash (stream_t *stream)
{
const uint8_t *peek;
const char* psz_namespace = "urn:mpeg:mpegB:schema:DASH:MPD:DIS2011";
if(stream_Peek(stream, &peek, 1024) < (int)strlen(psz_namespace))
return false;
const char *p = strstr((const char*)peek, psz_namespace );
return p != NULL;
}
<commit_msg>Fixed potential out of bound reads in DASH probe function.<commit_after>/*
* DOMParser.cpp
*****************************************************************************
* Copyright (C) 2010 - 2011 Klagenfurt University
*
* Created on: Aug 10, 2010
* Authors: Christopher Mueller <christopher.mueller@itec.uni-klu.ac.at>
* Christian Timmerer <christian.timmerer@itec.uni-klu.ac.at>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 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 Lesser 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.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "DOMParser.h"
using namespace dash::xml;
using namespace dash::http;
using namespace dash::mpd;
DOMParser::DOMParser (stream_t *stream) :
root( NULL ),
stream( stream ),
vlc_xml( NULL ),
vlc_reader( NULL )
{
}
DOMParser::~DOMParser ()
{
delete this->root;
if(this->vlc_reader)
xml_ReaderDelete(this->vlc_reader);
if ( this->vlc_xml )
xml_Delete( this->vlc_xml );
}
Node* DOMParser::getRootNode ()
{
return this->root;
}
bool DOMParser::parse ()
{
this->vlc_xml = xml_Create(this->stream);
if(!this->vlc_xml)
return false;
this->vlc_reader = xml_ReaderCreate(this->vlc_xml, this->stream);
if(!this->vlc_reader)
return false;
this->root = this->processNode();
return true;
}
Node* DOMParser::processNode ()
{
const char *data;
int type = xml_ReaderNextNode(this->vlc_reader, &data);
if(type != -1 && type != XML_READER_TEXT && type != XML_READER_NONE && type != XML_READER_ENDELEM)
{
Node *node = new Node();
std::string name = data;
bool isEmpty = xml_ReaderIsEmptyElement(this->vlc_reader);
node->setName(name);
this->addAttributesToNode(node);
if(isEmpty)
return node;
Node *subnode = NULL;
while((subnode = this->processNode()) != NULL)
node->addSubNode(subnode);
return node;
}
return NULL;
}
void DOMParser::addAttributesToNode (Node *node)
{
const char *attrValue;
const char *attrName;
while((attrName = xml_ReaderNextAttr(this->vlc_reader, &attrValue)) != NULL)
{
std::string key = attrName;
std::string value = attrValue;
node->addAttribute(key, value);
}
}
void DOMParser::print (Node *node, int offset)
{
for(int i = 0; i < offset; i++)
msg_Dbg(this->stream, " ");
msg_Dbg(this->stream, "%s", node->getName().c_str());
std::vector<std::string> keys = node->getAttributeKeys();
for(size_t i = 0; i < keys.size(); i++)
msg_Dbg(this->stream, " %s=%s", keys.at(i).c_str(), node->getAttributeValue(keys.at(i)).c_str());
msg_Dbg(this->stream, "\n");
offset++;
for(size_t i = 0; i < node->getSubNodes().size(); i++)
{
this->print(node->getSubNodes().at(i), offset);
}
}
void DOMParser::print ()
{
this->print(this->root, 0);
}
Profile DOMParser::getProfile (dash::xml::Node *node)
{
std::string profile = node->getAttributeValue("profiles");
if(!profile.compare("urn:mpeg:mpegB:profile:dash:isoff-basic-on-demand:cm"))
return dash::mpd::BasicCM;
return dash::mpd::NotValid;
}
bool DOMParser::isDash (stream_t *stream)
{
const char* psz_namespace = "urn:mpeg:mpegB:schema:DASH:MPD:DIS2011";
const uint8_t *peek;
int peek_size = stream_Peek(stream, &peek, 1024);
if (peek_size < (int)strlen(psz_namespace))
return false;
std::string header((const char*)peek, peek_size);
return header.find(psz_namespace) != std::string::npos;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* 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 <algorithm>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <fc/io/json.hpp>
#include <fc/io/stdio.hpp>
#include <fc/network/http/server.hpp>
#include <fc/network/http/websocket.hpp>
#include <fc/rpc/cli.hpp>
#include <fc/rpc/http_api.hpp>
#include <fc/rpc/websocket_api.hpp>
#include <fc/smart_ref_impl.hpp>
#include <graphene/app/api.hpp>
#include <graphene/chain/protocol/protocol.hpp>
#include <graphene/egenesis/egenesis.hpp>
#include <graphene/utilities/key_conversion.hpp>
#include <graphene/wallet/wallet.hpp>
#include <fc/interprocess/signals.hpp>
#include <boost/program_options.hpp>
#include <fc/log/console_appender.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/logger.hpp>
#include <fc/log/logger_config.hpp>
#ifndef WIN32
#include <csignal>
#endif
using namespace graphene::app;
using namespace graphene::chain;
using namespace graphene::utilities;
using namespace graphene::wallet;
using namespace std;
namespace bpo = boost::program_options;
int main( int argc, char** argv )
{
try {
boost::program_options::options_description opts;
opts.add_options()
("help,h", "Print this help message and exit.")
("server-rpc-endpoint,s", bpo::value<string>()->implicit_value("ws://127.0.0.1:8090"), "Server websocket RPC endpoint")
("server-rpc-user,u", bpo::value<string>(), "Server Username")
("server-rpc-password,p", bpo::value<string>(), "Server Password")
("rpc-endpoint,r", bpo::value<string>()->implicit_value("127.0.0.1:8091"), "Endpoint for wallet websocket RPC to listen on")
("rpc-tls-endpoint,t", bpo::value<string>()->implicit_value("127.0.0.1:8092"), "Endpoint for wallet websocket TLS RPC to listen on")
("rpc-tls-certificate,c", bpo::value<string>()->implicit_value("server.pem"), "PEM certificate for wallet websocket TLS RPC")
("rpc-http-endpoint,H", bpo::value<string>()->implicit_value("127.0.0.1:8093"), "Endpoint for wallet HTTP RPC to listen on")
("daemon,d", "Run the wallet in daemon mode" )
("wallet-file,w", bpo::value<string>()->implicit_value("wallet.json"), "wallet to load")
("chain-id", bpo::value<string>(), "chain ID to connect to");
bpo::variables_map options;
bpo::store( bpo::parse_command_line(argc, argv, opts), options );
if( options.count("help") )
{
std::cout << opts << "\n";
return 0;
}
fc::path data_dir;
fc::logging_config cfg;
fc::path log_dir = data_dir / "logs";
fc::file_appender::config ac;
ac.filename = log_dir / "rpc" / "rpc.log";
ac.flush = true;
ac.rotate = true;
ac.rotation_interval = fc::hours( 1 );
ac.rotation_limit = fc::days( 1 );
std::cout << "Logging RPC to file: " << (data_dir / ac.filename).preferred_string() << "\n";
cfg.appenders.push_back(fc::appender_config( "default", "console", fc::variant(fc::console_appender::config())));
cfg.appenders.push_back(fc::appender_config( "rpc", "file", fc::variant(ac)));
cfg.loggers = { fc::logger_config("default"), fc::logger_config( "rpc") };
cfg.loggers.front().level = fc::log_level::info;
cfg.loggers.front().appenders = {"default"};
cfg.loggers.back().level = fc::log_level::debug;
cfg.loggers.back().appenders = {"rpc"};
//fc::configure_logging( cfg );
fc::ecc::private_key committee_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("null_key")));
idump( (key_to_wif( committee_private_key ) ) );
fc::ecc::private_key nathan_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("nathan")));
public_key_type nathan_pub_key = nathan_private_key.get_public_key();
idump( (nathan_pub_key) );
idump( (key_to_wif( nathan_private_key ) ) );
//
// TODO: We read wallet_data twice, once in main() to grab the
// socket info, again in wallet_api when we do
// load_wallet_file(). Seems like this could be better
// designed.
//
wallet_data wdata;
fc::path wallet_file( options.count("wallet-file") ? options.at("wallet-file").as<string>() : "wallet.json");
if( fc::exists( wallet_file ) )
{
wdata = fc::json::from_file( wallet_file ).as<wallet_data>();
if( options.count("chain-id") )
{
// the --chain-id on the CLI must match the chain ID embedded in the wallet file
if( chain_id_type(options.at("chain-id").as<std::string>()) != wdata.chain_id )
{
std::cout << "Chain ID in wallet file does not match specified chain ID\n";
return 1;
}
}
}
else
{
if( options.count("chain-id") )
{
wdata.chain_id = chain_id_type(options.at("chain-id").as<std::string>());
std::cout << "Starting a new wallet with chain ID " << wdata.chain_id.str() << " (from CLI)\n";
}
else
{
wdata.chain_id = graphene::egenesis::get_egenesis_chain_id();
std::cout << "Starting a new wallet with chain ID " << wdata.chain_id.str() << " (from egenesis)\n";
}
}
// but allow CLI to override
if( options.count("server-rpc-endpoint") )
wdata.ws_server = options.at("server-rpc-endpoint").as<std::string>();
if( options.count("server-rpc-user") )
wdata.ws_user = options.at("server-rpc-user").as<std::string>();
if( options.count("server-rpc-password") )
wdata.ws_password = options.at("server-rpc-password").as<std::string>();
fc::http::websocket_client client;
idump((wdata.ws_server));
auto con = client.connect( wdata.ws_server );
auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con);
auto remote_api = apic->get_remote_api< login_api >(1);
edump((wdata.ws_user)(wdata.ws_password) );
// TODO: Error message here
FC_ASSERT( remote_api->login( wdata.ws_user, wdata.ws_password ) );
auto wapiptr = std::make_shared<wallet_api>( wdata, remote_api );
wapiptr->set_wallet_filename( wallet_file.generic_string() );
wapiptr->load_wallet_file();
fc::api<wallet_api> wapi(wapiptr);
auto wallet_cli = std::make_shared<fc::rpc::cli>();
for( auto& name_formatter : wapiptr->get_result_formatters() )
wallet_cli->format_result( name_formatter.first, name_formatter.second );
boost::signals2::scoped_connection closed_connection(con->closed.connect([]{
cerr << "Server has disconnected us.\n";
}));
(void)(closed_connection);
if( wapiptr->is_new() )
{
std::cout << "Please use the set_password method to initialize a new wallet before continuing\n";
wallet_cli->set_prompt( "new >>> " );
} else
wallet_cli->set_prompt( "locked >>> " );
boost::signals2::scoped_connection locked_connection(wapiptr->lock_changed.connect([&](bool locked) {
wallet_cli->set_prompt( locked ? "locked >>> " : "unlocked >>> " );
}));
auto _websocket_server = std::make_shared<fc::http::websocket_server>();
if( options.count("rpc-endpoint") )
{
_websocket_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){
std::cout << "here... \n";
wlog("." );
auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);
wsc->register_api(wapi);
c->set_session_data( wsc );
});
ilog( "Listening for incoming RPC requests on ${p}", ("p", options.at("rpc-endpoint").as<string>() ));
_websocket_server->listen( fc::ip::endpoint::from_string(options.at("rpc-endpoint").as<string>()) );
_websocket_server->start_accept();
}
string cert_pem = "server.pem";
if( options.count( "rpc-tls-certificate" ) )
cert_pem = options.at("rpc-tls-certificate").as<string>();
auto _websocket_tls_server = std::make_shared<fc::http::websocket_tls_server>(cert_pem);
if( options.count("rpc-tls-endpoint") )
{
_websocket_tls_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){
auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);
wsc->register_api(wapi);
c->set_session_data( wsc );
});
ilog( "Listening for incoming TLS RPC requests on ${p}", ("p", options.at("rpc-tls-endpoint").as<string>() ));
_websocket_tls_server->listen( fc::ip::endpoint::from_string(options.at("rpc-tls-endpoint").as<string>()) );
_websocket_tls_server->start_accept();
}
auto _http_server = std::make_shared<fc::http::server>();
if( options.count("rpc-http-endpoint" ) )
{
ilog( "Listening for incoming HTTP RPC requests on ${p}", ("p", options.at("rpc-http-endpoint").as<string>() ) );
_http_server->listen( fc::ip::endpoint::from_string( options.at( "rpc-http-endpoint" ).as<string>() ) );
//
// due to implementation, on_request() must come AFTER listen()
//
_http_server->on_request(
[&]( const fc::http::request& req, const fc::http::server::response& resp )
{
std::shared_ptr< fc::rpc::http_api_connection > conn =
std::make_shared< fc::rpc::http_api_connection>();
conn->register_api( wapi );
conn->on_request( req, resp );
} );
}
if( !options.count( "daemon" ) )
{
wallet_cli->register_api( wapi );
wallet_cli->start();
wallet_cli->wait();
}
else
{
fc::promise<int>::ptr exit_promise = new fc::promise<int>("UNIX Signal Handler");
#ifdef __unix__
fc::set_signal_handler([&exit_promise](int signal) {
exit_promise->set_value(signal);
}, SIGINT);
#endif
ilog( "Entering Daemon Mode, ^C to exit" );
exit_promise->wait();
}
wapi->save_wallet_file(wallet_file.generic_string());
locked_connection.disconnect();
closed_connection.disconnect();
}
catch ( const fc::exception& e )
{
std::cout << e.to_detail_string() << "\n";
return -1;
}
return 0;
}
<commit_msg>cli_wallet: Exit instead of hanging when disconnected #291<commit_after>/*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* 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 <algorithm>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <fc/io/json.hpp>
#include <fc/io/stdio.hpp>
#include <fc/network/http/server.hpp>
#include <fc/network/http/websocket.hpp>
#include <fc/rpc/cli.hpp>
#include <fc/rpc/http_api.hpp>
#include <fc/rpc/websocket_api.hpp>
#include <fc/smart_ref_impl.hpp>
#include <graphene/app/api.hpp>
#include <graphene/chain/protocol/protocol.hpp>
#include <graphene/egenesis/egenesis.hpp>
#include <graphene/utilities/key_conversion.hpp>
#include <graphene/wallet/wallet.hpp>
#include <fc/interprocess/signals.hpp>
#include <boost/program_options.hpp>
#include <fc/log/console_appender.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/logger.hpp>
#include <fc/log/logger_config.hpp>
#ifndef WIN32
#include <csignal>
#endif
using namespace graphene::app;
using namespace graphene::chain;
using namespace graphene::utilities;
using namespace graphene::wallet;
using namespace std;
namespace bpo = boost::program_options;
int main( int argc, char** argv )
{
try {
boost::program_options::options_description opts;
opts.add_options()
("help,h", "Print this help message and exit.")
("server-rpc-endpoint,s", bpo::value<string>()->implicit_value("ws://127.0.0.1:8090"), "Server websocket RPC endpoint")
("server-rpc-user,u", bpo::value<string>(), "Server Username")
("server-rpc-password,p", bpo::value<string>(), "Server Password")
("rpc-endpoint,r", bpo::value<string>()->implicit_value("127.0.0.1:8091"), "Endpoint for wallet websocket RPC to listen on")
("rpc-tls-endpoint,t", bpo::value<string>()->implicit_value("127.0.0.1:8092"), "Endpoint for wallet websocket TLS RPC to listen on")
("rpc-tls-certificate,c", bpo::value<string>()->implicit_value("server.pem"), "PEM certificate for wallet websocket TLS RPC")
("rpc-http-endpoint,H", bpo::value<string>()->implicit_value("127.0.0.1:8093"), "Endpoint for wallet HTTP RPC to listen on")
("daemon,d", "Run the wallet in daemon mode" )
("wallet-file,w", bpo::value<string>()->implicit_value("wallet.json"), "wallet to load")
("chain-id", bpo::value<string>(), "chain ID to connect to");
bpo::variables_map options;
bpo::store( bpo::parse_command_line(argc, argv, opts), options );
if( options.count("help") )
{
std::cout << opts << "\n";
return 0;
}
fc::path data_dir;
fc::logging_config cfg;
fc::path log_dir = data_dir / "logs";
fc::file_appender::config ac;
ac.filename = log_dir / "rpc" / "rpc.log";
ac.flush = true;
ac.rotate = true;
ac.rotation_interval = fc::hours( 1 );
ac.rotation_limit = fc::days( 1 );
std::cout << "Logging RPC to file: " << (data_dir / ac.filename).preferred_string() << "\n";
cfg.appenders.push_back(fc::appender_config( "default", "console", fc::variant(fc::console_appender::config())));
cfg.appenders.push_back(fc::appender_config( "rpc", "file", fc::variant(ac)));
cfg.loggers = { fc::logger_config("default"), fc::logger_config( "rpc") };
cfg.loggers.front().level = fc::log_level::info;
cfg.loggers.front().appenders = {"default"};
cfg.loggers.back().level = fc::log_level::debug;
cfg.loggers.back().appenders = {"rpc"};
//fc::configure_logging( cfg );
fc::ecc::private_key committee_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("null_key")));
idump( (key_to_wif( committee_private_key ) ) );
fc::ecc::private_key nathan_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("nathan")));
public_key_type nathan_pub_key = nathan_private_key.get_public_key();
idump( (nathan_pub_key) );
idump( (key_to_wif( nathan_private_key ) ) );
//
// TODO: We read wallet_data twice, once in main() to grab the
// socket info, again in wallet_api when we do
// load_wallet_file(). Seems like this could be better
// designed.
//
wallet_data wdata;
fc::path wallet_file( options.count("wallet-file") ? options.at("wallet-file").as<string>() : "wallet.json");
if( fc::exists( wallet_file ) )
{
wdata = fc::json::from_file( wallet_file ).as<wallet_data>();
if( options.count("chain-id") )
{
// the --chain-id on the CLI must match the chain ID embedded in the wallet file
if( chain_id_type(options.at("chain-id").as<std::string>()) != wdata.chain_id )
{
std::cout << "Chain ID in wallet file does not match specified chain ID\n";
return 1;
}
}
}
else
{
if( options.count("chain-id") )
{
wdata.chain_id = chain_id_type(options.at("chain-id").as<std::string>());
std::cout << "Starting a new wallet with chain ID " << wdata.chain_id.str() << " (from CLI)\n";
}
else
{
wdata.chain_id = graphene::egenesis::get_egenesis_chain_id();
std::cout << "Starting a new wallet with chain ID " << wdata.chain_id.str() << " (from egenesis)\n";
}
}
// but allow CLI to override
if( options.count("server-rpc-endpoint") )
wdata.ws_server = options.at("server-rpc-endpoint").as<std::string>();
if( options.count("server-rpc-user") )
wdata.ws_user = options.at("server-rpc-user").as<std::string>();
if( options.count("server-rpc-password") )
wdata.ws_password = options.at("server-rpc-password").as<std::string>();
fc::http::websocket_client client;
idump((wdata.ws_server));
auto con = client.connect( wdata.ws_server );
auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con);
auto remote_api = apic->get_remote_api< login_api >(1);
edump((wdata.ws_user)(wdata.ws_password) );
// TODO: Error message here
FC_ASSERT( remote_api->login( wdata.ws_user, wdata.ws_password ) );
auto wapiptr = std::make_shared<wallet_api>( wdata, remote_api );
wapiptr->set_wallet_filename( wallet_file.generic_string() );
wapiptr->load_wallet_file();
fc::api<wallet_api> wapi(wapiptr);
auto wallet_cli = std::make_shared<fc::rpc::cli>();
for( auto& name_formatter : wapiptr->get_result_formatters() )
wallet_cli->format_result( name_formatter.first, name_formatter.second );
boost::signals2::scoped_connection closed_connection(con->closed.connect([=]{
cerr << "Server has disconnected us.\n";
wallet_cli->stop();
}));
(void)(closed_connection);
if( wapiptr->is_new() )
{
std::cout << "Please use the set_password method to initialize a new wallet before continuing\n";
wallet_cli->set_prompt( "new >>> " );
} else
wallet_cli->set_prompt( "locked >>> " );
boost::signals2::scoped_connection locked_connection(wapiptr->lock_changed.connect([&](bool locked) {
wallet_cli->set_prompt( locked ? "locked >>> " : "unlocked >>> " );
}));
auto _websocket_server = std::make_shared<fc::http::websocket_server>();
if( options.count("rpc-endpoint") )
{
_websocket_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){
std::cout << "here... \n";
wlog("." );
auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);
wsc->register_api(wapi);
c->set_session_data( wsc );
});
ilog( "Listening for incoming RPC requests on ${p}", ("p", options.at("rpc-endpoint").as<string>() ));
_websocket_server->listen( fc::ip::endpoint::from_string(options.at("rpc-endpoint").as<string>()) );
_websocket_server->start_accept();
}
string cert_pem = "server.pem";
if( options.count( "rpc-tls-certificate" ) )
cert_pem = options.at("rpc-tls-certificate").as<string>();
auto _websocket_tls_server = std::make_shared<fc::http::websocket_tls_server>(cert_pem);
if( options.count("rpc-tls-endpoint") )
{
_websocket_tls_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){
auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);
wsc->register_api(wapi);
c->set_session_data( wsc );
});
ilog( "Listening for incoming TLS RPC requests on ${p}", ("p", options.at("rpc-tls-endpoint").as<string>() ));
_websocket_tls_server->listen( fc::ip::endpoint::from_string(options.at("rpc-tls-endpoint").as<string>()) );
_websocket_tls_server->start_accept();
}
auto _http_server = std::make_shared<fc::http::server>();
if( options.count("rpc-http-endpoint" ) )
{
ilog( "Listening for incoming HTTP RPC requests on ${p}", ("p", options.at("rpc-http-endpoint").as<string>() ) );
_http_server->listen( fc::ip::endpoint::from_string( options.at( "rpc-http-endpoint" ).as<string>() ) );
//
// due to implementation, on_request() must come AFTER listen()
//
_http_server->on_request(
[&]( const fc::http::request& req, const fc::http::server::response& resp )
{
std::shared_ptr< fc::rpc::http_api_connection > conn =
std::make_shared< fc::rpc::http_api_connection>();
conn->register_api( wapi );
conn->on_request( req, resp );
} );
}
if( !options.count( "daemon" ) )
{
wallet_cli->register_api( wapi );
wallet_cli->start();
wallet_cli->wait();
}
else
{
fc::promise<int>::ptr exit_promise = new fc::promise<int>("UNIX Signal Handler");
#ifdef __unix__
fc::set_signal_handler([&exit_promise](int signal) {
exit_promise->set_value(signal);
}, SIGINT);
#endif
ilog( "Entering Daemon Mode, ^C to exit" );
exit_promise->wait();
}
wapi->save_wallet_file(wallet_file.generic_string());
locked_connection.disconnect();
closed_connection.disconnect();
}
catch ( const fc::exception& e )
{
std::cout << e.to_detail_string() << "\n";
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// type_traits
// has_nothrow_copy_assign
#include <type_traits>
template <class T>
void test_has_nothrow_assign()
{
static_assert( std::has_nothrow_copy_assign<T>::value, "");
static_assert(!std::has_nothrow_copy_assign<const T>::value, "");
static_assert( std::has_nothrow_copy_assign<volatile T>::value, "");
static_assert(!std::has_nothrow_copy_assign<const volatile T>::value, "");
}
template <class T>
void test_has_not_nothrow_assign()
{
static_assert(!std::has_nothrow_copy_assign<T>::value, "");
static_assert(!std::has_nothrow_copy_assign<const T>::value, "");
static_assert(!std::has_nothrow_copy_assign<volatile T>::value, "");
static_assert(!std::has_nothrow_copy_assign<const volatile T>::value, "");
}
class Empty
{
};
class NotEmpty
{
virtual ~NotEmpty();
};
union Union {};
struct bit_zero
{
int : 0;
};
class Abstract
{
virtual ~Abstract() = 0;
};
struct A
{
A& operator=(const A&);
};
int main()
{
test_has_not_nothrow_assign<void>();
test_has_not_nothrow_assign<A>();
test_has_not_nothrow_assign<int&>();
test_has_nothrow_assign<Union>();
test_has_nothrow_assign<Abstract>();
test_has_nothrow_assign<Empty>();
test_has_nothrow_assign<int>();
test_has_nothrow_assign<double>();
test_has_nothrow_assign<int*>();
test_has_nothrow_assign<const int*>();
test_has_nothrow_assign<char[3]>();
test_has_nothrow_assign<char[3]>();
test_has_nothrow_assign<NotEmpty>();
test_has_nothrow_assign<bit_zero>();
}
<commit_msg>has_nothrow_copy_assign hooked up to clang<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// type_traits
// has_nothrow_copy_assign
#include <type_traits>
template <class T, bool Result>
void test_has_nothrow_assign()
{
static_assert(std::has_nothrow_copy_assign<T>::value == Result, "");
}
class Empty
{
};
struct NotEmpty
{
virtual ~NotEmpty();
};
union Union {};
struct bit_zero
{
int : 0;
};
struct Abstract
{
virtual ~Abstract() = 0;
};
struct A
{
A& operator=(const A&);
};
int main()
{
test_has_nothrow_assign<void, false>();
test_has_nothrow_assign<A, false>();
test_has_nothrow_assign<int&, false>();
test_has_nothrow_assign<Abstract, false>();
test_has_nothrow_assign<char[3], false>();
test_has_nothrow_assign<char[], false>();
test_has_nothrow_assign<Union, true>();
test_has_nothrow_assign<Empty, true>();
test_has_nothrow_assign<int, true>();
test_has_nothrow_assign<double, true>();
test_has_nothrow_assign<int*, true>();
test_has_nothrow_assign<const int*, true>();
test_has_nothrow_assign<NotEmpty, true>();
test_has_nothrow_assign<bit_zero, true>();
}
<|endoftext|> |
<commit_before>/*
* DamageOverTimeList.cpp
*
* Created on: 04/06/2010
* Author: victor
*/
#include "DamageOverTimeList.h"
#include "server/zone/objects/creature/CreatureObject.h"
uint64 DamageOverTimeList::activateDots(CreatureObject* victim) {
uint64 states = 0;
uint64 statesBefore = 0;
Locker locker(&guard);
for (int i = 0; i < size(); ++i) {
Vector<DamageOverTime>* vector = &elementAt(i).getValue();
for (int j = 0; j < vector->size(); ++j) {
DamageOverTime* dot = &vector->elementAt(j);
statesBefore |= dot->getType();
if (dot->nextTickPast()) {
//guard.unlock();
try {
dot->applyDot(victim);
} catch (...) {
//guard.wlock();
throw;
}
//guard.wlock();
}
Time nTime = dot->getNextTick();
if (nextTick.isPast() || (!dot->isPast() && (nTime.compareTo(nextTick) > 0)))
nextTick = nTime;
if (!dot->isPast()) {
states |= dot->getType();
} else {
if (i < size()) {
vector->remove(j);
--j;
}
}
}
}
int statesRemoved = states ^ statesBefore;
if( statesRemoved & CreatureState::BLEEDING )
{
victim->clearState(CreatureState::BLEEDING);
}
if( statesRemoved & CreatureState::POISONED )
{
victim->clearState(CreatureState::POISONED);
}
if( statesRemoved & CreatureState::DISEASED )
{
victim->clearState(CreatureState::DISEASED);
}
if( statesRemoved & CreatureState::ONFIRE )
{
victim->clearState(CreatureState::ONFIRE);
}
if (nextTick.isPast()) {
dot = false;
removeAll();
states = 0;
}
return states;
}
int DamageOverTimeList::getStrength(uint8 pool, uint64 dotType) {
Locker locker(&guard);
Vector<DamageOverTime>* vector;
int strength = 0;
for(int i = 0; i < size(); i++)
{
vector = &elementAt(i).getValue();
for(int j = 0; j < vector->size(); j++)
{
DamageOverTime* currentDot = &vector->elementAt(j);
if(currentDot->getType() == dotType && (currentDot->getAttribute() == pool))
{
if (!currentDot->isPast()) {
strength+=currentDot->getStrength();
}
}
}
}
return strength;
}
uint32 DamageOverTimeList::addDot(CreatureObject* victim, uint64 objectID, uint32 duration, uint64 dotType, uint8 pool, uint32 strength, float potency, uint32 defense, int secondaryStrength) {
Locker locker(&guard);
if (strength == 0) return 0;
int oldStrength = getStrength(pool, dotType);
float dotReductionMod = 1.0f;
int redStrength;
float redPotency;
if (!(dotType == CreatureState::DISEASED || dotType == CreatureState::POISONED)) { // Calculate hit for non poison & disease dots
if (defense > 0)
dotReductionMod -= (float) defense / 125.0f;
redStrength = (int)(strength * dotReductionMod);
redPotency = potency * dotReductionMod;
if (!(redPotency > System::random(125) || redPotency > System::random(125)))
return 0;
} else {
int missChance = System::random(100); // find out 5% miss and 5% hit
if (missChance <= 5) // 5% miss chance
return 0;
else if (missChance >5 && missChance <=95){ // Over 95 is 5% hit
int dotChance = 50; // If potency and resist are equal, then 50% chance to land
if (potency >= defense)
dotChance += (int)((potency - defense)*.5); // For every point of difference, increase chance by .5%
else
dotChance -= (int)((defense - potency)*.5); // For every point of difference, decrease chance by .5%
if (dotChance < (int)System::random(100))
return 0;
}
redStrength = strength;
redPotency = potency;
}
//only 1 disease per bar allowed
if(dotType == CreatureState::DISEASED)
{
objectID = Long::hashCode(CreatureState::DISEASED);
}
DamageOverTime newDot(dotType, pool, redStrength, duration, redPotency, secondaryStrength);
int dotPower = newDot.initDot(victim);
Time nTime = newDot.getNextTick();
if (isEmpty() || nextTick.isPast())
nextTick = nTime;
else if (nTime.compareTo(nextTick) > 0)
nextTick = nTime;
uint64 key = generateKey(dotType, pool, objectID);
if (contains(key)) {
Vector<DamageOverTime>* vector = &get(key);
vector->removeAll();
vector->add(newDot);
//System::out << "Replacing Dot" << endl;
} else {
Vector<DamageOverTime> newVector;
newVector.add(newDot);
put(key, newVector);
//System::out << "New Dot" << endl;
}
if(oldStrength == 0)
{
sendStartMessage(victim, dotType);
}
else
{
sendIncreaseMessage(victim, dotType);
}
dot = true;
locker.release();
victim->setState(dotType);
return dotPower;
}
bool DamageOverTimeList::healState(CreatureObject* victim, uint64 dotType, float reduction) {
Locker locker(&guard);
if (!hasDot())
return reduction;
bool expired = true;
for (int i = 0; i < size(); ++i) {
uint64 type = elementAt(i).getKey();
Vector<DamageOverTime>* vector = &elementAt(i).getValue();
for (int j = 0; j < vector->size(); ++j) {
DamageOverTime* dot = &vector->elementAt(j);
if (dot->getType() == dotType && !dot->isPast()) {
float tempReduction = dot->reduceTick(reduction);
if (tempReduction >= 0.0f)
expired = expired && true;
else
expired = false;
}
}
}
if (expired) {
locker.release();
victim->clearState(dotType);
return true;
}
sendDecreaseMessage(victim, dotType);
return false;
}
bool DamageOverTimeList::hasDot(uint64 dotType) {
Locker locker(&guard);
bool hasDot = false;
for (int i = 0; i < size(); ++i) {
uint64 type = elementAt(i).getKey();
Vector<DamageOverTime>* vector = &elementAt(i).getValue();
for (int j = 0; j < vector->size(); ++j) {
DamageOverTime* dot = &vector->elementAt(j);
if (dot->getType() == dotType)
hasDot = true;
}
}
return hasDot;
}
void DamageOverTimeList::clear(CreatureObject* creature) {
Locker locker(&guard);
dot = false;
for (int i = 0; i < size(); ++i) {
uint64 type = elementAt(i).getKey();
Vector<DamageOverTime>* vector = &elementAt(i).getValue();
for (int j = 0; j < vector->size(); ++j) {
DamageOverTime* dot = &vector->elementAt(j);
creature->clearState(dot->getType());
}
}
removeAll();
}
void DamageOverTimeList::sendStartMessage(CreatureObject* victim, uint64 type) {
if (!victim->isPlayerCreature())
return;
switch(type) {
case CreatureState::BLEEDING:
victim->sendSystemMessage("@dot_message:start_bleeding");
break;
case CreatureState::POISONED:
victim->sendSystemMessage("@dot_message:start_poisoned");
break;
case CreatureState::DISEASED:
victim->sendSystemMessage("@dot_message:start_diseased");
break;
case CreatureState::ONFIRE:
victim->sendSystemMessage("@dot_message:start_fire");
break;
}
}
void DamageOverTimeList::sendStopMessage(CreatureObject* victim, uint64 type) {
if (!victim->isPlayerCreature())
return;
switch(type) {
case CreatureState::BLEEDING:
victim->sendSystemMessage("@dot_message:stop_bleeding");
break;
case CreatureState::POISONED:
victim->sendSystemMessage("@dot_message:stop_poisoned");
break;
case CreatureState::DISEASED:
victim->sendSystemMessage("@dot_message:stop_diseased");
break;
case CreatureState::ONFIRE:
victim->sendSystemMessage("@dot_message:stop_fire");
break;
}
}
void DamageOverTimeList::sendIncreaseMessage(CreatureObject* victim, uint64 type) {
if (!victim->isPlayerCreature())
return;
switch(type) {
case CreatureState::BLEEDING:
victim->sendSystemMessage("@dot_message:increase_bleeding");
break;
case CreatureState::POISONED:
victim->sendSystemMessage("@dot_message:increase_poisoned");
break;
case CreatureState::DISEASED:
victim->sendSystemMessage("@dot_message:increase_diseased");
break;
case CreatureState::ONFIRE:
victim->sendSystemMessage("@dot_message:increase_fire");
break;
}
}
void DamageOverTimeList::sendDecreaseMessage(CreatureObject* victim, uint64 type) {
if (!victim->isPlayerCreature())
return;
switch(type) {
case CreatureState::BLEEDING:
victim->sendSystemMessage("@dot_message:decrease_bleeding");
break;
case CreatureState::POISONED:
victim->sendSystemMessage("@dot_message:decrease_poisoned");
break;
case CreatureState::DISEASED:
victim->sendSystemMessage("@dot_message:decrease_diseased");
break;
case CreatureState::ONFIRE:
victim->sendSystemMessage("@dot_message:decrease_fire");
break;
}
}
<commit_msg>[fixed] Cure packs applying individually to each dot rather then the total dot pool - mantis 4950<commit_after>/*
* DamageOverTimeList.cpp
*
* Created on: 04/06/2010
* Author: victor
*/
#include "DamageOverTimeList.h"
#include "server/zone/objects/creature/CreatureObject.h"
uint64 DamageOverTimeList::activateDots(CreatureObject* victim) {
uint64 states = 0;
uint64 statesBefore = 0;
Locker locker(&guard);
for (int i = 0; i < size(); ++i) {
Vector<DamageOverTime>* vector = &elementAt(i).getValue();
for (int j = 0; j < vector->size(); ++j) {
DamageOverTime* dot = &vector->elementAt(j);
statesBefore |= dot->getType();
if (dot->nextTickPast()) {
//guard.unlock();
try {
dot->applyDot(victim);
} catch (...) {
//guard.wlock();
throw;
}
//guard.wlock();
}
Time nTime = dot->getNextTick();
if (nextTick.isPast() || (!dot->isPast() && (nTime.compareTo(nextTick) > 0)))
nextTick = nTime;
if (!dot->isPast()) {
states |= dot->getType();
} else {
if (i < size()) {
vector->remove(j);
--j;
}
}
}
}
int statesRemoved = states ^ statesBefore;
if( statesRemoved & CreatureState::BLEEDING )
{
victim->clearState(CreatureState::BLEEDING);
}
if( statesRemoved & CreatureState::POISONED )
{
victim->clearState(CreatureState::POISONED);
}
if( statesRemoved & CreatureState::DISEASED )
{
victim->clearState(CreatureState::DISEASED);
}
if( statesRemoved & CreatureState::ONFIRE )
{
victim->clearState(CreatureState::ONFIRE);
}
if (nextTick.isPast()) {
dot = false;
removeAll();
states = 0;
}
return states;
}
int DamageOverTimeList::getStrength(uint8 pool, uint64 dotType) {
Locker locker(&guard);
Vector<DamageOverTime>* vector;
int strength = 0;
for(int i = 0; i < size(); i++)
{
vector = &elementAt(i).getValue();
for(int j = 0; j < vector->size(); j++)
{
DamageOverTime* currentDot = &vector->elementAt(j);
if(currentDot->getType() == dotType && (currentDot->getAttribute() == pool))
{
if (!currentDot->isPast()) {
strength+=currentDot->getStrength();
}
}
}
}
return strength;
}
uint32 DamageOverTimeList::addDot(CreatureObject* victim, uint64 objectID, uint32 duration, uint64 dotType, uint8 pool, uint32 strength, float potency, uint32 defense, int secondaryStrength) {
Locker locker(&guard);
if (strength == 0) return 0;
int oldStrength = getStrength(pool, dotType);
float dotReductionMod = 1.0f;
int redStrength;
float redPotency;
if (!(dotType == CreatureState::DISEASED || dotType == CreatureState::POISONED)) { // Calculate hit for non poison & disease dots
if (defense > 0)
dotReductionMod -= (float) defense / 125.0f;
redStrength = (int)(strength * dotReductionMod);
redPotency = potency * dotReductionMod;
if (!(redPotency > System::random(125) || redPotency > System::random(125)))
return 0;
} else {
int missChance = System::random(100); // find out 5% miss and 5% hit
if (missChance <= 5) // 5% miss chance
return 0;
else if (missChance >5 && missChance <=95){ // Over 95 is 5% hit
int dotChance = 50; // If potency and resist are equal, then 50% chance to land
if (potency >= defense)
dotChance += (int)((potency - defense)*.5); // For every point of difference, increase chance by .5%
else
dotChance -= (int)((defense - potency)*.5); // For every point of difference, decrease chance by .5%
if (dotChance < (int)System::random(100))
return 0;
}
redStrength = strength;
redPotency = potency;
}
//only 1 disease per bar allowed
if(dotType == CreatureState::DISEASED)
{
objectID = Long::hashCode(CreatureState::DISEASED);
}
DamageOverTime newDot(dotType, pool, redStrength, duration, redPotency, secondaryStrength);
int dotPower = newDot.initDot(victim);
Time nTime = newDot.getNextTick();
if (isEmpty() || nextTick.isPast())
nextTick = nTime;
else if (nTime.compareTo(nextTick) > 0)
nextTick = nTime;
uint64 key = generateKey(dotType, pool, objectID);
if (contains(key)) {
Vector<DamageOverTime>* vector = &get(key);
vector->removeAll();
vector->add(newDot);
//System::out << "Replacing Dot" << endl;
} else {
Vector<DamageOverTime> newVector;
newVector.add(newDot);
put(key, newVector);
//System::out << "New Dot" << endl;
}
if(oldStrength == 0)
{
sendStartMessage(victim, dotType);
}
else
{
sendIncreaseMessage(victim, dotType);
}
dot = true;
locker.release();
victim->setState(dotType);
return dotPower;
}
bool DamageOverTimeList::healState(CreatureObject* victim, uint64 dotType, float reduction) {
Locker locker(&guard);
if (!hasDot())
return reduction;
bool expired = true;
float reductionLeft = reduction;
for (int i = 0; i < size(); ++i) {
uint64 type = elementAt(i).getKey();
Vector<DamageOverTime>* vector = &elementAt(i).getValue();
for (int j = 0; j < vector->size(); ++j) {
DamageOverTime* dot = &vector->elementAt(j);
if (dot->getType() == dotType && !dot->isPast()) {
if (reductionLeft >= dot->getStrength()) {
reductionLeft -= dot->getStrength();
dot->reduceTick(dot->getStrength());
expired = expired && true;
} else {
dot->reduceTick(reductionLeft);
reductionLeft = 0;
expired = false;
break;
}
}
}
if (reductionLeft == 0)
break;
}
if (expired) {
locker.release();
victim->clearState(dotType);
return true;
}
sendDecreaseMessage(victim, dotType);
return false;
}
bool DamageOverTimeList::hasDot(uint64 dotType) {
Locker locker(&guard);
bool hasDot = false;
for (int i = 0; i < size(); ++i) {
uint64 type = elementAt(i).getKey();
Vector<DamageOverTime>* vector = &elementAt(i).getValue();
for (int j = 0; j < vector->size(); ++j) {
DamageOverTime* dot = &vector->elementAt(j);
if (dot->getType() == dotType)
hasDot = true;
}
}
return hasDot;
}
void DamageOverTimeList::clear(CreatureObject* creature) {
Locker locker(&guard);
dot = false;
for (int i = 0; i < size(); ++i) {
uint64 type = elementAt(i).getKey();
Vector<DamageOverTime>* vector = &elementAt(i).getValue();
for (int j = 0; j < vector->size(); ++j) {
DamageOverTime* dot = &vector->elementAt(j);
creature->clearState(dot->getType());
}
}
removeAll();
}
void DamageOverTimeList::sendStartMessage(CreatureObject* victim, uint64 type) {
if (!victim->isPlayerCreature())
return;
switch(type) {
case CreatureState::BLEEDING:
victim->sendSystemMessage("@dot_message:start_bleeding");
break;
case CreatureState::POISONED:
victim->sendSystemMessage("@dot_message:start_poisoned");
break;
case CreatureState::DISEASED:
victim->sendSystemMessage("@dot_message:start_diseased");
break;
case CreatureState::ONFIRE:
victim->sendSystemMessage("@dot_message:start_fire");
break;
}
}
void DamageOverTimeList::sendStopMessage(CreatureObject* victim, uint64 type) {
if (!victim->isPlayerCreature())
return;
switch(type) {
case CreatureState::BLEEDING:
victim->sendSystemMessage("@dot_message:stop_bleeding");
break;
case CreatureState::POISONED:
victim->sendSystemMessage("@dot_message:stop_poisoned");
break;
case CreatureState::DISEASED:
victim->sendSystemMessage("@dot_message:stop_diseased");
break;
case CreatureState::ONFIRE:
victim->sendSystemMessage("@dot_message:stop_fire");
break;
}
}
void DamageOverTimeList::sendIncreaseMessage(CreatureObject* victim, uint64 type) {
if (!victim->isPlayerCreature())
return;
switch(type) {
case CreatureState::BLEEDING:
victim->sendSystemMessage("@dot_message:increase_bleeding");
break;
case CreatureState::POISONED:
victim->sendSystemMessage("@dot_message:increase_poisoned");
break;
case CreatureState::DISEASED:
victim->sendSystemMessage("@dot_message:increase_diseased");
break;
case CreatureState::ONFIRE:
victim->sendSystemMessage("@dot_message:increase_fire");
break;
}
}
void DamageOverTimeList::sendDecreaseMessage(CreatureObject* victim, uint64 type) {
if (!victim->isPlayerCreature())
return;
switch(type) {
case CreatureState::BLEEDING:
victim->sendSystemMessage("@dot_message:decrease_bleeding");
break;
case CreatureState::POISONED:
victim->sendSystemMessage("@dot_message:decrease_poisoned");
break;
case CreatureState::DISEASED:
victim->sendSystemMessage("@dot_message:decrease_diseased");
break;
case CreatureState::ONFIRE:
victim->sendSystemMessage("@dot_message:decrease_fire");
break;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include "Communicator.hpp"
#include "PoolAllocator.hpp"
#include "FullEmpty.hpp"
#include "LegacyDelegate.hpp"
#include "GlobalCompletionEvent.hpp"
#include "ParallelLoop.hpp"
#include <type_traits>
namespace Grappa {
namespace delegate {
/// Do asynchronous generic delegate with `void` return type. Uses message pool to allocate
/// the message. Enrolls with GCE so you can guarantee all have completed after a global
/// GlobalCompletionEvent::wait() call.
template<GlobalCompletionEvent * GCE = &Grappa::impl::local_gce, typename F = decltype(nullptr)>
inline void call_async(MessagePoolBase& pool, Core dest, F remote_work) {
static_assert(std::is_same< decltype(remote_work()), void >::value, "return type of callable must be void when not associated with Promise.");
delegate_stats.count_op();
Core origin = Grappa::mycore();
if (dest == origin) {
// short-circuit if local
remote_work();
} else {
delegate_stats.count_op_am();
if (GCE) GCE->enroll();
pool.send_message(dest, [origin, remote_work] {
remote_work();
if (GCE) complete(make_global(GCE,origin));
});
}
}
/// A 'Promise' is a wrapper around a FullEmpty for async delegates with return values.
/// The idea is to allocate storage for the result, issue the delegate request, and then
/// block on waiting for the value when it's needed.
///
/// Usage example: @code {
/// delegate::Promise<int> x;
/// x.call_async(1, []()->int { return value; });
/// // other work
/// myvalue += x.get();
/// }
///
/// TODO: make this so you you can issue a call_async() directly and get a
/// delegate::Promise back. This should be able to be done using the same mechanism for
/// creating Messages (compiler-optimized-away move).
template<typename R>
class Promise {
FullEmpty<R> _result;
int64_t start_time;
int64_t network_time;
public:
Promise(): _result(), network_time(0), start_time(0) {}
inline void fill(const R& r) {
_result.writeXF(r);
}
/// Block on result being returned.
inline const R& get() {
// ... and wait for the result
const R& r = _result.readFF();
delegate_stats.record_wakeup_latency(start_time, network_time);
return r;
}
template <typename F>
void call_async(MessagePoolBase& pool, Core dest, F func) {
static_assert(std::is_same<R, decltype(func())>::value, "return type of callable must match the type of this Promise");
_result.reset();
delegate_stats.count_op();
Core origin = Grappa::mycore();
if (dest == origin) {
// short-circuit if local
fill(func());
} else {
delegate_stats.count_op_am();
start_time = Grappa_get_timestamp();
pool.send_message(dest, [origin, func, this] {
R val = func();
// TODO: replace with handler-safe send_message
send_heap_message(origin, [val, this] {
this->network_time = Grappa_get_timestamp();
delegate_stats.record_network_latency(this->start_time);
this->fill(val);
});
}); // send message
}
}
};
} // namespace delegate
} // namespace Grappa
<commit_msg>Add `delegate::increment_async()` because it comes up fairly frequently.<commit_after>#pragma once
#include "Communicator.hpp"
#include "PoolAllocator.hpp"
#include "FullEmpty.hpp"
#include "LegacyDelegate.hpp"
#include "GlobalCompletionEvent.hpp"
#include "ParallelLoop.hpp"
#include <type_traits>
namespace Grappa {
namespace delegate {
/// Do asynchronous generic delegate with `void` return type. Uses message pool to allocate
/// the message. Enrolls with GCE so you can guarantee all have completed after a global
/// GlobalCompletionEvent::wait() call.
template<GlobalCompletionEvent * GCE = &Grappa::impl::local_gce, typename F = decltype(nullptr)>
inline void call_async(MessagePoolBase& pool, Core dest, F remote_work) {
static_assert(std::is_same< decltype(remote_work()), void >::value, "return type of callable must be void when not associated with Promise.");
delegate_stats.count_op();
Core origin = Grappa::mycore();
if (dest == origin) {
// short-circuit if local
remote_work();
} else {
delegate_stats.count_op_am();
if (GCE) GCE->enroll();
pool.send_message(dest, [origin, remote_work] {
remote_work();
if (GCE) complete(make_global(GCE,origin));
});
}
}
template<typename T, typename U, GlobalCompletionEvent * GCE = &Grappa::impl::local_gce >
inline void increment_async(MessagePoolBase& pool, GlobalAddress<T> target, U increment) {
delegate::call_async(target.core(), [increment]{
(target.pointer()) += increment;
});
}
/// A 'Promise' is a wrapper around a FullEmpty for async delegates with return values.
/// The idea is to allocate storage for the result, issue the delegate request, and then
/// block on waiting for the value when it's needed.
///
/// Usage example: @code {
/// delegate::Promise<int> x;
/// x.call_async(1, []()->int { return value; });
/// // other work
/// myvalue += x.get();
/// }
///
/// TODO: make this so you you can issue a call_async() directly and get a
/// delegate::Promise back. This should be able to be done using the same mechanism for
/// creating Messages (compiler-optimized-away move).
template<typename R>
class Promise {
FullEmpty<R> _result;
int64_t start_time;
int64_t network_time;
public:
Promise(): _result(), network_time(0), start_time(0) {}
inline void fill(const R& r) {
_result.writeXF(r);
}
/// Block on result being returned.
inline const R& get() {
// ... and wait for the result
const R& r = _result.readFF();
delegate_stats.record_wakeup_latency(start_time, network_time);
return r;
}
template <typename F>
void call_async(MessagePoolBase& pool, Core dest, F func) {
static_assert(std::is_same<R, decltype(func())>::value, "return type of callable must match the type of this Promise");
_result.reset();
delegate_stats.count_op();
Core origin = Grappa::mycore();
if (dest == origin) {
// short-circuit if local
fill(func());
} else {
delegate_stats.count_op_am();
start_time = Grappa_get_timestamp();
pool.send_message(dest, [origin, func, this] {
R val = func();
// TODO: replace with handler-safe send_message
send_heap_message(origin, [val, this] {
this->network_time = Grappa_get_timestamp();
delegate_stats.record_network_latency(this->start_time);
this->fill(val);
});
}); // send message
}
}
};
} // namespace delegate
} // namespace Grappa
<|endoftext|> |
<commit_before>#include <atomic>
#include <string>
#include <gtest/gtest.h>
#include <teelogging/teelogging.h>
#include "../shell.h"
#include "../coroutine.h"
#include "../scheduler.h"
#include "../semaphore.h"
#include "../channel.h"
class CoroTest : testing::Test { };
using namespace cu;
TEST(CoroTest, Test_find)
{
cu::scheduler sch;
LOGI("---------- begin find test --------");
cu::channel<std::string> c1(sch, 20);
c1.pipeline( find()
, grep("*.h")
, cat()
, replace("class", "object")
, log() );
c1("../..");
LOGI("---------- end find test --------");
}
TEST(CoroTest, Test_run_ls_strip_quote_grep)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
run()
, strip()
, quote()
, grep("shell_*")
, assert_count(1)
, assert_string("\"shell_exe\"")
, log()
);
c1("ls .");
/////////////////////////////////
cu::channel<std::string> c2(sch, 100);
c2.pipeline(
ls()
, strip()
, quote()
, grep("shell_*")
, assert_count(1)
, assert_string("\"shell_exe\"")
, log()
);
c2(".");
}
TEST(CoroTest, Test_run_ls_sort_grep_uniq_join)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
std::string out_subproces;
c1.pipeline(run(), strip(), sort(), grep("*fes*"), uniq(), join(), log(), out(out_subproces));
c1("ls .");
//
cu::channel<std::string> c2(sch, 100);
std::string out_ls;
c2.pipeline(ls(), sort(), grep("*fes*"), uniq(), join(), log(), out(out_ls));
c2(".");
//
ASSERT_STREQ(out_subproces.c_str(), out_ls.c_str());
}
TEST(CoroTest, TestCut)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
assert_count(1)
, split()
, assert_count(3)
, join()
, assert_count(1)
, cut(0)
, assert_count(1)
, assert_string("hello")
);
c1("hello big world");
cu::channel<std::string> c2(sch, 100);
c2.pipeline(
assert_count(1)
, split()
, assert_count(3)
, join()
, assert_count(1)
, cut(1)
, assert_count(1)
, assert_string("big")
);
c2("hello big world");
cu::channel<std::string> c3(sch, 100);
c3.pipeline(
assert_count(1)
, split()
, assert_count(3)
, join()
, assert_count(1)
, cut(2)
, assert_count(1)
, assert_string("world")
);
c3("hello big world");
}
TEST(CoroTest, TestGrep)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
split("\n")
, assert_count(3)
, grep("line2")
, assert_count(1)
, assert_string("line2")
);
c1("line1\nline2\nline3");
}
TEST(CoroTest, TestGrep2)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
split("\n")
, assert_count(4)
);
c1("line1\nline2\nline3\n");
}
// TEST(CoroTest, TestCount)
// {
// cu::scheduler sch;
//
// cu::channel<std::string> c1(sch, 100);
// int result;
// c1.pipeline(
// split("\n")
// , count()
// , out(result)
// );
// c1("line1\nline2\nline3");
// ASSERT_EQ(result, 3) << "maybe count() is not working well";
// }
TEST(CoroTest, TestUpper)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 10);
c1.pipeline( replace("mundo", "gente"), toupper() );
sch.spawn([&](auto& yield) {
for(int x=1; x<=1; ++x)
{
LOGI("sending hola mundo");
c1(yield, "hola mundo");
}
c1.close(yield);
});
sch.spawn([&](auto& yield) {
LOGI("begin");
for(auto& r : cu::range(yield, c1))
{
LOGI("recv %s", r.c_str());
// ASSERT_STREQ("HOLA GENTE", r.c_str());
}
LOGI("end");
});
sch.run_until_complete();
}
TEST(CoroTest, TestScheduler2)
{
cu::scheduler sch;
cu::channel<int> c1(sch, 10);
cu::channel<int> c2(sch, 10);
cu::channel<int> c3(sch, 10);
c1.pipeline( []() -> cu::link<int>
{
return [](auto&& source, auto&& yield)
{
for (auto& s : source)
{
if(s)
yield(*s - 256);
else
yield(s);
}
}
}()
);
/*
c2.pipeline( cu::link<int>(
[](auto&& source, auto&& yield)
{
for (auto& s : source)
{
if(s)
yield(*s + 4096);
else
yield(s);
}
}
)
);
c3.pipeline( cu::link<int>(
[](auto&& source, auto&& yield)
{
int total = 0;
int count = 0;
for (auto& s : source)
{
if(s)
{
total += *s;
++count;
}
else
yield(s);
}
yield( int(total / count) );
}
)
);
*/
sch.spawn([&](auto& yield)
{
for(int x=1; x<=100; ++x)
{
LOGI("1. send %d", x);
c1(yield, x);
}
c1.close(yield);
});
sch.spawn([&](auto& yield)
{
for(int y=1; y<=100; ++y)
{
LOGI("2. send %d", y);
c2(yield, y);
}
c2.close(yield);
});
sch.spawn([&](auto& yield)
{
int a, b;
for(auto& t : cu::range(yield, c1, c2))
{
std::tie(a, b) = t;
LOGI("3. recv and resend %d", a+b);
c3(yield, a + b);
}
c3.close(yield);
});
sch.spawn([&](auto& yield)
{
for(auto& r : cu::range(yield, c3))
{
LOGI("4. result = %d", r);
}
});
sch.run_until_complete();
}
<commit_msg>Update test_shell.cpp<commit_after>#include <atomic>
#include <string>
#include <gtest/gtest.h>
#include <teelogging/teelogging.h>
#include "../shell.h"
#include "../coroutine.h"
#include "../scheduler.h"
#include "../semaphore.h"
#include "../channel.h"
class CoroTest : testing::Test { };
using namespace cu;
TEST(CoroTest, Test_find)
{
cu::scheduler sch;
LOGI("---------- begin find test --------");
cu::channel<std::string> c1(sch, 20);
c1.pipeline( find()
, grep("*.h")
, cat()
, replace("class", "object")
, log() );
c1("../..");
LOGI("---------- end find test --------");
}
TEST(CoroTest, Test_run_ls_strip_quote_grep)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
run()
, strip()
, quote()
, grep("shell_*")
, assert_count(1)
, assert_string("\"shell_exe\"")
, log()
);
c1("ls .");
/////////////////////////////////
cu::channel<std::string> c2(sch, 100);
c2.pipeline(
ls()
, strip()
, quote()
, grep("shell_*")
, assert_count(1)
, assert_string("\"shell_exe\"")
, log()
);
c2(".");
}
TEST(CoroTest, Test_run_ls_sort_grep_uniq_join)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
std::string out_subproces;
c1.pipeline(run(), strip(), sort(), grep("*fes*"), uniq(), join(), log(), out(out_subproces));
c1("ls .");
//
cu::channel<std::string> c2(sch, 100);
std::string out_ls;
c2.pipeline(ls(), sort(), grep("*fes*"), uniq(), join(), log(), out(out_ls));
c2(".");
//
ASSERT_STREQ(out_subproces.c_str(), out_ls.c_str());
}
TEST(CoroTest, TestCut)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
assert_count(1)
, split()
, assert_count(3)
, join()
, assert_count(1)
, cut(0)
, assert_count(1)
, assert_string("hello")
);
c1("hello big world");
cu::channel<std::string> c2(sch, 100);
c2.pipeline(
assert_count(1)
, split()
, assert_count(3)
, join()
, assert_count(1)
, cut(1)
, assert_count(1)
, assert_string("big")
);
c2("hello big world");
cu::channel<std::string> c3(sch, 100);
c3.pipeline(
assert_count(1)
, split()
, assert_count(3)
, join()
, assert_count(1)
, cut(2)
, assert_count(1)
, assert_string("world")
);
c3("hello big world");
}
TEST(CoroTest, TestGrep)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
split("\n")
, assert_count(3)
, grep("line2")
, assert_count(1)
, assert_string("line2")
);
c1("line1\nline2\nline3");
}
TEST(CoroTest, TestGrep2)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
split("\n")
, assert_count(4)
);
c1("line1\nline2\nline3\n");
}
// TEST(CoroTest, TestCount)
// {
// cu::scheduler sch;
//
// cu::channel<std::string> c1(sch, 100);
// int result;
// c1.pipeline(
// split("\n")
// , count()
// , out(result)
// );
// c1("line1\nline2\nline3");
// ASSERT_EQ(result, 3) << "maybe count() is not working well";
// }
TEST(CoroTest, TestUpper)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 10);
c1.pipeline( replace("mundo", "gente"), toupper() );
sch.spawn([&](auto& yield) {
for(int x=1; x<=1; ++x)
{
LOGI("sending hola mundo");
c1(yield, "hola mundo");
}
c1.close(yield);
});
sch.spawn([&](auto& yield) {
LOGI("begin");
for(auto& r : cu::range(yield, c1))
{
LOGI("recv %s", r.c_str());
// ASSERT_STREQ("HOLA GENTE", r.c_str());
}
LOGI("end");
});
sch.run_until_complete();
}
TEST(CoroTest, TestScheduler2)
{
cu::scheduler sch;
cu::channel<int> c1(sch, 10);
cu::channel<int> c2(sch, 10);
cu::channel<int> c3(sch, 10);
c1.pipeline( []() -> cu::link<int>
{
return [](auto&& source, auto&& yield)
{
for (auto& s : source)
{
if(s)
yield(*s - 256);
else
yield(s);
}
};
}()
);
c2.pipeline( []() -> cu::link<int>
{
return [](auto&& source, auto&& yield)
{
for (auto& s : source)
{
if(s)
yield(*s + 4096);
else
yield(s);
}
};
}()
);
c3.pipeline( []() -> cu::link<int>
{
return [](auto&& source, auto&& yield)
{
int total = 0;
int count = 0;
for (auto& s : source)
{
if(s)
{
total += *s;
++count;
}
else
yield(s);
}
yield( int(total / count) );
};
}()
);
sch.spawn([&](auto& yield)
{
for(int x=1; x<=100; ++x)
{
LOGI("1. send %d", x);
c1(yield, x);
}
c1.close(yield);
});
sch.spawn([&](auto& yield)
{
for(int y=1; y<=100; ++y)
{
LOGI("2. send %d", y);
c2(yield, y);
}
c2.close(yield);
});
sch.spawn([&](auto& yield)
{
int a, b;
for(auto& t : cu::range(yield, c1, c2))
{
std::tie(a, b) = t;
LOGI("3. recv and resend %d", a+b);
c3(yield, a + b);
}
c3.close(yield);
});
sch.spawn([&](auto& yield)
{
for(auto& r : cu::range(yield, c3))
{
LOGI("4. result = %d", r);
}
});
sch.run_until_complete();
}
<|endoftext|> |
<commit_before>#include "utest.h"
#include "math/random.h"
#include "math/numeric.h"
#include "math/epsilon.h"
#include "solver_stoch.h"
#include "functions/test.h"
using namespace nano;
static void check_function(const function_t& function)
{
const auto epochs = size_t(100);
const auto tune_epochs = size_t(4);
const auto epoch_size = size_t(32);
const auto trials = size_t(10);
const auto dims = function.size();
auto rgen = make_rng(scalar_t(-1), scalar_t(+1));
// generate fixed random trials
std::vector<vector_t> x0s(trials);
for (auto& x0 : x0s)
{
x0.resize(dims);
rgen(x0.data(), x0.data() + x0.size());
}
// solvers to try
for (const auto& id : get_stoch_solvers().ids())
{
const auto solver = get_stoch_solvers().get(id);
NANO_REQUIRE(solver);
size_t out_of_domain = 0;
for (size_t t = 0; t < trials; ++ t)
{
const auto& x0 = x0s[t];
const auto f0 = function.eval(x0);
const auto g_thres = epsilon3<scalar_t>();
// optimize
const auto params = stoch_params_t(epochs, epoch_size, epsilon3<scalar_t>());
const auto tune_params = stoch_params_t(tune_epochs, epoch_size, epsilon3<scalar_t>());
const auto tstate = solver->tune(tune_params, function, x0);
const auto state = solver->minimize(params, function, tstate.x);
const auto x = state.x;
const auto f = state.f;
const auto g = state.convergence_criteria();
// ignore out-of-domain solutions
if (!function.is_valid(x))
{
out_of_domain ++;
continue;
}
std::cout << function.name() << ", " << id
<< " [" << (t + 1) << "/" << trials << "]"
<< ": x = [" << x0.transpose() << "]/[" << x.transpose() << "]"
<< ", f = " << f0 << "/" << f
<< ", g = " << g << ".\n";
// check function value decrease
NANO_CHECK_LESS_EQUAL(f, f0);
// check convergence
NANO_CHECK_LESS_EQUAL(g, g_thres);
}
std::cout << function.name() << ", " << id
<< ": out of domain " << out_of_domain << "/" << trials << ".\n";
}
}
NANO_BEGIN_MODULE(test_stoch_solvers)
NANO_CASE(evaluate)
{
foreach_test_function(make_convex_functions(1, 1), check_function);
}
NANO_END_MODULE()
<commit_msg>more robust unit test for stochastic solvers<commit_after>#include "utest.h"
#include "math/random.h"
#include "math/numeric.h"
#include "math/epsilon.h"
#include "solver_stoch.h"
#include "functions/test.h"
using namespace nano;
static void check_function(const function_t& function)
{
const auto epochs = size_t(32);
const auto tune_epochs = size_t(1);
const auto epoch_size = size_t(128);
const auto trials = size_t(10);
const auto dims = function.size();
auto rgen = make_rng(scalar_t(-1), scalar_t(+1));
// generate fixed random trials
std::vector<vector_t> x0s(trials);
for (auto& x0 : x0s)
{
x0.resize(dims);
rgen(x0.data(), x0.data() + x0.size());
}
// solvers to try
for (const auto& id : get_stoch_solvers().ids())
{
const auto solver = get_stoch_solvers().get(id);
NANO_REQUIRE(solver);
size_t out_of_domain = 0;
for (size_t t = 0; t < trials; ++ t)
{
const auto& x0 = x0s[t];
const auto f0 = function.eval(x0);
const auto g_thres = epsilon3<scalar_t>();
// optimize
const auto params = stoch_params_t(epochs, epoch_size, epsilon3<scalar_t>());
const auto tune_params = stoch_params_t(tune_epochs, epoch_size, epsilon3<scalar_t>());
const auto tstate = solver->tune(tune_params, function, x0);
const auto state = solver->minimize(params, function, tstate.x);
const auto x = state.x;
const auto f = state.f;
const auto g = state.convergence_criteria();
// ignore out-of-domain solutions
if (!function.is_valid(x))
{
out_of_domain ++;
continue;
}
std::cout << function.name() << ", " << id
<< " [" << (t + 1) << "/" << trials << "]"
<< ": x = [" << x0.transpose() << "]/[" << x.transpose() << "]"
<< ", f = " << f0 << "/" << f
<< ", g = " << g << ".\n";
// check function value decrease
NANO_CHECK_LESS_EQUAL(f, f0);
// check convergence
NANO_CHECK_LESS_EQUAL(g, g_thres);
}
std::cout << function.name() << ", " << id
<< ": out of domain " << out_of_domain << "/" << trials << ".\n";
}
}
NANO_BEGIN_MODULE(test_stoch_solvers)
NANO_CASE(evaluate)
{
foreach_test_function(make_convex_functions(1, 1), check_function);
}
NANO_END_MODULE()
<|endoftext|> |
<commit_before>/*********************************************************************/
/* Copyright (c) 2013, EPFL/Blue Brain Project */
/* Daniel Nachbaur <daniel.nachbaur@epfl.ch> */
/* 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 UNIVERSITY OF TEXAS AT */
/* AUSTIN ``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 UNIVERSITY OF TEXAS AT */
/* AUSTIN 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. */
/* */
/* The views and conclusions contained in the software and */
/* documentation are those of the authors and should not be */
/* interpreted as representing official policies, either expressed */
/* or implied, of The University of Texas at Austin. */
/*********************************************************************/
#define BOOST_TEST_MODULE WebBrowser
#include <boost/test/unit_test.hpp>
namespace ut = boost::unit_test;
#include "globals.h"
#include "Options.h"
#include "configuration/Configuration.h"
#include "WebkitPixelStreamer.h"
#include <QApplication>
#include <QWebElementCollection>
#include <QWebFrame>
#include <QWebPage>
#include <QWebView>
#include <X11/Xlib.h>
#define TEST_PAGE_URL "webgl_interaction.html"
#define CONFIG_TEST_FILENAME "configuration.xml"
namespace ut = boost::unit_test;
bool hasGLXDisplay()
{
Display* display = XOpenDisplay( 0 );
if( !display )
return false;
int major, event, error;
const bool hasGLX = XQueryExtension( display, "GLX", &major, &event,
&error );
XCloseDisplay( display );
return hasGLX;
}
// We need a global fixture because a bug in QApplication prevents
// deleting then recreating a QApplication in the same process.
// https://bugreports.qt-project.org/browse/QTBUG-7104
struct GlobalQtApp
{
GlobalQtApp()
{
// need QApplication to instantiate WebkitPixelStreamer
ut::master_test_suite_t& testSuite = ut::framework::master_test_suite();
app = new QApplication( testSuite.argc, testSuite.argv );
// To test wheel events the WebkitPixelStreamer needs access to the g_configuration element
OptionsPtr options(new Options());
g_configuration = new Configuration(CONFIG_TEST_FILENAME, options);
}
~GlobalQtApp()
{
delete g_configuration;
delete app;
}
QApplication* app;
};
BOOST_GLOBAL_FIXTURE( GlobalQtApp );
BOOST_AUTO_TEST_CASE( test_webgl_support )
{
if( !hasGLXDisplay( ))
return;
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
QWebElementCollection webglCanvases = frame->findAllElements( "canvas[id=webgl-canvas]" );
BOOST_REQUIRE_EQUAL( webglCanvases.count(), 1 );
// http://stackoverflow.com/questions/11871077/proper-way-to-detect-webgl-support
QVariant hasContext = frame->evaluateJavaScript("var hasContext = false;"
"if( window.WebGLRenderingContext ) {"
" hasContext = true;"
"}");
QVariant hasGL = frame->evaluateJavaScript("var hasGL = false;"
"gl = canvas.getContext(\"webgl\");"
"if( gl ) {"
" hasGL = true;"
"}");
QVariant hasExperimentalGL = frame->evaluateJavaScript("var hasGL = false;"
"gl = canvas.getContext(\"experimental-webgl\");"
"if( gl ) {"
" hasGL = true;"
"}");
BOOST_CHECK( hasContext.toBool( ));
BOOST_CHECK( hasGL.toBool() || hasExperimentalGL.toBool( ));
delete streamer;
}
BOOST_AUTO_TEST_CASE( test_webgl_interaction )
{
if( !hasGLXDisplay( ))
return;
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
// Normalized mouse coordinates
InteractionState pressState;
pressState.mouseX = 0.1;
pressState.mouseY = 0.1;
pressState.mouseLeft = true;
pressState.type = InteractionState::EVT_PRESS;
InteractionState moveState;
moveState.mouseX = 0.2;
moveState.mouseY = 0.2;
moveState.mouseLeft = true;
moveState.type = InteractionState::EVT_MOVE;
InteractionState releaseState;
releaseState.mouseX = 0.2;
releaseState.mouseY = 0.2;
releaseState.mouseLeft = true;
releaseState.type = InteractionState::EVT_RELEASE;
streamer->updateInteractionState(pressState);
streamer->updateInteractionState(moveState);
streamer->updateInteractionState(releaseState);
const int expectedDisplacementX = (releaseState.mouseX-pressState.mouseX) *
streamer->size().width() / streamer->getView()->zoomFactor();
const int expectedDisplacementY = (releaseState.mouseY-pressState.mouseY) *
streamer->size().height() / streamer->getView()->zoomFactor();
QString jsX = QString("deltaX == %1;").arg(expectedDisplacementX);
QString jsY = QString("deltaY == %1;").arg(expectedDisplacementY);
QVariant validDeltaX = frame->evaluateJavaScript(jsX);
QVariant validDeltaY = frame->evaluateJavaScript(jsY);
BOOST_CHECK( validDeltaX.toBool());
BOOST_CHECK( validDeltaY.toBool());
delete streamer;
}
BOOST_AUTO_TEST_CASE( test_webgl_click )
{
if( !hasGLXDisplay( ))
return;
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
// Normalized mouse coordinates
InteractionState clickState;
clickState.mouseX = 0.1;
clickState.mouseY = 0.1;
clickState.mouseLeft = true;
clickState.type = InteractionState::EVT_CLICK;
streamer->updateInteractionState(clickState);
const int expectedPosX = clickState.mouseX * streamer->size().width() /
streamer->getView()->zoomFactor();
const int expectedPosY = clickState.mouseY * streamer->size().height() /
streamer->getView()->zoomFactor();
QString jsX = QString("lastMouseX == %1;").arg(expectedPosX);
QString jsY = QString("lastMouseY == %1;").arg(expectedPosY);
BOOST_CHECK( frame->evaluateJavaScript(jsX).toBool());
BOOST_CHECK( frame->evaluateJavaScript(jsY).toBool());
delete streamer;
}
BOOST_AUTO_TEST_CASE( test_webgl_wheel )
{
if( !hasGLXDisplay( ))
return;
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
// Normalized mouse coordinates
InteractionState wheelState;
wheelState.mouseX = 0.1;
wheelState.mouseY = 0.1;
wheelState.dy = 0.05;
wheelState.type = InteractionState::EVT_WHEEL;
streamer->updateInteractionState(wheelState);
const int expectedPosX = wheelState.mouseX * streamer->size().width() /
streamer->getView()->zoomFactor();
const int expectedPosY = wheelState.mouseY * streamer->size().height() /
streamer->getView()->zoomFactor();
const int expectedWheelDelta = wheelState.dy * g_configuration->getTotalHeight();
QString jsX = QString("lastMouseX == %1;").arg(expectedPosX);
QString jsY = QString("lastMouseY == %1;").arg(expectedPosY);
QString jsD = QString("wheelDelta == %1;").arg(expectedWheelDelta);
BOOST_CHECK( frame->evaluateJavaScript(jsX).toBool());
BOOST_CHECK( frame->evaluateJavaScript(jsY).toBool());
BOOST_CHECK( frame->evaluateJavaScript(jsD).toBool());
delete streamer;
}
<commit_msg>More fixes for headless unit tests<commit_after>/*********************************************************************/
/* Copyright (c) 2013, EPFL/Blue Brain Project */
/* Daniel Nachbaur <daniel.nachbaur@epfl.ch> */
/* 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 UNIVERSITY OF TEXAS AT */
/* AUSTIN ``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 UNIVERSITY OF TEXAS AT */
/* AUSTIN 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. */
/* */
/* The views and conclusions contained in the software and */
/* documentation are those of the authors and should not be */
/* interpreted as representing official policies, either expressed */
/* or implied, of The University of Texas at Austin. */
/*********************************************************************/
#define BOOST_TEST_MODULE WebBrowser
#include <boost/test/unit_test.hpp>
namespace ut = boost::unit_test;
#include "globals.h"
#include "Options.h"
#include "configuration/Configuration.h"
#include "WebkitPixelStreamer.h"
#include <QApplication>
#include <QWebElementCollection>
#include <QWebFrame>
#include <QWebPage>
#include <QWebView>
#include <X11/Xlib.h>
#define TEST_PAGE_URL "webgl_interaction.html"
#define CONFIG_TEST_FILENAME "configuration.xml"
namespace ut = boost::unit_test;
bool hasGLXDisplay()
{
Display* display = XOpenDisplay( 0 );
if( !display )
return false;
int major, event, error;
const bool hasGLX = XQueryExtension( display, "GLX", &major, &event,
&error );
XCloseDisplay( display );
return hasGLX;
}
// We need a global fixture because a bug in QApplication prevents
// deleting then recreating a QApplication in the same process.
// https://bugreports.qt-project.org/browse/QTBUG-7104
struct GlobalQtApp
{
GlobalQtApp()
: app( 0 )
{
if( !hasGLXDisplay( ))
return;
// need QApplication to instantiate WebkitPixelStreamer
ut::master_test_suite_t& testSuite = ut::framework::master_test_suite();
app = new QApplication( testSuite.argc, testSuite.argv );
// To test wheel events the WebkitPixelStreamer needs access to the g_configuration element
OptionsPtr options(new Options());
g_configuration = new Configuration(CONFIG_TEST_FILENAME, options);
}
~GlobalQtApp()
{
delete g_configuration;
delete app;
}
QApplication* app;
};
BOOST_GLOBAL_FIXTURE( GlobalQtApp );
BOOST_AUTO_TEST_CASE( test_webgl_support )
{
if( !hasGLXDisplay( ))
return;
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
QWebElementCollection webglCanvases = frame->findAllElements( "canvas[id=webgl-canvas]" );
BOOST_REQUIRE_EQUAL( webglCanvases.count(), 1 );
// http://stackoverflow.com/questions/11871077/proper-way-to-detect-webgl-support
QVariant hasContext = frame->evaluateJavaScript("var hasContext = false;"
"if( window.WebGLRenderingContext ) {"
" hasContext = true;"
"}");
QVariant hasGL = frame->evaluateJavaScript("var hasGL = false;"
"gl = canvas.getContext(\"webgl\");"
"if( gl ) {"
" hasGL = true;"
"}");
QVariant hasExperimentalGL = frame->evaluateJavaScript("var hasGL = false;"
"gl = canvas.getContext(\"experimental-webgl\");"
"if( gl ) {"
" hasGL = true;"
"}");
BOOST_CHECK( hasContext.toBool( ));
BOOST_CHECK( hasGL.toBool() || hasExperimentalGL.toBool( ));
delete streamer;
}
BOOST_AUTO_TEST_CASE( test_webgl_interaction )
{
if( !hasGLXDisplay( ))
return;
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
// Normalized mouse coordinates
InteractionState pressState;
pressState.mouseX = 0.1;
pressState.mouseY = 0.1;
pressState.mouseLeft = true;
pressState.type = InteractionState::EVT_PRESS;
InteractionState moveState;
moveState.mouseX = 0.2;
moveState.mouseY = 0.2;
moveState.mouseLeft = true;
moveState.type = InteractionState::EVT_MOVE;
InteractionState releaseState;
releaseState.mouseX = 0.2;
releaseState.mouseY = 0.2;
releaseState.mouseLeft = true;
releaseState.type = InteractionState::EVT_RELEASE;
streamer->updateInteractionState(pressState);
streamer->updateInteractionState(moveState);
streamer->updateInteractionState(releaseState);
const int expectedDisplacementX = (releaseState.mouseX-pressState.mouseX) *
streamer->size().width() / streamer->getView()->zoomFactor();
const int expectedDisplacementY = (releaseState.mouseY-pressState.mouseY) *
streamer->size().height() / streamer->getView()->zoomFactor();
QString jsX = QString("deltaX == %1;").arg(expectedDisplacementX);
QString jsY = QString("deltaY == %1;").arg(expectedDisplacementY);
QVariant validDeltaX = frame->evaluateJavaScript(jsX);
QVariant validDeltaY = frame->evaluateJavaScript(jsY);
BOOST_CHECK( validDeltaX.toBool());
BOOST_CHECK( validDeltaY.toBool());
delete streamer;
}
BOOST_AUTO_TEST_CASE( test_webgl_click )
{
if( !hasGLXDisplay( ))
return;
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
// Normalized mouse coordinates
InteractionState clickState;
clickState.mouseX = 0.1;
clickState.mouseY = 0.1;
clickState.mouseLeft = true;
clickState.type = InteractionState::EVT_CLICK;
streamer->updateInteractionState(clickState);
const int expectedPosX = clickState.mouseX * streamer->size().width() /
streamer->getView()->zoomFactor();
const int expectedPosY = clickState.mouseY * streamer->size().height() /
streamer->getView()->zoomFactor();
QString jsX = QString("lastMouseX == %1;").arg(expectedPosX);
QString jsY = QString("lastMouseY == %1;").arg(expectedPosY);
BOOST_CHECK( frame->evaluateJavaScript(jsX).toBool());
BOOST_CHECK( frame->evaluateJavaScript(jsY).toBool());
delete streamer;
}
BOOST_AUTO_TEST_CASE( test_webgl_wheel )
{
if( !hasGLXDisplay( ))
return;
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
// Normalized mouse coordinates
InteractionState wheelState;
wheelState.mouseX = 0.1;
wheelState.mouseY = 0.1;
wheelState.dy = 0.05;
wheelState.type = InteractionState::EVT_WHEEL;
streamer->updateInteractionState(wheelState);
const int expectedPosX = wheelState.mouseX * streamer->size().width() /
streamer->getView()->zoomFactor();
const int expectedPosY = wheelState.mouseY * streamer->size().height() /
streamer->getView()->zoomFactor();
const int expectedWheelDelta = wheelState.dy * g_configuration->getTotalHeight();
QString jsX = QString("lastMouseX == %1;").arg(expectedPosX);
QString jsY = QString("lastMouseY == %1;").arg(expectedPosY);
QString jsD = QString("wheelDelta == %1;").arg(expectedWheelDelta);
BOOST_CHECK( frame->evaluateJavaScript(jsX).toBool());
BOOST_CHECK( frame->evaluateJavaScript(jsY).toBool());
BOOST_CHECK( frame->evaluateJavaScript(jsD).toBool());
delete streamer;
}
<|endoftext|> |
<commit_before>/*********************************************************************/
/* Copyright (c) 2013, EPFL/Blue Brain Project */
/* Daniel Nachbaur <daniel.nachbaur@epfl.ch> */
/* 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 UNIVERSITY OF TEXAS AT */
/* AUSTIN ``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 UNIVERSITY OF TEXAS AT */
/* AUSTIN 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. */
/* */
/* The views and conclusions contained in the software and */
/* documentation are those of the authors and should not be */
/* interpreted as representing official policies, either expressed */
/* or implied, of The University of Texas at Austin. */
/*********************************************************************/
#define BOOST_TEST_MODULE WebBrowser
#include <boost/test/unit_test.hpp>
namespace ut = boost::unit_test;
#include "globals.h"
#include "Options.h"
#include "configuration/Configuration.h"
#include "WebkitPixelStreamer.h"
#include <QApplication>
#include <QWebElementCollection>
#include <QWebFrame>
#include <QWebPage>
#include <QWebView>
#include <X11/Xlib.h>
#define TEST_PAGE_URL "webgl_interaction.html"
#define CONFIG_TEST_FILENAME "configuration.xml"
namespace ut = boost::unit_test;
bool hasGLXDisplay()
{
Display* display = XOpenDisplay( 0 );
if( !display )
return false;
int major, event, error;
const bool hasGLX = XQueryExtension( display, "GLX", &major, &event,
&error );
XCloseDisplay( display );
return hasGLX;
}
// We need a global fixture because a bug in QApplication prevents
// deleting then recreating a QApplication in the same process.
// https://bugreports.qt-project.org/browse/QTBUG-7104
struct GlobalQtApp
{
GlobalQtApp()
{
// need QApplication to instantiate WebkitPixelStreamer
ut::master_test_suite_t& testSuite = ut::framework::master_test_suite();
app = new QApplication( testSuite.argc, testSuite.argv );
// To test wheel events the WebkitPixelStreamer needs access to the g_configuration element
OptionsPtr options(new Options());
g_configuration = new Configuration(CONFIG_TEST_FILENAME, options);
}
~GlobalQtApp()
{
delete g_configuration;
delete app;
}
QApplication* app;
};
BOOST_GLOBAL_FIXTURE( GlobalQtApp );
BOOST_AUTO_TEST_CASE( test_webgl_support )
{
if( !hasGLXDisplay( ))
return;
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
QWebElementCollection webglCanvases = frame->findAllElements( "canvas[id=webgl-canvas]" );
BOOST_REQUIRE_EQUAL( webglCanvases.count(), 1 );
// http://stackoverflow.com/questions/11871077/proper-way-to-detect-webgl-support
QVariant hasContext = frame->evaluateJavaScript("var hasContext = false;"
"if( window.WebGLRenderingContext ) {"
" hasContext = true;"
"}");
QVariant hasGL = frame->evaluateJavaScript("var hasGL = false;"
"gl = canvas.getContext(\"webgl\");"
"if( gl ) {"
" hasGL = true;"
"}");
QVariant hasExperimentalGL = frame->evaluateJavaScript("var hasGL = false;"
"gl = canvas.getContext(\"experimental-webgl\");"
"if( gl ) {"
" hasGL = true;"
"}");
BOOST_CHECK( hasContext.toBool( ));
BOOST_CHECK( hasGL.toBool() || hasExperimentalGL.toBool( ));
delete streamer;
}
BOOST_AUTO_TEST_CASE( test_webgl_interaction )
{
if( !hasGLXDisplay( ))
return;
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
// Normalized mouse coordinates
InteractionState pressState;
pressState.mouseX = 0.1;
pressState.mouseY = 0.1;
pressState.mouseLeft = true;
pressState.type = InteractionState::EVT_PRESS;
InteractionState moveState;
moveState.mouseX = 0.2;
moveState.mouseY = 0.2;
moveState.mouseLeft = true;
moveState.type = InteractionState::EVT_MOVE;
InteractionState releaseState;
releaseState.mouseX = 0.2;
releaseState.mouseY = 0.2;
releaseState.mouseLeft = true;
releaseState.type = InteractionState::EVT_RELEASE;
streamer->updateInteractionState(pressState);
streamer->updateInteractionState(moveState);
streamer->updateInteractionState(releaseState);
const int expectedDisplacementX = (releaseState.mouseX-pressState.mouseX) *
streamer->size().width() / streamer->getView()->zoomFactor();
const int expectedDisplacementY = (releaseState.mouseY-pressState.mouseY) *
streamer->size().height() / streamer->getView()->zoomFactor();
QString jsX = QString("deltaX == %1;").arg(expectedDisplacementX);
QString jsY = QString("deltaY == %1;").arg(expectedDisplacementY);
QVariant validDeltaX = frame->evaluateJavaScript(jsX);
QVariant validDeltaY = frame->evaluateJavaScript(jsY);
BOOST_CHECK( validDeltaX.toBool());
BOOST_CHECK( validDeltaY.toBool());
delete streamer;
}
BOOST_AUTO_TEST_CASE( test_webgl_click )
{
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
// Normalized mouse coordinates
InteractionState clickState;
clickState.mouseX = 0.1;
clickState.mouseY = 0.1;
clickState.mouseLeft = true;
clickState.type = InteractionState::EVT_CLICK;
streamer->updateInteractionState(clickState);
const int expectedPosX = clickState.mouseX * streamer->size().width() /
streamer->getView()->zoomFactor();
const int expectedPosY = clickState.mouseY * streamer->size().height() /
streamer->getView()->zoomFactor();
QString jsX = QString("lastMouseX == %1;").arg(expectedPosX);
QString jsY = QString("lastMouseY == %1;").arg(expectedPosY);
BOOST_CHECK( frame->evaluateJavaScript(jsX).toBool());
BOOST_CHECK( frame->evaluateJavaScript(jsY).toBool());
delete streamer;
}
BOOST_AUTO_TEST_CASE( test_webgl_wheel )
{
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
// Normalized mouse coordinates
InteractionState wheelState;
wheelState.mouseX = 0.1;
wheelState.mouseY = 0.1;
wheelState.dy = 0.05;
wheelState.type = InteractionState::EVT_WHEEL;
streamer->updateInteractionState(wheelState);
const int expectedPosX = wheelState.mouseX * streamer->size().width() /
streamer->getView()->zoomFactor();
const int expectedPosY = wheelState.mouseY * streamer->size().height() /
streamer->getView()->zoomFactor();
const int expectedWheelDelta = wheelState.dy * g_configuration->getTotalHeight();
QString jsX = QString("lastMouseX == %1;").arg(expectedPosX);
QString jsY = QString("lastMouseY == %1;").arg(expectedPosY);
QString jsD = QString("wheelDelta == %1;").arg(expectedWheelDelta);
BOOST_CHECK( frame->evaluateJavaScript(jsX).toBool());
BOOST_CHECK( frame->evaluateJavaScript(jsY).toBool());
BOOST_CHECK( frame->evaluateJavaScript(jsD).toBool());
delete streamer;
}
<commit_msg>Fix tests on travis<commit_after>/*********************************************************************/
/* Copyright (c) 2013, EPFL/Blue Brain Project */
/* Daniel Nachbaur <daniel.nachbaur@epfl.ch> */
/* 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 UNIVERSITY OF TEXAS AT */
/* AUSTIN ``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 UNIVERSITY OF TEXAS AT */
/* AUSTIN 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. */
/* */
/* The views and conclusions contained in the software and */
/* documentation are those of the authors and should not be */
/* interpreted as representing official policies, either expressed */
/* or implied, of The University of Texas at Austin. */
/*********************************************************************/
#define BOOST_TEST_MODULE WebBrowser
#include <boost/test/unit_test.hpp>
namespace ut = boost::unit_test;
#include "globals.h"
#include "Options.h"
#include "configuration/Configuration.h"
#include "WebkitPixelStreamer.h"
#include <QApplication>
#include <QWebElementCollection>
#include <QWebFrame>
#include <QWebPage>
#include <QWebView>
#include <X11/Xlib.h>
#define TEST_PAGE_URL "webgl_interaction.html"
#define CONFIG_TEST_FILENAME "configuration.xml"
namespace ut = boost::unit_test;
bool hasGLXDisplay()
{
Display* display = XOpenDisplay( 0 );
if( !display )
return false;
int major, event, error;
const bool hasGLX = XQueryExtension( display, "GLX", &major, &event,
&error );
XCloseDisplay( display );
return hasGLX;
}
// We need a global fixture because a bug in QApplication prevents
// deleting then recreating a QApplication in the same process.
// https://bugreports.qt-project.org/browse/QTBUG-7104
struct GlobalQtApp
{
GlobalQtApp()
{
// need QApplication to instantiate WebkitPixelStreamer
ut::master_test_suite_t& testSuite = ut::framework::master_test_suite();
app = new QApplication( testSuite.argc, testSuite.argv );
// To test wheel events the WebkitPixelStreamer needs access to the g_configuration element
OptionsPtr options(new Options());
g_configuration = new Configuration(CONFIG_TEST_FILENAME, options);
}
~GlobalQtApp()
{
delete g_configuration;
delete app;
}
QApplication* app;
};
BOOST_GLOBAL_FIXTURE( GlobalQtApp );
BOOST_AUTO_TEST_CASE( test_webgl_support )
{
if( !hasGLXDisplay( ))
return;
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
QWebElementCollection webglCanvases = frame->findAllElements( "canvas[id=webgl-canvas]" );
BOOST_REQUIRE_EQUAL( webglCanvases.count(), 1 );
// http://stackoverflow.com/questions/11871077/proper-way-to-detect-webgl-support
QVariant hasContext = frame->evaluateJavaScript("var hasContext = false;"
"if( window.WebGLRenderingContext ) {"
" hasContext = true;"
"}");
QVariant hasGL = frame->evaluateJavaScript("var hasGL = false;"
"gl = canvas.getContext(\"webgl\");"
"if( gl ) {"
" hasGL = true;"
"}");
QVariant hasExperimentalGL = frame->evaluateJavaScript("var hasGL = false;"
"gl = canvas.getContext(\"experimental-webgl\");"
"if( gl ) {"
" hasGL = true;"
"}");
BOOST_CHECK( hasContext.toBool( ));
BOOST_CHECK( hasGL.toBool() || hasExperimentalGL.toBool( ));
delete streamer;
}
BOOST_AUTO_TEST_CASE( test_webgl_interaction )
{
if( !hasGLXDisplay( ))
return;
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
// Normalized mouse coordinates
InteractionState pressState;
pressState.mouseX = 0.1;
pressState.mouseY = 0.1;
pressState.mouseLeft = true;
pressState.type = InteractionState::EVT_PRESS;
InteractionState moveState;
moveState.mouseX = 0.2;
moveState.mouseY = 0.2;
moveState.mouseLeft = true;
moveState.type = InteractionState::EVT_MOVE;
InteractionState releaseState;
releaseState.mouseX = 0.2;
releaseState.mouseY = 0.2;
releaseState.mouseLeft = true;
releaseState.type = InteractionState::EVT_RELEASE;
streamer->updateInteractionState(pressState);
streamer->updateInteractionState(moveState);
streamer->updateInteractionState(releaseState);
const int expectedDisplacementX = (releaseState.mouseX-pressState.mouseX) *
streamer->size().width() / streamer->getView()->zoomFactor();
const int expectedDisplacementY = (releaseState.mouseY-pressState.mouseY) *
streamer->size().height() / streamer->getView()->zoomFactor();
QString jsX = QString("deltaX == %1;").arg(expectedDisplacementX);
QString jsY = QString("deltaY == %1;").arg(expectedDisplacementY);
QVariant validDeltaX = frame->evaluateJavaScript(jsX);
QVariant validDeltaY = frame->evaluateJavaScript(jsY);
BOOST_CHECK( validDeltaX.toBool());
BOOST_CHECK( validDeltaY.toBool());
delete streamer;
}
BOOST_AUTO_TEST_CASE( test_webgl_click )
{
if( !hasGLXDisplay( ))
return;
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
// Normalized mouse coordinates
InteractionState clickState;
clickState.mouseX = 0.1;
clickState.mouseY = 0.1;
clickState.mouseLeft = true;
clickState.type = InteractionState::EVT_CLICK;
streamer->updateInteractionState(clickState);
const int expectedPosX = clickState.mouseX * streamer->size().width() /
streamer->getView()->zoomFactor();
const int expectedPosY = clickState.mouseY * streamer->size().height() /
streamer->getView()->zoomFactor();
QString jsX = QString("lastMouseX == %1;").arg(expectedPosX);
QString jsY = QString("lastMouseY == %1;").arg(expectedPosY);
BOOST_CHECK( frame->evaluateJavaScript(jsX).toBool());
BOOST_CHECK( frame->evaluateJavaScript(jsY).toBool());
delete streamer;
}
BOOST_AUTO_TEST_CASE( test_webgl_wheel )
{
if( !hasGLXDisplay( ))
return;
// load the webgl website, exec() returns when loading is finished
WebkitPixelStreamer* streamer = new WebkitPixelStreamer( "testBrowser" );
QObject::connect( streamer->getView(), SIGNAL(loadFinished(bool)),
QApplication::instance(), SLOT(quit()));
streamer->setUrl( TEST_PAGE_URL );
QApplication::instance()->exec();
QWebPage* page = streamer->getView()->page();
BOOST_REQUIRE( page );
QWebFrame* frame = page->mainFrame();
BOOST_REQUIRE( frame );
// Normalized mouse coordinates
InteractionState wheelState;
wheelState.mouseX = 0.1;
wheelState.mouseY = 0.1;
wheelState.dy = 0.05;
wheelState.type = InteractionState::EVT_WHEEL;
streamer->updateInteractionState(wheelState);
const int expectedPosX = wheelState.mouseX * streamer->size().width() /
streamer->getView()->zoomFactor();
const int expectedPosY = wheelState.mouseY * streamer->size().height() /
streamer->getView()->zoomFactor();
const int expectedWheelDelta = wheelState.dy * g_configuration->getTotalHeight();
QString jsX = QString("lastMouseX == %1;").arg(expectedPosX);
QString jsY = QString("lastMouseY == %1;").arg(expectedPosY);
QString jsD = QString("wheelDelta == %1;").arg(expectedWheelDelta);
BOOST_CHECK( frame->evaluateJavaScript(jsX).toBool());
BOOST_CHECK( frame->evaluateJavaScript(jsY).toBool());
BOOST_CHECK( frame->evaluateJavaScript(jsD).toBool());
delete streamer;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
//
// ------------------------------------------------------------------------
// Extruder Miniapp: Extrude a low dimensional mesh into a higher dimension
// ------------------------------------------------------------------------
//
// This miniapp performs multiple levels of adaptive mesh refinement to resolve
// the interfaces between different "materials" in the mesh, as specified by the
// given material() function. It can be used as a simple initial mesh generator,
// for example in the case when the interface is too complex to describe without
// local refinement. Both conforming and non-conforming refinements are supported.
//
// Compile with: make extruder
//
// Sample runs:
// extruder
// extruder -m ../../data/inline-segment.mesh -ny 8 -wy 2
// extruder -m ../../data/inline-segment.mesh -ny 8 -wy 2 -nz 12 -hz 3
// extruder -m ../../data/star.mesh -nz 3
// extruder -m ../../data/star-mixed.mesh -nz 3
// extruder -m ../../data/square-disc.mesh -nz 3
// extruder -m ../../data/square-disc.mesh -nz 3
// extruder -m ../../data/inline-segment.mesh -ny 8 -wy 2 -trans
// extruder -m ../../data/inline-segment.mesh -ny 8 -wy 2 -nz 12 -hz 3 -trans
// extruder -m ../../data/star.mesh -nz 3 -trans
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace mfem;
using namespace std;
void trans2D(const Vector&, Vector&);
void trans3D(const Vector&, Vector&);
int main(int argc, char *argv[])
{
const char *mesh_file = "../../data/inline-quad.mesh";
int ny = -1, nz = -1;
double wy = 1.0, hz = 1.0;
bool trans = false;
bool visualization = 1;
// Parse command line
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Input mesh file to shape materials in.");
args.AddOption(&ny, "-ny", "--num-elem-in-y",
"Extrude a 1D mesh into ny elements in the y-direction.");
args.AddOption(&wy, "-wy", "--width-in-y",
"Extrude a 1D mesh to a width wy in the y-direction.");
args.AddOption(&nz, "-nz", "--num-elem-in-z",
"Extrude a 2D mesh into nz elements in the z-direction.");
args.AddOption(&hz, "-hz", "--height-in-z",
"Extrude a 2D mesh to a height hz in the z-direction.");
args.AddOption(&trans, "-trans", "--transform", "-no-trans",
"--no-transform",
"Enable or disable mesh transformation.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.Parse();
if (!args.Good()) { args.PrintUsage(cout); return 1; }
args.PrintOptions(cout);
// Read initial mesh, get dimensions and bounding box
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
bool newMesh = false;
if ( dim == 3 )
{
cout << "Extruding 3D meshes is not (yet) supported." << endl;
delete mesh;
exit(0);
}
if ( dim == 1 && ny > 0 )
{
cout << "Extruding 1D mesh to a width of " << wy
<< " using " << ny << " elements." << endl;
Mesh *mesh2d = Extrude1D(mesh, ny, wy);
delete mesh;
mesh = mesh2d;
dim = 2;
if (trans)
{
mesh->SetCurvature(3, false, 2, Ordering::byVDIM);
mesh->Transform(trans2D);
}
newMesh = true;
}
if ( dim == 2 && nz > 0 )
{
cout << "Extruding 2D mesh to a height of " << hz
<< " using " << nz << " elements." << endl;
Mesh *mesh3d = Extrude2D(mesh, nz, hz);
delete mesh;
mesh = mesh3d;
dim = 3;
if (trans)
{
mesh->SetCurvature(3, false, 3, Ordering::byVDIM);
mesh->Transform(trans3D);
}
newMesh = true;
}
if ( newMesh )
{
if (visualization)
{
// GLVis server to visualize to
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock.precision(8);
sol_sock << "mesh\n" << *mesh << flush;
}
// Save the final mesh
ofstream mesh_ofs("extruder.mesh");
mesh_ofs.precision(8);
mesh->Print(mesh_ofs);
}
else
{
cout << "No mesh extrusion performed." << endl;
}
delete mesh;
}
void trans2D(const Vector&x, Vector&p)
{
p[0] = x[0] + 0.25 * sin(M_PI * x[1]);
p[1] = x[1];
}
void trans3D(const Vector&x, Vector&p)
{
double r = sqrt(x[0] * x[0] + x[1] * x[1]);
double theta = atan2(x[1], x[0]);
p[0] = r * cos(theta + 0.25 * M_PI * x[2]);
p[1] = r * sin(theta + 0.25 * M_PI * x[2]);
p[2] = x[2];
}
<commit_msg>Controlling the order used for transformed meshes<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
//
// ------------------------------------------------------------------------
// Extruder Miniapp: Extrude a low dimensional mesh into a higher dimension
// ------------------------------------------------------------------------
//
// This miniapp performs multiple levels of adaptive mesh refinement to resolve
// the interfaces between different "materials" in the mesh, as specified by the
// given material() function. It can be used as a simple initial mesh generator,
// for example in the case when the interface is too complex to describe without
// local refinement. Both conforming and non-conforming refinements are supported.
//
// Compile with: make extruder
//
// Sample runs:
// extruder
// extruder -m ../../data/inline-segment.mesh -ny 8 -wy 2
// extruder -m ../../data/inline-segment.mesh -ny 8 -wy 2 -nz 12 -hz 3
// extruder -m ../../data/star.mesh -nz 3
// extruder -m ../../data/star-mixed.mesh -nz 3
// extruder -m ../../data/square-disc.mesh -nz 3
// extruder -m ../../data/square-disc.mesh -nz 3
// extruder -m ../../data/inline-segment.mesh -ny 8 -wy 2 -trans
// extruder -m ../../data/inline-segment.mesh -ny 8 -wy 2 -nz 12 -hz 3 -trans
// extruder -m ../../data/star.mesh -nz 3 -trans
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace mfem;
using namespace std;
void trans2D(const Vector&, Vector&);
void trans3D(const Vector&, Vector&);
int main(int argc, char *argv[])
{
const char *mesh_file = "../../data/inline-quad.mesh";
int order = -1;
int ny = -1, nz = -1;
double wy = 1.0, hz = 1.0;
bool trans = false;
bool visualization = 1;
// Parse command line
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Input mesh file to shape materials in.");
args.AddOption(&order, "-o", "--mesh-order",
"Order (polynomial degree) of the mesh elements.");
args.AddOption(&ny, "-ny", "--num-elem-in-y",
"Extrude a 1D mesh into ny elements in the y-direction.");
args.AddOption(&wy, "-wy", "--width-in-y",
"Extrude a 1D mesh to a width wy in the y-direction.");
args.AddOption(&nz, "-nz", "--num-elem-in-z",
"Extrude a 2D mesh into nz elements in the z-direction.");
args.AddOption(&hz, "-hz", "--height-in-z",
"Extrude a 2D mesh to a height hz in the z-direction.");
args.AddOption(&trans, "-trans", "--transform", "-no-trans",
"--no-transform",
"Enable or disable mesh transformation.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.Parse();
if (!args.Good()) { args.PrintUsage(cout); return 1; }
args.PrintOptions(cout);
// Read initial mesh, get dimensions and bounding box
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
// Determine the order to use for a transformed mesh
if ( order < 0 && trans )
{
int meshOrder = 1;
if ( mesh->GetNodalFESpace() != NULL )
{
meshOrder = mesh->GetNodalFESpace()->GetORder(0);
}
order = meshOrder;
}
bool newMesh = false;
if ( dim == 3 )
{
cout << "Extruding 3D meshes is not (yet) supported." << endl;
delete mesh;
exit(0);
}
if ( dim == 1 && ny > 0 )
{
cout << "Extruding 1D mesh to a width of " << wy
<< " using " << ny << " elements." << endl;
Mesh *mesh2d = Extrude1D(mesh, ny, wy);
delete mesh;
mesh = mesh2d;
dim = 2;
if (trans)
{
mesh->SetCurvature(order, false, 2, Ordering::byVDIM);
mesh->Transform(trans2D);
}
newMesh = true;
}
if ( dim == 2 && nz > 0 )
{
cout << "Extruding 2D mesh to a height of " << hz
<< " using " << nz << " elements." << endl;
Mesh *mesh3d = Extrude2D(mesh, nz, hz);
delete mesh;
mesh = mesh3d;
dim = 3;
if (trans)
{
mesh->SetCurvature(order, false, 3, Ordering::byVDIM);
mesh->Transform(trans3D);
}
newMesh = true;
}
if ( newMesh )
{
if (visualization)
{
// GLVis server to visualize to
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock.precision(8);
sol_sock << "mesh\n" << *mesh << flush;
}
// Save the final mesh
ofstream mesh_ofs("extruder.mesh");
mesh_ofs.precision(8);
mesh->Print(mesh_ofs);
}
else
{
cout << "No mesh extrusion performed." << endl;
}
delete mesh;
}
void trans2D(const Vector&x, Vector&p)
{
p[0] = x[0] + 0.25 * sin(M_PI * x[1]);
p[1] = x[1];
}
void trans3D(const Vector&x, Vector&p)
{
double r = sqrt(x[0] * x[0] + x[1] * x[1]);
double theta = atan2(x[1], x[0]);
p[0] = r * cos(theta + 0.25 * M_PI * x[2]);
p[1] = r * sin(theta + 0.25 * M_PI * x[2]);
p[2] = x[2];
}
<|endoftext|> |
<commit_before>#include "sampler.hpp"
#include "context.hpp"
#include "texture.hpp"
#include "internal/wrapper.hpp"
#include "internal/modules.hpp"
#include "internal/tools.hpp"
#include "internal/glsl.hpp"
/* MGLContext.sampler(texture)
*/
PyObject * MGLContext_meth_sampler(MGLContext * self, PyObject * const * args, Py_ssize_t nargs) {
if (nargs != 1) {
// TODO: error
return 0;
}
PyObject * texture = args[0];
MGLSampler * sampler = MGLContext_new_object(self, Sampler);
const GLMethods & gl = self->gl;
gl.GenSamplers(1, (GLuint *)&sampler->sampler_obj);
if (!sampler->sampler_obj) {
PyErr_Format(moderngl_error, "cannot create sampler");
Py_DECREF(sampler);
return 0;
}
gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
SLOT(sampler->wrapper, PyObject, Sampler_class_texture) = texture;
return NEW_REF(sampler->wrapper);
}
/* MGLSampler.use(location)
*/
PyObject * MGLSampler_meth_use(MGLSampler * self, PyObject * arg) {
PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture);
MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo);
int location = PyLong_AsLong(arg);
self->context->bind_sampler(location, texture->texture_target, texture->texture_obj, self->sampler_obj);
Py_RETURN_NONE;
}
int MGLSampler_set_filter(MGLSampler * self, PyObject * value) {
return 0;
}
enum MGLSamplerWrapModes {
MGL_CLAMP_TO_EDGE = 0x01,
MGL_REPEAT = 0x02,
MGL_MIRRORED_REPEAT = 0x04,
MGL_MIRROR_CLAMP_TO_EDGE = 0x08,
MGL_CLAMP_TO_BORDER = 0x10,
};
int MGLSampler_set_wrap(MGLSampler * self, PyObject * value) {
int wrap = PyLong_AsLong(value);
SLOT(self->wrapper, PyObject, Sampler_class_wrap) = PyLong_FromLong(wrap);
switch (((unsigned char *)&wrap)[0]) {
case 0:
case MGL_CLAMP_TO_EDGE:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
break;
case MGL_REPEAT:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_REPEAT);
break;
case MGL_MIRRORED_REPEAT:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
break;
case MGL_MIRROR_CLAMP_TO_EDGE:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRROR_CLAMP_TO_EDGE);
break;
case MGL_CLAMP_TO_BORDER:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
break;
default:
// TODO: error
return -1;
}
switch (((unsigned char *)&wrap)[1]) {
case 0:
case MGL_CLAMP_TO_EDGE:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
break;
case MGL_REPEAT:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_REPEAT);
break;
case MGL_MIRRORED_REPEAT:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
break;
case MGL_MIRROR_CLAMP_TO_EDGE:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRROR_CLAMP_TO_EDGE);
break;
case MGL_CLAMP_TO_BORDER:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
break;
default:
// TODO: error
return -1;
}
PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture);
MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo);
if (texture->texture_target == GL_TEXTURE_3D) {
switch (((unsigned char *)&wrap)[2]) {
case 0:
case MGL_CLAMP_TO_EDGE:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
break;
case MGL_REPEAT:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_REPEAT);
break;
case MGL_MIRRORED_REPEAT:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRRORED_REPEAT);
break;
case MGL_MIRROR_CLAMP_TO_EDGE:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRROR_CLAMP_TO_EDGE);
break;
case MGL_CLAMP_TO_BORDER:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);
break;
default:
// TODO: error
return -1;
}
} else if (((unsigned char *)&wrap)[2]) {
return -1;
}
return 0;
}
int MGLSampler_set_anisotropy(MGLSampler * self, PyObject * value) {
return 0;
}
int MGLSampler_set_min_lod(MGLSampler * self, PyObject * value) {
int min_lod = PyLong_AsLong(value);
SLOT(self->wrapper, PyObject, Sampler_class_min_lod) = NEW_REF(value);
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MIN_LOD, min_lod);
return 0;
}
int MGLSampler_set_max_lod(MGLSampler * self, PyObject * value) {
int max_lod = PyLong_AsLong(value);
SLOT(self->wrapper, PyObject, Sampler_class_max_lod) = NEW_REF(value);
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MAX_LOD, max_lod);
return 0;
}
#if PY_VERSION_HEX >= 0x03070000
PyMethodDef MGLSampler_methods[] = {
{"use", (PyCFunction)MGLSampler_meth_use, METH_O, 0},
{0},
};
#else
PyMethodDef MGLSampler_methods[] = {
{"use", (PyCFunction)MGLSampler_meth_use, METH_O, 0},
{0},
};
#endif
PyGetSetDef MGLSampler_getset[] = {
{"filter", 0, (setter)MGLSampler_set_filter, 0, 0},
{"wrap", 0, (setter)MGLSampler_set_wrap, 0, 0},
{"anisotropy", 0, (setter)MGLSampler_set_anisotropy, 0, 0},
{"min_lod", 0, (setter)MGLSampler_set_min_lod, 0, 0},
{"max_lod", 0, (setter)MGLSampler_set_max_lod, 0, 0},
{0},
};
PyType_Slot MGLSampler_slots[] = {
{Py_tp_methods, MGLSampler_methods},
{Py_tp_getset, MGLSampler_getset},
{0},
};
PyType_Spec MGLSampler_spec = {
mgl_ext ".Sampler",
sizeof(MGLSampler),
0,
Py_TPFLAGS_DEFAULT,
MGLSampler_slots,
};
<commit_msg>anisotropy setter<commit_after>#include "sampler.hpp"
#include "context.hpp"
#include "texture.hpp"
#include "internal/wrapper.hpp"
#include "internal/modules.hpp"
#include "internal/tools.hpp"
#include "internal/glsl.hpp"
/* MGLContext.sampler(texture)
*/
PyObject * MGLContext_meth_sampler(MGLContext * self, PyObject * const * args, Py_ssize_t nargs) {
if (nargs != 1) {
// TODO: error
return 0;
}
PyObject * texture = args[0];
MGLSampler * sampler = MGLContext_new_object(self, Sampler);
const GLMethods & gl = self->gl;
gl.GenSamplers(1, (GLuint *)&sampler->sampler_obj);
if (!sampler->sampler_obj) {
PyErr_Format(moderngl_error, "cannot create sampler");
Py_DECREF(sampler);
return 0;
}
gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
SLOT(sampler->wrapper, PyObject, Sampler_class_texture) = texture;
return NEW_REF(sampler->wrapper);
}
/* MGLSampler.use(location)
*/
PyObject * MGLSampler_meth_use(MGLSampler * self, PyObject * arg) {
PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture);
MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo);
int location = PyLong_AsLong(arg);
self->context->bind_sampler(location, texture->texture_target, texture->texture_obj, self->sampler_obj);
Py_RETURN_NONE;
}
int MGLSampler_set_filter(MGLSampler * self, PyObject * value) {
return 0;
}
enum MGLSamplerWrapModes {
MGL_CLAMP_TO_EDGE = 0x01,
MGL_REPEAT = 0x02,
MGL_MIRRORED_REPEAT = 0x04,
MGL_MIRROR_CLAMP_TO_EDGE = 0x08,
MGL_CLAMP_TO_BORDER = 0x10,
};
int MGLSampler_set_wrap(MGLSampler * self, PyObject * value) {
int wrap = PyLong_AsLong(value);
SLOT(self->wrapper, PyObject, Sampler_class_wrap) = PyLong_FromLong(wrap);
switch (((unsigned char *)&wrap)[0]) {
case 0:
case MGL_CLAMP_TO_EDGE:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
break;
case MGL_REPEAT:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_REPEAT);
break;
case MGL_MIRRORED_REPEAT:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
break;
case MGL_MIRROR_CLAMP_TO_EDGE:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRROR_CLAMP_TO_EDGE);
break;
case MGL_CLAMP_TO_BORDER:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
break;
default:
// TODO: error
return -1;
}
switch (((unsigned char *)&wrap)[1]) {
case 0:
case MGL_CLAMP_TO_EDGE:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
break;
case MGL_REPEAT:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_REPEAT);
break;
case MGL_MIRRORED_REPEAT:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
break;
case MGL_MIRROR_CLAMP_TO_EDGE:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRROR_CLAMP_TO_EDGE);
break;
case MGL_CLAMP_TO_BORDER:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
break;
default:
// TODO: error
return -1;
}
PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture);
MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo);
if (texture->texture_target == GL_TEXTURE_3D) {
switch (((unsigned char *)&wrap)[2]) {
case 0:
case MGL_CLAMP_TO_EDGE:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
break;
case MGL_REPEAT:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_REPEAT);
break;
case MGL_MIRRORED_REPEAT:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRRORED_REPEAT);
break;
case MGL_MIRROR_CLAMP_TO_EDGE:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRROR_CLAMP_TO_EDGE);
break;
case MGL_CLAMP_TO_BORDER:
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);
break;
default:
// TODO: error
return -1;
}
} else if (((unsigned char *)&wrap)[2]) {
return -1;
}
return 0;
}
int MGLSampler_set_anisotropy(MGLSampler * self, PyObject * value) {
float anisotropy = PyFloat_AsDouble(value);
if (anisotropy < 1.0) {
anisotropy = 1.0;
}
// if (anisotropy > max_anisotropy) {
// anisotropy = max_anisotropy;
// }
SLOT(self->wrapper, PyObject, Sampler_class_max_lod) = PyFloat_FromDouble(anisotropy);
self->context->gl.SamplerParameterf(self->sampler_obj, GL_TEXTURE_MAX_ANISOTROPY, anisotropy);
return 0;
}
int MGLSampler_set_min_lod(MGLSampler * self, PyObject * value) {
int min_lod = PyLong_AsLong(value);
SLOT(self->wrapper, PyObject, Sampler_class_min_lod) = NEW_REF(value);
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MIN_LOD, min_lod);
return 0;
}
int MGLSampler_set_max_lod(MGLSampler * self, PyObject * value) {
int max_lod = PyLong_AsLong(value);
SLOT(self->wrapper, PyObject, Sampler_class_max_lod) = NEW_REF(value);
self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MAX_LOD, max_lod);
return 0;
}
#if PY_VERSION_HEX >= 0x03070000
PyMethodDef MGLSampler_methods[] = {
{"use", (PyCFunction)MGLSampler_meth_use, METH_O, 0},
{0},
};
#else
PyMethodDef MGLSampler_methods[] = {
{"use", (PyCFunction)MGLSampler_meth_use, METH_O, 0},
{0},
};
#endif
PyGetSetDef MGLSampler_getset[] = {
{"filter", 0, (setter)MGLSampler_set_filter, 0, 0},
{"wrap", 0, (setter)MGLSampler_set_wrap, 0, 0},
{"anisotropy", 0, (setter)MGLSampler_set_anisotropy, 0, 0},
{"min_lod", 0, (setter)MGLSampler_set_min_lod, 0, 0},
{"max_lod", 0, (setter)MGLSampler_set_max_lod, 0, 0},
{0},
};
PyType_Slot MGLSampler_slots[] = {
{Py_tp_methods, MGLSampler_methods},
{Py_tp_getset, MGLSampler_getset},
{0},
};
PyType_Spec MGLSampler_spec = {
mgl_ext ".Sampler",
sizeof(MGLSampler),
0,
Py_TPFLAGS_DEFAULT,
MGLSampler_slots,
};
<|endoftext|> |
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <unistd.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/wallclock.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-mdb/MDB.h"
#include "cm-common/CustomerNamespace.h"
#include "cm-logjoin/LogJoin.h"
using namespace fnord;
struct FeedChunkInfo {
uint64_t generation;
uint64_t generation_window;
uint64_t start_time;
uint64_t end_time;
HashMap<String, String> start_offsets;
template <typename T>
static void reflect(T* meta) {
meta->prop(&FeedChunkInfo::generation, 1, "generation", false);
meta->prop(&FeedChunkInfo::generation_window, 2, "generation_window", false);
meta->prop(&FeedChunkInfo::start_time, 3, "start_time", false);
meta->prop(&FeedChunkInfo::end_time, 4, "end_time", false);
meta->prop(&FeedChunkInfo::start_offsets, 5, "start_offsets", false);
};
};
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"output_path",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"output file path",
"<path>");
flags.defineFlag(
"output_prefix",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"output filename prefix",
"<prefix>");
flags.defineFlag(
"batch_size",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"2048",
"batch_size",
"<num>");
flags.defineFlag(
"buffer_size",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"8192",
"buffer_size",
"<num>");
flags.defineFlag(
"generation_window_secs",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"14400",
"generation_window_secs",
"<secs>");
flags.defineFlag(
"generation_delay_secs",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"3600",
"generation_delay_secs",
"<secs>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
/* start event loop */
fnord::thread::EventLoop ev;
auto evloop_thread = std::thread([&ev] {
ev.run();
});
/* set up rpc client */
HTTPRPCClient rpc_client(&ev);
auto output_path = flags.getString("output_path");
auto output_prefix = flags.getString("output_prefix");
size_t batch_size = flags.getInt("batch_size");
size_t buffer_size = flags.getInt("buffer_size");
size_t generation_window_micros =
flags.getInt("generation_window_secs") * kMicrosPerSecond;
size_t generation_delay_micros =
flags.getInt("generation_delay_secs") * kMicrosPerSecond;
FileUtil::mkdir_p(output_path);
HashMap<String, uint64_t> feed_offsets;
HashMap<uint64_t, std::unique_ptr<sstable::SSTableWriter>> generations;
Set<uint64_t> finished_generations;
uint64_t max_gen = 0;
/* check old sstables */
FileUtil::ls(output_path, [
output_path,
output_prefix,
&max_gen,
&feed_offsets,
&finished_generations] (const String& filename) -> bool {
if (!StringUtil::beginsWith(filename, output_prefix) ||
!StringUtil::endsWith(filename, ".sstable")) {
return true;
}
auto filepath = FileUtil::joinPaths(output_path, filename);
sstable::SSTableReader reader(
File::openFile(filepath, File::O_READ));
if (reader.bodySize() == 0) {
fnord::logWarning(
"fnord.feedexport",
"Deleting unfinished sstable $0",
filepath);
FileUtil::rm(filepath);
return true;
}
auto hdr = reader.readHeader();
auto fci = json::fromJSON<FeedChunkInfo>(hdr);
for (const auto& fo : fci.start_offsets) {
auto foff = std::stoul(fo.second);
if (feed_offsets[fo.first] < foff) {
feed_offsets[fo.first] = foff;
}
}
if (fci.generation > max_gen) {
max_gen = fci.generation;
}
finished_generations.emplace(fci.generation);
return true;
});
/* set up input feed reader */
feeds::RemoteFeedReader feed_reader(&rpc_client);
/* get source urls */
Vector<String> uris = flags.getArgv();
HashMap<String, String> feed_urls;
for (const auto& uri_raw : uris) {
URI uri(uri_raw);
const auto& params = uri.queryParams();
std::string feed;
if (!URI::getParam(params, "feed", &feed)) {
RAISEF(
kIllegalArgumentError,
"feed url missing ?feed query param: $0",
uri_raw);
}
feed_urls.emplace(feed, uri_raw.substr(0, uri_raw.find("?")));
uint64_t offset = feed_offsets[feed];
std::string offset_str;
if (URI::getParam(params, "offset", &offset_str)) {
if (offset_str == "HEAD") {
offset = std::numeric_limits<uint64_t>::max();
} else {
offset = std::stoul(offset_str);
}
}
feed_reader.addSourceFeed(
uri,
feed,
offset,
batch_size,
buffer_size);
}
uint64_t total_rows = 0;
uint64_t total_rows_written = 0;
uint64_t total_bytes = 0;
auto start_time = WallClock::now().unixMicros();
auto last_status_line = start_time;
DateTime last_iter;
uint64_t rate_limit_micros = 0.1 * kMicrosPerSecond;
for (;;) {
last_iter = WallClock::now();
feed_reader.fillBuffers();
/* read feed and build generations */
int i = 0;
for (; i < batch_size; ++i) {
auto entry = feed_reader.fetchNextEntry();
if (entry.isEmpty()) {
break;
}
++total_rows;
total_bytes += entry.get().data.size();
auto now = WallClock::now().unixMicros();
if (now - last_status_line > 10000) {
Set<uint64_t> active_gens;
for (const auto& g : generations) {
active_gens.emplace(g.first);
}
auto watermarks = feed_reader.watermarks();
auto runtime = (now - start_time) / 1000000;
uint64_t bandwidth = total_bytes / (runtime + 1);
auto str = StringUtil::format(
"\rrows=$0 bytes=$1B time=$2s bw=$3B/s active_gens=$4 streamtime=$5"
" ",
total_rows,
total_bytes,
runtime,
bandwidth,
inspect(active_gens),
watermarks.first);
write(0, str.c_str(), str.length());
fflush(0);
}
auto entry_time = entry.get().time.unixMicros();
if (entry_time == 0) {
continue;
}
uint64_t entry_gen = entry_time / generation_window_micros;
auto iter = generations.find(entry_gen);
if (iter == generations.end()) {
if (max_gen >= entry_gen) {
if (finished_generations.count(entry_gen) == 0) {
fnord::logWarning(
"fnord.feedexport",
"Dropping late data for generation #$0",
entry_gen);
}
continue;
}
fnord::logDebug(
"fnord.feedexport",
"Creating new generation #$0",
entry_gen);
FeedChunkInfo fci;
fci.generation = entry_gen;
fci.generation_window = generation_window_micros;
fci.start_time = entry_gen * generation_window_micros;
fci.end_time = (entry_gen + 1) * generation_window_micros;
auto stream_offsets = feed_reader.streamOffsets();
for (const auto& soff : stream_offsets) {
fci.start_offsets.emplace(
soff.first,
StringUtil::toString(soff.second));
}
auto fci_json = json::toJSONString(fci);
auto sstable_file_path = FileUtil::joinPaths(
output_path,
StringUtil::format("$0.$1.sstable", output_prefix, entry_gen));
auto sstable_writer = sstable::SSTableWriter::create(
sstable_file_path,
sstable::IndexProvider{},
fci_json.c_str(),
fci_json.length());
if (entry_gen > max_gen) {
max_gen = entry_gen;
}
generations.emplace(entry_gen, std::move(sstable_writer));
}
const auto& entry_data = entry.get().data;
generations[entry_gen]->appendRow(
(void *) &entry_time,
sizeof(entry_time),
entry_data.c_str(),
entry_data.length());
++total_rows_written;
}
feed_reader.fillBuffers();
/* flush generations */
auto watermarks = feed_reader.watermarks();
auto stream_time_micros = watermarks.first.unixMicros();
if (stream_time_micros > generation_delay_micros) {
stream_time_micros -= generation_delay_micros;
}
for (auto iter = generations.begin(); iter != generations.end(); ) {
if (stream_time_micros < ((iter->first + 1) * generation_window_micros)) {
++iter;
continue;
}
fnord::logDebug(
"cm.ctrstatsbuild",
"Flushing report generation #$0",
iter->first);
iter->second->finalize();
iter = generations.erase(iter);
}
auto etime = WallClock::now().unixMicros() - last_iter.unixMicros();
if (i < 1 && etime < rate_limit_micros) {
usleep(rate_limit_micros - etime);
}
}
evloop_thread.join();
return 0;
}
<commit_msg>allow for up to generation_delay / 2 secs spread<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <unistd.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/wallclock.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-mdb/MDB.h"
#include "cm-common/CustomerNamespace.h"
#include "cm-logjoin/LogJoin.h"
using namespace fnord;
struct FeedChunkInfo {
uint64_t generation;
uint64_t generation_window;
uint64_t start_time;
uint64_t end_time;
HashMap<String, String> start_offsets;
template <typename T>
static void reflect(T* meta) {
meta->prop(&FeedChunkInfo::generation, 1, "generation", false);
meta->prop(&FeedChunkInfo::generation_window, 2, "generation_window", false);
meta->prop(&FeedChunkInfo::start_time, 3, "start_time", false);
meta->prop(&FeedChunkInfo::end_time, 4, "end_time", false);
meta->prop(&FeedChunkInfo::start_offsets, 5, "start_offsets", false);
};
};
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"output_path",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"output file path",
"<path>");
flags.defineFlag(
"output_prefix",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"output filename prefix",
"<prefix>");
flags.defineFlag(
"batch_size",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"2048",
"batch_size",
"<num>");
flags.defineFlag(
"buffer_size",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"8192",
"buffer_size",
"<num>");
flags.defineFlag(
"generation_window_secs",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"14400",
"generation_window_secs",
"<secs>");
flags.defineFlag(
"generation_delay_secs",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"3600",
"generation_delay_secs",
"<secs>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
/* start event loop */
fnord::thread::EventLoop ev;
auto evloop_thread = std::thread([&ev] {
ev.run();
});
/* set up rpc client */
HTTPRPCClient rpc_client(&ev);
auto output_path = flags.getString("output_path");
auto output_prefix = flags.getString("output_prefix");
size_t batch_size = flags.getInt("batch_size");
size_t buffer_size = flags.getInt("buffer_size");
size_t generation_window_micros =
flags.getInt("generation_window_secs") * kMicrosPerSecond;
size_t generation_delay_micros =
flags.getInt("generation_delay_secs") * kMicrosPerSecond;
FileUtil::mkdir_p(output_path);
HashMap<String, uint64_t> feed_offsets;
HashMap<uint64_t, std::unique_ptr<sstable::SSTableWriter>> generations;
Set<uint64_t> finished_generations;
uint64_t max_gen = 0;
/* check old sstables */
FileUtil::ls(output_path, [
output_path,
output_prefix,
&max_gen,
&feed_offsets,
&finished_generations] (const String& filename) -> bool {
if (!StringUtil::beginsWith(filename, output_prefix) ||
!StringUtil::endsWith(filename, ".sstable")) {
return true;
}
auto filepath = FileUtil::joinPaths(output_path, filename);
sstable::SSTableReader reader(
File::openFile(filepath, File::O_READ));
if (reader.bodySize() == 0) {
fnord::logWarning(
"fnord.feedexport",
"Deleting unfinished sstable $0",
filepath);
FileUtil::rm(filepath);
return true;
}
auto hdr = reader.readHeader();
auto fci = json::fromJSON<FeedChunkInfo>(hdr);
for (const auto& fo : fci.start_offsets) {
auto foff = std::stoul(fo.second);
if (feed_offsets[fo.first] < foff) {
feed_offsets[fo.first] = foff;
}
}
if (fci.generation > max_gen) {
max_gen = fci.generation;
}
finished_generations.emplace(fci.generation);
return true;
});
/* set up input feed reader */
feeds::RemoteFeedReader feed_reader(&rpc_client);
feed_reader.setMaxSpread(generation_delay_micros / 2);
/* get source urls */
Vector<String> uris = flags.getArgv();
HashMap<String, String> feed_urls;
for (const auto& uri_raw : uris) {
URI uri(uri_raw);
const auto& params = uri.queryParams();
std::string feed;
if (!URI::getParam(params, "feed", &feed)) {
RAISEF(
kIllegalArgumentError,
"feed url missing ?feed query param: $0",
uri_raw);
}
feed_urls.emplace(feed, uri_raw.substr(0, uri_raw.find("?")));
uint64_t offset = feed_offsets[feed];
std::string offset_str;
if (URI::getParam(params, "offset", &offset_str)) {
if (offset_str == "HEAD") {
offset = std::numeric_limits<uint64_t>::max();
} else {
offset = std::stoul(offset_str);
}
}
feed_reader.addSourceFeed(
uri,
feed,
offset,
batch_size,
buffer_size);
}
uint64_t total_rows = 0;
uint64_t total_rows_written = 0;
uint64_t total_bytes = 0;
auto start_time = WallClock::now().unixMicros();
auto last_status_line = start_time;
DateTime last_iter;
uint64_t rate_limit_micros = 0.1 * kMicrosPerSecond;
for (;;) {
last_iter = WallClock::now();
feed_reader.fillBuffers();
/* read feed and build generations */
int i = 0;
for (; i < batch_size; ++i) {
auto entry = feed_reader.fetchNextEntry();
if (entry.isEmpty()) {
break;
}
++total_rows;
total_bytes += entry.get().data.size();
auto now = WallClock::now().unixMicros();
if (now - last_status_line > 10000) {
Set<uint64_t> active_gens;
for (const auto& g : generations) {
active_gens.emplace(g.first);
}
auto watermarks = feed_reader.watermarks();
auto runtime = (now - start_time) / 1000000;
uint64_t bandwidth = total_bytes / (runtime + 1);
auto str = StringUtil::format(
"\rrows=$0 bytes=$1B time=$2s bw=$3B/s active_gens=$4 streamtime=$5"
" ",
total_rows,
total_bytes,
runtime,
bandwidth,
inspect(active_gens),
watermarks.first);
write(0, str.c_str(), str.length());
fflush(0);
}
auto entry_time = entry.get().time.unixMicros();
if (entry_time == 0) {
continue;
}
uint64_t entry_gen = entry_time / generation_window_micros;
auto iter = generations.find(entry_gen);
if (iter == generations.end()) {
if (max_gen >= entry_gen) {
if (finished_generations.count(entry_gen) == 0) {
fnord::logWarning(
"fnord.feedexport",
"Dropping late data for generation #$0",
entry_gen);
}
continue;
}
fnord::logDebug(
"fnord.feedexport",
"Creating new generation #$0",
entry_gen);
FeedChunkInfo fci;
fci.generation = entry_gen;
fci.generation_window = generation_window_micros;
fci.start_time = entry_gen * generation_window_micros;
fci.end_time = (entry_gen + 1) * generation_window_micros;
auto stream_offsets = feed_reader.streamOffsets();
for (const auto& soff : stream_offsets) {
fci.start_offsets.emplace(
soff.first,
StringUtil::toString(soff.second));
}
auto fci_json = json::toJSONString(fci);
auto sstable_file_path = FileUtil::joinPaths(
output_path,
StringUtil::format("$0.$1.sstable", output_prefix, entry_gen));
auto sstable_writer = sstable::SSTableWriter::create(
sstable_file_path,
sstable::IndexProvider{},
fci_json.c_str(),
fci_json.length());
if (entry_gen > max_gen) {
max_gen = entry_gen;
}
generations.emplace(entry_gen, std::move(sstable_writer));
}
const auto& entry_data = entry.get().data;
generations[entry_gen]->appendRow(
(void *) &entry_time,
sizeof(entry_time),
entry_data.c_str(),
entry_data.length());
++total_rows_written;
}
feed_reader.fillBuffers();
/* flush generations */
auto watermarks = feed_reader.watermarks();
auto stream_time_micros = watermarks.first.unixMicros();
if (stream_time_micros > generation_delay_micros) {
stream_time_micros -= generation_delay_micros;
}
for (auto iter = generations.begin(); iter != generations.end(); ) {
if (stream_time_micros < ((iter->first + 1) * generation_window_micros)) {
++iter;
continue;
}
fnord::logDebug(
"cm.ctrstatsbuild",
"Flushing report generation #$0",
iter->first);
iter->second->finalize();
iter = generations.erase(iter);
}
auto etime = WallClock::now().unixMicros() - last_iter.unixMicros();
if (i < 1 && etime < rate_limit_micros) {
usleep(rate_limit_micros - etime);
}
}
evloop_thread.join();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/Random.h>
#include <array>
#include <mutex>
#include <random>
#include <folly/CppAttributes.h>
#include <folly/File.h>
#include <folly/FileUtil.h>
#include <folly/SingletonThreadLocal.h>
#include <folly/ThreadLocal.h>
#include <folly/detail/FileUtilDetail.h>
#include <folly/portability/Config.h>
#include <folly/portability/SysTime.h>
#include <folly/portability/Unistd.h>
#include <folly/synchronization/RelaxedAtomic.h>
#include <glog/logging.h>
#ifdef _MSC_VER
#include <wincrypt.h> // @manual
#endif
#if FOLLY_HAVE_GETRANDOM
#include <sys/random.h>
#endif
namespace folly {
namespace {
void readRandomDevice(void* data, size_t size) {
#ifdef _MSC_VER
static auto const cryptoProv = [] {
HCRYPTPROV prov;
if (!CryptAcquireContext(
&prov, nullptr, nullptr, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
if (GetLastError() == NTE_BAD_KEYSET) {
// Mostly likely cause of this is that no key container
// exists yet, so try to create one.
PCHECK(CryptAcquireContext(
&prov, nullptr, nullptr, PROV_RSA_FULL, CRYPT_NEWKEYSET));
} else {
LOG(FATAL) << "Failed to acquire the default crypto context.";
}
}
return prov;
}();
CHECK(size <= std::numeric_limits<DWORD>::max());
PCHECK(CryptGenRandom(cryptoProv, (DWORD)size, (BYTE*)data));
#else
ssize_t bytesRead = 0;
auto gen = [](int, void* buf, size_t buflen) {
#if FOLLY_HAVE_GETRANDOM
auto flags = 0u;
return ::getrandom(buf, buflen, flags);
#else
[](...) {}(buf, buflen);
errno = ENOSYS;
return -1;
#endif
};
bytesRead = fileutil_detail::wrapFull(gen, -1, data, size);
if (bytesRead == -1 && errno == ENOSYS) {
// Keep the random device open for the duration of the program.
static int randomFd = ::open("/dev/urandom", O_RDONLY | O_CLOEXEC);
PCHECK(randomFd >= 0);
bytesRead = readFull(randomFd, data, size);
}
PCHECK(bytesRead >= 0);
CHECK_EQ(size_t(bytesRead), size);
#endif
}
class BufferedRandomDevice {
public:
static constexpr size_t kDefaultBufferSize = 128;
static void notifyNewGlobalEpoch() { ++globalEpoch_; }
explicit BufferedRandomDevice(size_t bufferSize = kDefaultBufferSize);
void get(void* data, size_t size) {
if (LIKELY(epoch_ == globalEpoch_ && size <= remaining())) {
memcpy(data, ptr_, size);
ptr_ += size;
} else {
getSlow(static_cast<unsigned char*>(data), size);
}
}
private:
void getSlow(unsigned char* data, size_t size);
inline size_t remaining() const {
return size_t(buffer_.get() + bufferSize_ - ptr_);
}
static relaxed_atomic<size_t> globalEpoch_;
size_t epoch_{size_t(-1)}; // refill on first use
const size_t bufferSize_;
std::unique_ptr<unsigned char[]> buffer_;
unsigned char* ptr_;
};
relaxed_atomic<size_t> BufferedRandomDevice::globalEpoch_{0};
struct RandomTag {};
BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize)
: bufferSize_(bufferSize),
buffer_(new unsigned char[bufferSize]),
ptr_(buffer_.get() + bufferSize) { // refill on first use
FOLLY_MAYBE_UNUSED static auto const init = [] {
detail::AtFork::registerHandler(
nullptr,
/*prepare*/ []() { return true; },
/*parent*/ []() {},
/*child*/
[]() {
// Ensure child and parent do not share same entropy pool.
BufferedRandomDevice::notifyNewGlobalEpoch();
});
return 0;
}();
}
void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) {
if (epoch_ != globalEpoch_) {
epoch_ = globalEpoch_;
ptr_ = buffer_.get() + bufferSize_;
}
DCHECK_GT(size, remaining());
if (size >= bufferSize_) {
// Just read directly.
readRandomDevice(data, size);
return;
}
size_t copied = remaining();
memcpy(data, ptr_, copied);
data += copied;
size -= copied;
// refill
readRandomDevice(buffer_.get(), bufferSize_);
ptr_ = buffer_.get();
memcpy(data, ptr_, size);
ptr_ += size;
}
} // namespace
void Random::secureRandom(void* data, size_t size) {
using Single = SingletonThreadLocal<BufferedRandomDevice, RandomTag>;
Single::get().get(data, size);
}
ThreadLocalPRNG::result_type ThreadLocalPRNG::operator()() {
struct Wrapper {
Random::DefaultGenerator object{Random::create()};
};
using Single = SingletonThreadLocal<Wrapper, RandomTag>;
return Single::get().object();
}
} // namespace folly
<commit_msg>cut dep from Random onto File and FileUtil<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/Random.h>
#include <array>
#include <mutex>
#include <random>
#include <folly/CppAttributes.h>
#include <folly/SingletonThreadLocal.h>
#include <folly/ThreadLocal.h>
#include <folly/detail/FileUtilDetail.h>
#include <folly/portability/Config.h>
#include <folly/portability/SysTime.h>
#include <folly/portability/Unistd.h>
#include <folly/synchronization/RelaxedAtomic.h>
#include <glog/logging.h>
#ifdef _MSC_VER
#include <wincrypt.h> // @manual
#else
#include <fcntl.h>
#endif
#if FOLLY_HAVE_GETRANDOM
#include <sys/random.h>
#endif
namespace folly {
namespace {
void readRandomDevice(void* data, size_t size) {
#ifdef _MSC_VER
static auto const cryptoProv = [] {
HCRYPTPROV prov;
if (!CryptAcquireContext(
&prov, nullptr, nullptr, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
if (GetLastError() == NTE_BAD_KEYSET) {
// Mostly likely cause of this is that no key container
// exists yet, so try to create one.
PCHECK(CryptAcquireContext(
&prov, nullptr, nullptr, PROV_RSA_FULL, CRYPT_NEWKEYSET));
} else {
LOG(FATAL) << "Failed to acquire the default crypto context.";
}
}
return prov;
}();
CHECK(size <= std::numeric_limits<DWORD>::max());
PCHECK(CryptGenRandom(cryptoProv, (DWORD)size, (BYTE*)data));
#else
ssize_t bytesRead = 0;
auto gen = [](int, void* buf, size_t buflen) {
#if FOLLY_HAVE_GETRANDOM
auto flags = 0u;
return ::getrandom(buf, buflen, flags);
#else
[](...) {}(buf, buflen);
errno = ENOSYS;
return -1;
#endif
};
bytesRead = fileutil_detail::wrapFull(gen, -1, data, size);
if (bytesRead == -1 && errno == ENOSYS) {
// Keep the random device open for the duration of the program.
static int randomFd = ::open("/dev/urandom", O_RDONLY | O_CLOEXEC);
PCHECK(randomFd >= 0);
bytesRead = fileutil_detail::wrapFull(::read, randomFd, data, size);
}
PCHECK(bytesRead >= 0);
CHECK_EQ(size_t(bytesRead), size);
#endif
}
class BufferedRandomDevice {
public:
static constexpr size_t kDefaultBufferSize = 128;
static void notifyNewGlobalEpoch() { ++globalEpoch_; }
explicit BufferedRandomDevice(size_t bufferSize = kDefaultBufferSize);
void get(void* data, size_t size) {
if (LIKELY(epoch_ == globalEpoch_ && size <= remaining())) {
memcpy(data, ptr_, size);
ptr_ += size;
} else {
getSlow(static_cast<unsigned char*>(data), size);
}
}
private:
void getSlow(unsigned char* data, size_t size);
inline size_t remaining() const {
return size_t(buffer_.get() + bufferSize_ - ptr_);
}
static relaxed_atomic<size_t> globalEpoch_;
size_t epoch_{size_t(-1)}; // refill on first use
const size_t bufferSize_;
std::unique_ptr<unsigned char[]> buffer_;
unsigned char* ptr_;
};
relaxed_atomic<size_t> BufferedRandomDevice::globalEpoch_{0};
struct RandomTag {};
BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize)
: bufferSize_(bufferSize),
buffer_(new unsigned char[bufferSize]),
ptr_(buffer_.get() + bufferSize) { // refill on first use
FOLLY_MAYBE_UNUSED static auto const init = [] {
detail::AtFork::registerHandler(
nullptr,
/*prepare*/ []() { return true; },
/*parent*/ []() {},
/*child*/
[]() {
// Ensure child and parent do not share same entropy pool.
BufferedRandomDevice::notifyNewGlobalEpoch();
});
return 0;
}();
}
void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) {
if (epoch_ != globalEpoch_) {
epoch_ = globalEpoch_;
ptr_ = buffer_.get() + bufferSize_;
}
DCHECK_GT(size, remaining());
if (size >= bufferSize_) {
// Just read directly.
readRandomDevice(data, size);
return;
}
size_t copied = remaining();
memcpy(data, ptr_, copied);
data += copied;
size -= copied;
// refill
readRandomDevice(buffer_.get(), bufferSize_);
ptr_ = buffer_.get();
memcpy(data, ptr_, size);
ptr_ += size;
}
} // namespace
void Random::secureRandom(void* data, size_t size) {
using Single = SingletonThreadLocal<BufferedRandomDevice, RandomTag>;
Single::get().get(data, size);
}
ThreadLocalPRNG::result_type ThreadLocalPRNG::operator()() {
struct Wrapper {
Random::DefaultGenerator object{Random::create()};
};
using Single = SingletonThreadLocal<Wrapper, RandomTag>;
return Single::get().object();
}
} // namespace folly
<|endoftext|> |
<commit_before><commit_msg>also backport 1.881 for vertical scrolling of checkboxes, thanks Sandro.<commit_after><|endoftext|> |
<commit_before><commit_msg>Enable completion for the reply-to field.<commit_after><|endoftext|> |
<commit_before>/*
Kopete Yahoo Protocol
Notifies about incoming filetransfers
Copyright (c) 2006 André Duffeck <andre.duffeck@kdemail.net>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "filetransfernotifiertask.h"
#include "transfer.h"
#include "ymsgtransfer.h"
#include "yahootypes.h"
#include "client.h"
#include <qstring.h>
#include <kdebug.h>
FileTransferNotifierTask::FileTransferNotifierTask(Task* parent) : Task(parent)
{
kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
}
FileTransferNotifierTask::~FileTransferNotifierTask()
{
}
bool FileTransferNotifierTask::take( Transfer* transfer )
{
kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
if ( !forMe( transfer ) )
return false;
YMSGTransfer *t = static_cast<YMSGTransfer*>(transfer);
if( t->service() == Yahoo::ServiceFileTransfer )
parseFileTransfer( t );
else if( t->service() == Yahoo::ServiceFileTransfer7 )
parseFileTransfer7( t );
else if( t->service() == Yahoo::ServicePeerToPeer )
acceptFileTransfer( t );
return true;
}
bool FileTransferNotifierTask::forMe( Transfer *transfer ) const
{
kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
YMSGTransfer *t = 0L;
t = dynamic_cast<YMSGTransfer*>(transfer);
if (!t)
return false;
if( t->service() == Yahoo::ServiceP2PFileXfer ||
t->service() == Yahoo::ServicePeerToPeer ||
t->service() == Yahoo::ServiceFileTransfer ||
t->service() == Yahoo::ServiceFileTransfer7
)
return true;
else
return false;
}
void FileTransferNotifierTask::parseFileTransfer( YMSGTransfer *t )
{
kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
QString from; /* key = 4 */
QString to; /* key = 5 */
QString url; /* key = 20 */
long expires; /* key = 38 */
QString msg; /* key = 14 */
QString filename; /* key = 27 */
unsigned long size; /* key = 28 */
from = t->firstParam( 4 );
to = t->firstParam( 5 );
url = t->firstParam( 20 );
expires = t->firstParam( 38 ).toLong();
msg = t->firstParam( 14 );
filename = t->firstParam( 27 );
size = t->firstParam( 28 ).toULong();
if( from.startsWith( "FILE_TRANSFER_SYSTEM" ) )
{
client()->notifyError( "Fileupload result received.", msg, Client::Notice );
}
if( url.isEmpty() )
return;
unsigned int left = url.findRev( '/' ) + 1;
unsigned int right = url.findRev( '?' );
filename = url.mid( left, right - left );
emit incomingFileTransfer( from, url, expires, msg, filename, size );
}
void FileTransferNotifierTask::parseFileTransfer7( YMSGTransfer *t )
{
kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
QString from; /* key = 4 */
QString to; /* key = 5 */
QString url; /* key = 20 */
long expires; /* key = 38 */
QString msg; /* key = 14 */
QString filename; /* key = 27 */
unsigned long size; /* key = 28 */
if( t->firstParam( 222 ).toInt() == 2 )
return; // user cancelled the file transfer
from = t->firstParam( 4 );
to = t->firstParam( 5 );
url = t->firstParam( 265 );
msg = t->firstParam( 14 );
filename = t->firstParam( 27 );
size = t->firstParam( 28 ).toULong();
emit incomingFileTransfer( from, url, expires, msg, filename, size );
}
void FileTransferNotifierTask::acceptFileTransfer( YMSGTransfer *transfer )
{
kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
YMSGTransfer *t = new YMSGTransfer(Yahoo::ServicePeerToPeer);
t->setId( client()->sessionID() );
t->setParam( 4, client()->userId().local8Bit() );
t->setParam( 5, transfer->firstParam( 4 ) );
t->setParam( 11, transfer->firstParam( 11 ) );
send( t );
}
#include "filetransfernotifiertask.moc"
<commit_msg>return in case of a fileupload result<commit_after>/*
Kopete Yahoo Protocol
Notifies about incoming filetransfers
Copyright (c) 2006 André Duffeck <andre.duffeck@kdemail.net>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "filetransfernotifiertask.h"
#include "transfer.h"
#include "ymsgtransfer.h"
#include "yahootypes.h"
#include "client.h"
#include <qstring.h>
#include <kdebug.h>
FileTransferNotifierTask::FileTransferNotifierTask(Task* parent) : Task(parent)
{
kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
}
FileTransferNotifierTask::~FileTransferNotifierTask()
{
}
bool FileTransferNotifierTask::take( Transfer* transfer )
{
kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
if ( !forMe( transfer ) )
return false;
YMSGTransfer *t = static_cast<YMSGTransfer*>(transfer);
if( t->service() == Yahoo::ServiceFileTransfer )
parseFileTransfer( t );
else if( t->service() == Yahoo::ServiceFileTransfer7 )
parseFileTransfer7( t );
else if( t->service() == Yahoo::ServicePeerToPeer )
acceptFileTransfer( t );
return true;
}
bool FileTransferNotifierTask::forMe( Transfer *transfer ) const
{
kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
YMSGTransfer *t = 0L;
t = dynamic_cast<YMSGTransfer*>(transfer);
if (!t)
return false;
if( t->service() == Yahoo::ServiceP2PFileXfer ||
t->service() == Yahoo::ServicePeerToPeer ||
t->service() == Yahoo::ServiceFileTransfer ||
t->service() == Yahoo::ServiceFileTransfer7
)
return true;
else
return false;
}
void FileTransferNotifierTask::parseFileTransfer( YMSGTransfer *t )
{
kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
QString from; /* key = 4 */
QString to; /* key = 5 */
QString url; /* key = 20 */
long expires; /* key = 38 */
QString msg; /* key = 14 */
QString filename; /* key = 27 */
unsigned long size; /* key = 28 */
from = t->firstParam( 4 );
to = t->firstParam( 5 );
url = t->firstParam( 20 );
expires = t->firstParam( 38 ).toLong();
msg = t->firstParam( 14 );
filename = t->firstParam( 27 );
size = t->firstParam( 28 ).toULong();
if( from.startsWith( "FILE_TRANSFER_SYSTEM" ) )
{
client()->notifyError( "Fileupload result received.", msg, Client::Notice );
return;
}
if( url.isEmpty() )
return;
unsigned int left = url.findRev( '/' ) + 1;
unsigned int right = url.findRev( '?' );
filename = url.mid( left, right - left );
emit incomingFileTransfer( from, url, expires, msg, filename, size );
}
void FileTransferNotifierTask::parseFileTransfer7( YMSGTransfer *t )
{
kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
QString from; /* key = 4 */
QString to; /* key = 5 */
QString url; /* key = 20 */
long expires; /* key = 38 */
QString msg; /* key = 14 */
QString filename; /* key = 27 */
unsigned long size; /* key = 28 */
if( t->firstParam( 222 ).toInt() == 2 )
return; // user cancelled the file transfer
from = t->firstParam( 4 );
to = t->firstParam( 5 );
url = t->firstParam( 265 );
msg = t->firstParam( 14 );
filename = t->firstParam( 27 );
size = t->firstParam( 28 ).toULong();
emit incomingFileTransfer( from, url, expires, msg, filename, size );
}
void FileTransferNotifierTask::acceptFileTransfer( YMSGTransfer *transfer )
{
kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
YMSGTransfer *t = new YMSGTransfer(Yahoo::ServicePeerToPeer);
t->setId( client()->sessionID() );
t->setParam( 4, client()->userId().local8Bit() );
t->setParam( 5, transfer->firstParam( 4 ) );
t->setParam( 11, transfer->firstParam( 11 ) );
send( t );
}
#include "filetransfernotifiertask.moc"
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreSTBICodec.h"
#include "OgreLogManager.h"
#include "OgreDataStream.h"
#include "OgrePlatformInformation.h"
#if __OGRE_HAVE_NEON
#define STBI_NEON
#endif
#define STBI_NO_STDIO
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_STATIC
#include "stbi/stb_image.h"
#if OGRE_NO_ZIP_ARCHIVE == 0
#include <zlib.h>
static Ogre::uchar* custom_zlib_compress(Ogre::uchar* data, int data_len, int* out_len, int /*quality*/)
{
unsigned long destLen = compressBound(data_len);
Ogre::uchar* dest = (Ogre::uchar*)malloc(destLen);
int ret = compress(dest, &destLen, data, data_len); // use default quality
if (ret != Z_OK)
{
free(dest);
OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, "compress failed");
}
*out_len = destLen;
return dest;
}
#define STBIW_ZLIB_COMPRESS custom_zlib_compress
#endif
#define STB_IMAGE_WRITE_IMPLEMENTATION
#define STBI_WRITE_NO_STDIO
#include "stbi/stb_image_write.h"
namespace Ogre {
STBIImageCodec::RegisteredCodecList STBIImageCodec::msCodecList;
//---------------------------------------------------------------------
void STBIImageCodec::startup(void)
{
stbi_convert_iphone_png_to_rgb(1);
stbi_set_unpremultiply_on_load(1);
LogManager::getSingleton().logMessage("stb_image - v2.23 - public domain image loader");
// Register codecs
String exts = "jpeg,jpg,png,bmp,psd,tga,gif,pic,ppm,pgm,hdr";
StringVector extsVector = StringUtil::split(exts, ",");
for (StringVector::iterator v = extsVector.begin(); v != extsVector.end(); ++v)
{
ImageCodec* codec = OGRE_NEW STBIImageCodec(*v);
msCodecList.push_back(codec);
Codec::registerCodec(codec);
}
LogManager::getSingleton().logMessage("Supported formats: " + exts);
}
//---------------------------------------------------------------------
void STBIImageCodec::shutdown(void)
{
for (RegisteredCodecList::iterator i = msCodecList.begin();
i != msCodecList.end(); ++i)
{
Codec::unregisterCodec(*i);
OGRE_DELETE *i;
}
msCodecList.clear();
}
//---------------------------------------------------------------------
STBIImageCodec::STBIImageCodec(const String &type):
mType(type)
{
}
//---------------------------------------------------------------------
DataStreamPtr STBIImageCodec::encode(const MemoryDataStreamPtr& input,
const Codec::CodecDataPtr& pData) const
{
if(mType != "png") {
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"currently only encoding to PNG supported",
"STBIImageCodec::encode" ) ;
}
ImageData* pImgData = static_cast<ImageData*>(pData.get());
PixelFormat format = pImgData->format;
uchar* inputData = input->getPtr();
// Convert image data to ABGR format for STBI (unless it's already compatible)
uchar* tempData = 0;
if(format != Ogre::PF_A8B8G8R8 && format != PF_B8G8R8 && format != PF_BYTE_LA &&
format != PF_L8 && format != PF_R8)
{
format = Ogre::PF_A8B8G8R8;
size_t tempDataSize = pImgData->width * pImgData->height * pImgData->depth * Ogre::PixelUtil::getNumElemBytes(format);
tempData = OGRE_ALLOC_T(unsigned char, tempDataSize, Ogre::MEMCATEGORY_GENERAL);
Ogre::PixelBox pbIn(pImgData->width, pImgData->height, pImgData->depth, pImgData->format, inputData);
Ogre::PixelBox pbOut(pImgData->width, pImgData->height, pImgData->depth, format, tempData);
PixelUtil::bulkPixelConversion(pbIn, pbOut);
inputData = tempData;
}
// Save to PNG
int channels = (int)PixelUtil::getComponentCount(format);
int stride = pImgData->width * (int)PixelUtil::getNumElemBytes(format);
int len;
uchar* data = stbi_write_png_to_mem(inputData, stride, pImgData->width, pImgData->height, channels, &len);
if(tempData)
{
OGRE_FREE(tempData, MEMCATEGORY_GENERAL);
}
if (!data) {
OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
"Error encoding image: " + String(stbi_failure_reason()),
"STBIImageCodec::encode");
}
return DataStreamPtr(new MemoryDataStream(data, len, true));
}
//---------------------------------------------------------------------
void STBIImageCodec::encodeToFile(const MemoryDataStreamPtr& input, const String& outFileName,
const Codec::CodecDataPtr& pData) const
{
#if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN
MemoryDataStreamPtr data = static_pointer_cast<MemoryDataStream>(encode(input, pData));
std::ofstream f(outFileName.c_str(), std::ios::out | std::ios::binary);
if(!f.is_open()) {
OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
"could not open file",
"STBIImageCodec::encodeToFile" ) ;
}
f.write((char*)data->getPtr(), data->size());
#endif
}
//---------------------------------------------------------------------
Codec::DecodeResult STBIImageCodec::decode(const DataStreamPtr& input) const
{
String contents = input->getAsString();
int width, height, components;
stbi_uc* pixelData = stbi_load_from_memory((const uchar*)contents.data(),
static_cast<int>(contents.size()), &width, &height, &components, 0);
if (!pixelData)
{
OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
"Error decoding image: " + String(stbi_failure_reason()),
"STBIImageCodec::decode");
}
SharedPtr<ImageData> imgData(OGRE_NEW ImageData());
imgData->depth = 1; // only 2D formats handled by this codec
imgData->width = width;
imgData->height = height;
imgData->num_mipmaps = 0; // no mipmaps in non-DDS
imgData->flags = 0;
switch( components )
{
case 1:
imgData->format = PF_BYTE_L;
break;
case 2:
imgData->format = PF_BYTE_LA;
break;
case 3:
imgData->format = PF_BYTE_RGB;
break;
case 4:
imgData->format = PF_BYTE_RGBA;
break;
default:
stbi_image_free(pixelData);
OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,
"Unknown or unsupported image format",
"STBIImageCodec::decode");
break;
}
size_t dstPitch = imgData->width * PixelUtil::getNumElemBytes(imgData->format);
imgData->size = dstPitch * imgData->height;
MemoryDataStreamPtr output(OGRE_NEW MemoryDataStream(pixelData, imgData->size, true));
DecodeResult ret;
ret.first = output;
ret.second = imgData;
return ret;
}
//---------------------------------------------------------------------
String STBIImageCodec::getType() const
{
return mType;
}
//---------------------------------------------------------------------
String STBIImageCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const
{
return BLANKSTRING;
}
const String& STBIPlugin::getName() const {
static String name = "STB Image Codec";
return name;
}
#ifndef OGRE_STATIC_LIB
extern "C" void _OgreSTBICodecExport dllStartPlugin();
extern "C" void _OgreSTBICodecExport dllStopPlugin();
extern "C" void _OgreSTBICodecExport dllStartPlugin()
{
STBIImageCodec::startup();
}
extern "C" void _OgreSTBICodecExport dllStopPlugin()
{
STBIImageCodec::shutdown();
}
#endif
}
<commit_msg>STBICodec: encodeToFile - improve error message<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreSTBICodec.h"
#include "OgreLogManager.h"
#include "OgreDataStream.h"
#include "OgrePlatformInformation.h"
#if __OGRE_HAVE_NEON
#define STBI_NEON
#endif
#define STBI_NO_STDIO
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_STATIC
#include "stbi/stb_image.h"
#if OGRE_NO_ZIP_ARCHIVE == 0
#include <zlib.h>
static Ogre::uchar* custom_zlib_compress(Ogre::uchar* data, int data_len, int* out_len, int /*quality*/)
{
unsigned long destLen = compressBound(data_len);
Ogre::uchar* dest = (Ogre::uchar*)malloc(destLen);
int ret = compress(dest, &destLen, data, data_len); // use default quality
if (ret != Z_OK)
{
free(dest);
OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, "compress failed");
}
*out_len = destLen;
return dest;
}
#define STBIW_ZLIB_COMPRESS custom_zlib_compress
#endif
#define STB_IMAGE_WRITE_IMPLEMENTATION
#define STBI_WRITE_NO_STDIO
#include "stbi/stb_image_write.h"
namespace Ogre {
STBIImageCodec::RegisteredCodecList STBIImageCodec::msCodecList;
//---------------------------------------------------------------------
void STBIImageCodec::startup(void)
{
stbi_convert_iphone_png_to_rgb(1);
stbi_set_unpremultiply_on_load(1);
LogManager::getSingleton().logMessage("stb_image - v2.23 - public domain image loader");
// Register codecs
String exts = "jpeg,jpg,png,bmp,psd,tga,gif,pic,ppm,pgm,hdr";
StringVector extsVector = StringUtil::split(exts, ",");
for (StringVector::iterator v = extsVector.begin(); v != extsVector.end(); ++v)
{
ImageCodec* codec = OGRE_NEW STBIImageCodec(*v);
msCodecList.push_back(codec);
Codec::registerCodec(codec);
}
LogManager::getSingleton().logMessage("Supported formats: " + exts);
}
//---------------------------------------------------------------------
void STBIImageCodec::shutdown(void)
{
for (RegisteredCodecList::iterator i = msCodecList.begin();
i != msCodecList.end(); ++i)
{
Codec::unregisterCodec(*i);
OGRE_DELETE *i;
}
msCodecList.clear();
}
//---------------------------------------------------------------------
STBIImageCodec::STBIImageCodec(const String &type):
mType(type)
{
}
//---------------------------------------------------------------------
DataStreamPtr STBIImageCodec::encode(const MemoryDataStreamPtr& input,
const Codec::CodecDataPtr& pData) const
{
if(mType != "png") {
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"currently only encoding to PNG supported",
"STBIImageCodec::encode" ) ;
}
ImageData* pImgData = static_cast<ImageData*>(pData.get());
PixelFormat format = pImgData->format;
uchar* inputData = input->getPtr();
// Convert image data to ABGR format for STBI (unless it's already compatible)
uchar* tempData = 0;
if(format != Ogre::PF_A8B8G8R8 && format != PF_B8G8R8 && format != PF_BYTE_LA &&
format != PF_L8 && format != PF_R8)
{
format = Ogre::PF_A8B8G8R8;
size_t tempDataSize = pImgData->width * pImgData->height * pImgData->depth * Ogre::PixelUtil::getNumElemBytes(format);
tempData = OGRE_ALLOC_T(unsigned char, tempDataSize, Ogre::MEMCATEGORY_GENERAL);
Ogre::PixelBox pbIn(pImgData->width, pImgData->height, pImgData->depth, pImgData->format, inputData);
Ogre::PixelBox pbOut(pImgData->width, pImgData->height, pImgData->depth, format, tempData);
PixelUtil::bulkPixelConversion(pbIn, pbOut);
inputData = tempData;
}
// Save to PNG
int channels = (int)PixelUtil::getComponentCount(format);
int stride = pImgData->width * (int)PixelUtil::getNumElemBytes(format);
int len;
uchar* data = stbi_write_png_to_mem(inputData, stride, pImgData->width, pImgData->height, channels, &len);
if(tempData)
{
OGRE_FREE(tempData, MEMCATEGORY_GENERAL);
}
if (!data) {
OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
"Error encoding image: " + String(stbi_failure_reason()),
"STBIImageCodec::encode");
}
return DataStreamPtr(new MemoryDataStream(data, len, true));
}
//---------------------------------------------------------------------
void STBIImageCodec::encodeToFile(const MemoryDataStreamPtr& input, const String& outFileName,
const Codec::CodecDataPtr& pData) const
{
#if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN
MemoryDataStreamPtr data = static_pointer_cast<MemoryDataStream>(encode(input, pData));
std::ofstream f(outFileName.c_str(), std::ios::out | std::ios::binary);
if (!f.is_open())
{
OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "could not open file " + outFileName);
}
f.write((char*)data->getPtr(), data->size());
#endif
}
//---------------------------------------------------------------------
Codec::DecodeResult STBIImageCodec::decode(const DataStreamPtr& input) const
{
String contents = input->getAsString();
int width, height, components;
stbi_uc* pixelData = stbi_load_from_memory((const uchar*)contents.data(),
static_cast<int>(contents.size()), &width, &height, &components, 0);
if (!pixelData)
{
OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
"Error decoding image: " + String(stbi_failure_reason()),
"STBIImageCodec::decode");
}
SharedPtr<ImageData> imgData(OGRE_NEW ImageData());
imgData->depth = 1; // only 2D formats handled by this codec
imgData->width = width;
imgData->height = height;
imgData->num_mipmaps = 0; // no mipmaps in non-DDS
imgData->flags = 0;
switch( components )
{
case 1:
imgData->format = PF_BYTE_L;
break;
case 2:
imgData->format = PF_BYTE_LA;
break;
case 3:
imgData->format = PF_BYTE_RGB;
break;
case 4:
imgData->format = PF_BYTE_RGBA;
break;
default:
stbi_image_free(pixelData);
OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,
"Unknown or unsupported image format",
"STBIImageCodec::decode");
break;
}
size_t dstPitch = imgData->width * PixelUtil::getNumElemBytes(imgData->format);
imgData->size = dstPitch * imgData->height;
MemoryDataStreamPtr output(OGRE_NEW MemoryDataStream(pixelData, imgData->size, true));
DecodeResult ret;
ret.first = output;
ret.second = imgData;
return ret;
}
//---------------------------------------------------------------------
String STBIImageCodec::getType() const
{
return mType;
}
//---------------------------------------------------------------------
String STBIImageCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const
{
return BLANKSTRING;
}
const String& STBIPlugin::getName() const {
static String name = "STB Image Codec";
return name;
}
#ifndef OGRE_STATIC_LIB
extern "C" void _OgreSTBICodecExport dllStartPlugin();
extern "C" void _OgreSTBICodecExport dllStopPlugin();
extern "C" void _OgreSTBICodecExport dllStartPlugin()
{
STBIImageCodec::startup();
}
extern "C" void _OgreSTBICodecExport dllStopPlugin()
{
STBIImageCodec::shutdown();
}
#endif
}
<|endoftext|> |
<commit_before>#include "cubeb/cubeb.h"
#include <atomic>
#include <cassert>
#include <cmath>
#include <cstdarg>
#include <cstring>
#include <iostream>
#ifdef _WIN32
#include <objbase.h> // Used by CoInitialize()
#endif
#ifndef M_PI
#define M_PI 3.14159263
#endif
// Default values if none specified
#define DEFAULT_RATE 44100
#define DEFAULT_CHANNELS 2
static const char* state_to_string(cubeb_state state) {
switch (state) {
case CUBEB_STATE_STARTED:
return "CUBEB_STATE_STARTED";
case CUBEB_STATE_STOPPED:
return "CUBEB_STATE_STOPPED";
case CUBEB_STATE_DRAINED:
return "CUBEB_STATE_DRAINED";
case CUBEB_STATE_ERROR:
return "CUBEB_STATE_ERROR";
default:
return "Undefined state";
}
}
void print_log(const char* msg, ...) {
va_list args;
va_start(args, msg);
vprintf(msg, args);
va_end(args);
}
class cubeb_client final {
public:
cubeb_client() {}
~cubeb_client() {}
bool init(char const * backend_name = nullptr);
bool init_stream();
bool start_stream() const;
bool stop_stream() const;
bool destroy_stream() const;
bool destroy();
bool activate_log(bool active);
long user_data_cb(cubeb_stream* stm, void* user, const void* input_buffer,
void* output_buffer, long nframes);
void user_state_cb(cubeb_stream* stm, void* user, cubeb_state state);
bool register_device_collection_changed(cubeb_device_type devtype);
void device_collection_changed_callback(cubeb* context, void* user);
cubeb_stream_params output_params = {};
cubeb_stream_params input_params = {};
private:
bool has_input() { return input_params.rate != 0; }
bool has_output() { return output_params.rate != 0; }
cubeb* context = nullptr;
cubeb_stream* stream = nullptr;
cubeb_devid output_device = nullptr;
cubeb_devid input_device = nullptr;
/* Accessed only from client and audio thread. */
std::atomic<uint32_t> _rate = {0};
std::atomic<uint32_t> _channels = {0};
/* Accessed only from audio thread. */
uint32_t _total_frames = 0;
};
bool cubeb_client::init(char const * backend_name) {
int rv = cubeb_init(&context, "Cubeb Test Application", nullptr);
if (rv != CUBEB_OK) {
fprintf(stderr, "Could not init cubeb\n");
return false;
}
return true;
}
static long user_data_cb_s(cubeb_stream* stm, void* user,
const void* input_buffer, void* output_buffer,
long nframes) {
assert(user);
return static_cast<cubeb_client*>(user)->user_data_cb(stm, user, input_buffer,
output_buffer, nframes);
}
static void user_state_cb_s(cubeb_stream* stm, void* user, cubeb_state state) {
assert(user);
return static_cast<cubeb_client*>(user)->user_state_cb(stm, user, state);
}
void device_collection_changed_callback_s(cubeb* context, void* user) {
assert(user);
return static_cast<cubeb_client*>(user)->device_collection_changed_callback(
context, user);
}
bool cubeb_client::init_stream() {
assert(has_input() || has_output());
_rate = has_output() ? output_params.rate : input_params.rate;
_channels = has_output() ? output_params.channels : input_params.channels;
int rv =
cubeb_stream_init(context, &stream, "Stream", input_device,
has_input() ? &input_params : nullptr, output_device,
has_output() ? &output_params : nullptr, 512,
user_data_cb_s, user_state_cb_s, this);
if (rv != CUBEB_OK) {
fprintf(stderr, "Could not open the stream\n");
return false;
}
return true;
}
bool cubeb_client::start_stream() const {
int rv = cubeb_stream_start(stream);
if (rv != CUBEB_OK) {
fprintf(stderr, "Could not start the stream\n");
return false;
}
return true;
}
bool cubeb_client::stop_stream() const {
int rv = cubeb_stream_stop(stream);
if (rv != CUBEB_OK) {
fprintf(stderr, "Could not stop the stream\n");
return false;
}
return true;
}
bool cubeb_client::destroy_stream() const {
cubeb_stream_destroy(stream);
return true;
}
bool cubeb_client::destroy() {
cubeb_destroy(context);
return true;
}
bool cubeb_client::activate_log(bool active) {
cubeb_log_level log_level = CUBEB_LOG_DISABLED;
cubeb_log_callback log_callback = nullptr;
if (active) {
log_level = CUBEB_LOG_NORMAL;
log_callback = print_log;
}
if (cubeb_set_log_callback(log_level, log_callback) != CUBEB_OK) {
fprintf(stderr, "Set log callback failed\n");
return false;
}
return true;
}
static void fill_with_sine_tone(float* buf, uint32_t num_of_frames,
uint32_t num_of_channels, uint32_t frame_rate,
uint32_t position) {
for (uint32_t i = 0; i < num_of_frames; ++i) {
for (uint32_t c = 0; c < num_of_channels; ++c) {
buf[i * num_of_channels + c] =
0.2 * sin(2 * M_PI * (i + position) * 350 / frame_rate);
buf[i * num_of_channels + c] +=
0.2 * sin(2 * M_PI * (i + position) * 440 / frame_rate);
}
}
}
long cubeb_client::user_data_cb(cubeb_stream* stm, void* user,
const void* input_buffer, void* output_buffer,
long nframes) {
if (input_buffer && output_buffer) {
const float* in = static_cast<const float*>(input_buffer);
float* out = static_cast<float*>(output_buffer);
memcpy(out, in, sizeof(float) * nframes * _channels);
} else if (output_buffer && !input_buffer) {
fill_with_sine_tone(static_cast<float*>(output_buffer), nframes, _channels,
_rate, _total_frames);
}
_total_frames += nframes;
return nframes;
}
void cubeb_client::user_state_cb(cubeb_stream* stm, void* user,
cubeb_state state) {
fprintf(stderr, "state is %s\n", state_to_string(state));
}
bool cubeb_client::register_device_collection_changed(
cubeb_device_type devtype) {
int r = 0;
r = cubeb_register_device_collection_changed(
context, devtype, device_collection_changed_callback_s, this);
if (r != CUBEB_OK) {
return false;
}
return true;
}
void cubeb_client::device_collection_changed_callback(cubeb* context,
void* user) {
fprintf(stderr, "device_collection_changed_callback\n");
}
enum play_mode {
RECORD,
PLAYBACK,
DUPLEX,
COLLECTION_CHANGE,
};
bool choose_action(const cubeb_client& cl, play_mode pm, char c) {
while (c == 10 || c == 32) {
// Consume "enter and "space"
c = getchar();
}
if (c == 's') {
if (pm == PLAYBACK || pm == RECORD || pm == DUPLEX) {
cl.stop_stream();
cl.destroy_stream();
}
return false;
}
fprintf(stderr, "Error: %c is not a valid entry\n", c);
return true;
}
int main(int argc, char* argv[]) {
#ifdef _WIN32
CoInitialize(nullptr);
#endif
play_mode pm = DUPLEX;
if (argc > 1) {
if ('r' == argv[1][0]) {
pm = RECORD;
} else if ('p' == argv[1][0]) {
pm = PLAYBACK;
} else if ('d' == argv[1][0]) {
pm = DUPLEX;
} else if ('c' == argv[1][0]) {
pm = COLLECTION_CHANGE;
}
}
uint32_t rate = DEFAULT_RATE;
if (argc > 2) {
rate = strtoul(argv[2], NULL, 0);
}
bool res = false;
cubeb_client cl;
cl.activate_log(true);
cl.init();
if (pm == COLLECTION_CHANGE) {
res = cl.register_device_collection_changed(static_cast<cubeb_device_type>(
CUBEB_DEVICE_TYPE_INPUT & CUBEB_DEVICE_TYPE_INPUT));
if (res) {
fprintf(stderr,
"register_device_collection_changed for input+output devices "
"success\n");
} else {
fprintf(stderr, "register_device_collection_changed failed\n");
}
} else {
if (pm == PLAYBACK || pm == DUPLEX) {
cl.output_params = {CUBEB_SAMPLE_FLOAT32NE, rate, DEFAULT_CHANNELS,
CUBEB_LAYOUT_UNDEFINED, CUBEB_STREAM_PREF_NONE};
}
if (pm == RECORD || pm == DUPLEX) {
cl.input_params = {CUBEB_SAMPLE_FLOAT32NE, rate, DEFAULT_CHANNELS,
CUBEB_LAYOUT_UNDEFINED, CUBEB_STREAM_PREF_NONE};
}
res = cl.init_stream();
if (!res) {
return 1;
}
cl.start_stream();
}
// User input
do {
fprintf(stderr, "press `s` to stop the stream (if any) and abort\n");
} while (choose_action(cl, pm, getchar()));
cl.destroy();
return 0;
}
<commit_msg>cubeb-test: improvements for testing collection changed callback (#489)<commit_after>#include "cubeb/cubeb.h"
#include <atomic>
#include <cassert>
#include <cmath>
#include <cstdarg>
#include <cstring>
#include <iostream>
#ifdef _WIN32
#include <objbase.h> // Used by CoInitialize()
#endif
#ifndef M_PI
#define M_PI 3.14159263
#endif
// Default values if none specified
#define DEFAULT_RATE 44100
#define DEFAULT_CHANNELS 2
static const char* state_to_string(cubeb_state state) {
switch (state) {
case CUBEB_STATE_STARTED:
return "CUBEB_STATE_STARTED";
case CUBEB_STATE_STOPPED:
return "CUBEB_STATE_STOPPED";
case CUBEB_STATE_DRAINED:
return "CUBEB_STATE_DRAINED";
case CUBEB_STATE_ERROR:
return "CUBEB_STATE_ERROR";
default:
return "Undefined state";
}
}
void print_log(const char* msg, ...) {
va_list args;
va_start(args, msg);
vprintf(msg, args);
va_end(args);
}
class cubeb_client final {
public:
cubeb_client() {}
~cubeb_client() {}
bool init(char const * backend_name = nullptr);
bool init_stream();
bool start_stream() const;
bool stop_stream() const;
bool destroy_stream() const;
bool destroy();
bool activate_log(bool active);
long user_data_cb(cubeb_stream* stm, void* user, const void* input_buffer,
void* output_buffer, long nframes);
void user_state_cb(cubeb_stream* stm, void* user, cubeb_state state);
bool register_device_collection_changed(cubeb_device_type devtype) const;
bool unregister_device_collection_changed(cubeb_device_type devtype) const;
cubeb_stream_params output_params = {};
cubeb_stream_params input_params = {};
private:
bool has_input() { return input_params.rate != 0; }
bool has_output() { return output_params.rate != 0; }
cubeb* context = nullptr;
cubeb_stream* stream = nullptr;
cubeb_devid output_device = nullptr;
cubeb_devid input_device = nullptr;
/* Accessed only from client and audio thread. */
std::atomic<uint32_t> _rate = {0};
std::atomic<uint32_t> _channels = {0};
/* Accessed only from audio thread. */
uint32_t _total_frames = 0;
};
bool cubeb_client::init(char const * backend_name) {
int rv = cubeb_init(&context, "Cubeb Test Application", nullptr);
if (rv != CUBEB_OK) {
fprintf(stderr, "Could not init cubeb\n");
return false;
}
return true;
}
static long user_data_cb_s(cubeb_stream* stm, void* user,
const void* input_buffer, void* output_buffer,
long nframes) {
assert(user);
return static_cast<cubeb_client*>(user)->user_data_cb(stm, user, input_buffer,
output_buffer, nframes);
}
static void user_state_cb_s(cubeb_stream* stm, void* user, cubeb_state state) {
assert(user);
return static_cast<cubeb_client*>(user)->user_state_cb(stm, user, state);
}
void input_device_changed_callback_s(cubeb* context, void* user) {
fprintf(stderr, "input_device_changed_callback_s\n");
}
void output_device_changed_callback_s(cubeb* context, void* user) {
fprintf(stderr, "output_device_changed_callback_s\n");
}
void io_device_changed_callback_s(cubeb* context, void* user) {
fprintf(stderr, "io_device_changed_callback\n");
}
bool cubeb_client::init_stream() {
assert(has_input() || has_output());
_rate = has_output() ? output_params.rate : input_params.rate;
_channels = has_output() ? output_params.channels : input_params.channels;
int rv =
cubeb_stream_init(context, &stream, "Stream", input_device,
has_input() ? &input_params : nullptr, output_device,
has_output() ? &output_params : nullptr, 512,
user_data_cb_s, user_state_cb_s, this);
if (rv != CUBEB_OK) {
fprintf(stderr, "Could not open the stream\n");
return false;
}
return true;
}
bool cubeb_client::start_stream() const {
int rv = cubeb_stream_start(stream);
if (rv != CUBEB_OK) {
fprintf(stderr, "Could not start the stream\n");
return false;
}
return true;
}
bool cubeb_client::stop_stream() const {
int rv = cubeb_stream_stop(stream);
if (rv != CUBEB_OK) {
fprintf(stderr, "Could not stop the stream\n");
return false;
}
return true;
}
bool cubeb_client::destroy_stream() const {
cubeb_stream_destroy(stream);
return true;
}
bool cubeb_client::destroy() {
cubeb_destroy(context);
return true;
}
bool cubeb_client::activate_log(bool active) {
cubeb_log_level log_level = CUBEB_LOG_DISABLED;
cubeb_log_callback log_callback = nullptr;
if (active) {
log_level = CUBEB_LOG_NORMAL;
log_callback = print_log;
}
if (cubeb_set_log_callback(log_level, log_callback) != CUBEB_OK) {
fprintf(stderr, "Set log callback failed\n");
return false;
}
return true;
}
static void fill_with_sine_tone(float* buf, uint32_t num_of_frames,
uint32_t num_of_channels, uint32_t frame_rate,
uint32_t position) {
for (uint32_t i = 0; i < num_of_frames; ++i) {
for (uint32_t c = 0; c < num_of_channels; ++c) {
buf[i * num_of_channels + c] =
0.2 * sin(2 * M_PI * (i + position) * 350 / frame_rate);
buf[i * num_of_channels + c] +=
0.2 * sin(2 * M_PI * (i + position) * 440 / frame_rate);
}
}
}
long cubeb_client::user_data_cb(cubeb_stream* stm, void* user,
const void* input_buffer, void* output_buffer,
long nframes) {
if (input_buffer && output_buffer) {
const float* in = static_cast<const float*>(input_buffer);
float* out = static_cast<float*>(output_buffer);
memcpy(out, in, sizeof(float) * nframes * _channels);
} else if (output_buffer && !input_buffer) {
fill_with_sine_tone(static_cast<float*>(output_buffer), nframes, _channels,
_rate, _total_frames);
}
_total_frames += nframes;
return nframes;
}
void cubeb_client::user_state_cb(cubeb_stream* stm, void* user,
cubeb_state state) {
fprintf(stderr, "state is %s\n", state_to_string(state));
}
bool cubeb_client::register_device_collection_changed(
cubeb_device_type devtype) const {
cubeb_device_collection_changed_callback callback = nullptr;
if (devtype == static_cast<cubeb_device_type>(CUBEB_DEVICE_TYPE_INPUT |
CUBEB_DEVICE_TYPE_OUTPUT)) {
callback = io_device_changed_callback_s;
} else if (devtype & CUBEB_DEVICE_TYPE_OUTPUT) {
callback = output_device_changed_callback_s;
} else if (devtype & CUBEB_DEVICE_TYPE_INPUT) {
callback = input_device_changed_callback_s;
}
int r = cubeb_register_device_collection_changed(
context, devtype, callback, nullptr);
if (r != CUBEB_OK) {
return false;
}
return true;
}
bool cubeb_client::unregister_device_collection_changed(
cubeb_device_type devtype) const {
int r = cubeb_register_device_collection_changed(
context, devtype, nullptr, nullptr);
if (r != CUBEB_OK) {
return false;
}
return true;
}
enum play_mode {
RECORD,
PLAYBACK,
DUPLEX,
COLLECTION_CHANGE,
};
struct operation_data {
play_mode pm;
uint32_t rate;
cubeb_device_type collection_device_type;
};
void print_help() {
const char * msg =
"p: start a initialized stream\n"
"s: stop a started stream\n"
"i: change device type to input\n"
"o: change device type to output\n"
"a: change device type to input and output\n"
"k: change device type to unknown\n"
"r: register device collection changed callback for the current device type\n"
"u: unregister device collection changed callback for the current device type\n"
"q: quit\n"
"h: print this message\n";
fprintf(stderr, "%s\n", msg);
}
bool choose_action(const cubeb_client& cl, operation_data * op, char c) {
while (c == 10 || c == 32) {
// Consume "enter and "space"
c = getchar();
}
if (c == 'q') {
if (op->pm == PLAYBACK || op->pm == RECORD || op->pm == DUPLEX) {
bool res = cl.stop_stream();
if (!res) {
fprintf(stderr, "stop_stream failed\n");
}
res = cl.destroy_stream();
if (!res) {
fprintf(stderr, "destroy_stream failed\n");
}
} else if (op->pm == COLLECTION_CHANGE) {
bool res = cl.unregister_device_collection_changed(op->collection_device_type);
if (!res) {
fprintf(stderr, "unregister_device_collection_changed failed\n");
}
}
return false; // exit the loop
} else if (c == 'h') {
print_help();
} else if (c == 'p') {
bool res = cl.start_stream();
if (res) {
fprintf(stderr, "start_stream succeed\n");
} else {
fprintf(stderr, "start_stream failed\n");
}
} else if (c == 's') {
bool res = cl.stop_stream();
if (res) {
fprintf(stderr, "stop_stream succeed\n");
} else {
fprintf(stderr, "stop_stream failed\n");
}
} else if (c == 'i') {
op->collection_device_type = CUBEB_DEVICE_TYPE_INPUT;
fprintf(stderr, "collection device type changed to INPUT\n");
} else if (c == 'o') {
op->collection_device_type = CUBEB_DEVICE_TYPE_OUTPUT;
fprintf(stderr, "collection device type changed to OUTPUT\n");
} else if (c == 'a') {
op->collection_device_type = static_cast<cubeb_device_type>(CUBEB_DEVICE_TYPE_INPUT | CUBEB_DEVICE_TYPE_OUTPUT);
fprintf(stderr, "collection device type changed to INPUT | OUTPUT\n");
} else if (c == 'k') {
op->collection_device_type = CUBEB_DEVICE_TYPE_UNKNOWN;
fprintf(stderr, "collection device type changed to UNKNOWN\n");
} else if (c == 'r') {
bool res = cl.register_device_collection_changed(op->collection_device_type);
if (res) {
fprintf(stderr, "register_device_collection_changed succeed\n");
} else {
fprintf(stderr, "register_device_collection_changed failed\n");
}
} else if (c == 'u') {
bool res = cl.unregister_device_collection_changed(op->collection_device_type);
if (res) {
fprintf(stderr, "unregister_device_collection_changed succeed\n");
} else {
fprintf(stderr, "unregister_device_collection_changed failed\n");
}
} else {
fprintf(stderr, "Error: %c is not a valid entry\n", c);
}
return true; // Loop up
}
int main(int argc, char* argv[]) {
#ifdef _WIN32
CoInitialize(nullptr);
#endif
operation_data op;
op.pm = PLAYBACK;
if (argc > 1) {
if ('r' == argv[1][0]) {
op.pm = RECORD;
} else if ('p' == argv[1][0]) {
op.pm = PLAYBACK;
} else if ('d' == argv[1][0]) {
op.pm = DUPLEX;
} else if ('c' == argv[1][0]) {
op.pm = COLLECTION_CHANGE;
}
}
op.rate = DEFAULT_RATE;
if (argc > 2) {
op.rate = strtoul(argv[2], NULL, 0);
}
bool res = false;
cubeb_client cl;
cl.activate_log(true);
cl.init();
op.collection_device_type = CUBEB_DEVICE_TYPE_UNKNOWN;
fprintf(stderr, "collection device type is UNKNOWN\n");
if (op.pm == COLLECTION_CHANGE) {
op.collection_device_type = CUBEB_DEVICE_TYPE_OUTPUT;
fprintf(stderr, "collection device type changed to OUTPUT\n");
res = cl.register_device_collection_changed(op.collection_device_type);
if (res) {
fprintf(stderr, "register_device_collection_changed succeed\n");
} else {
fprintf(stderr, "register_device_collection_changed failed\n");
}
} else {
if (op.pm == PLAYBACK || op.pm == DUPLEX) {
cl.output_params = {CUBEB_SAMPLE_FLOAT32NE, op.rate, DEFAULT_CHANNELS,
CUBEB_LAYOUT_UNDEFINED, CUBEB_STREAM_PREF_NONE};
}
if (op.pm == RECORD || op.pm == DUPLEX) {
cl.input_params = {CUBEB_SAMPLE_FLOAT32NE, op.rate, DEFAULT_CHANNELS,
CUBEB_LAYOUT_UNDEFINED, CUBEB_STREAM_PREF_NONE};
}
res = cl.init_stream();
if (!res) {
fprintf(stderr, "stream_init failed\n");
return -1;
}
fprintf(stderr, "stream_init succeed\n");
res = cl.start_stream();
if (res) {
fprintf(stderr, "stream_start succeed\n");
} else {
fprintf(stderr, "stream_init failed\n");
}
}
// User input
do {
fprintf(stderr, "press `q` to abort or `h` for help\n");
} while (choose_action(cl, &op, getchar()));
cl.destroy();
return 0;
}
<|endoftext|> |
<commit_before>/// @brief provides fixed-point sum info
#ifndef INC_SUM_INFO_HPP_
#define INC_SUM_INFO_HPP_
#include <boost/integer.hpp>
#include <boost/static_assert.hpp>
#include <boost/concept_check.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/eval_if.hpp>
#include <limits>
#include <boost/cstdint.hpp>
namespace utils {
namespace {
using boost::mpl::if_;
using boost::mpl::eval_if;
}
template<typename storage_type, size_t total, size_t fractionals>
class number;
/// @brief tool for type inference of the summ result with fixed-point and
/// floating-point numbers
template<typename value_type>
class sum_info
{
public:
typedef value_type sum_type;
typedef value_type sum_value_type;
struct sign_info
{
enum { value = true };
};
struct closing_info
{
enum { value = true };
};
struct value_type_info
{
struct op
{
typedef value_type type;
};
struct cl
{
typedef value_type type;
};
};
};
/// @brief in case of fixed-point numbers
template<typename T, size_t n, size_t f>
class sum_info<number<T, n, f> >
{
typedef number<T, n, f> operand_type;
public:
///< is the type of summ a signed type?
struct is_signed
{
enum { value = std::numeric_limits<T>::is_signed };
};
///< is type of the summ closed under arithmetic operations?
struct is_closed
{
typedef typename if_<is_signed, boost::intmax_t, boost::uintmax_t>::type
max_type;
// total bits and std::numeric_limits do not count sign bit
enum { value = !(n + 1 <= std::numeric_limits<max_type>::digits) };
};
// brief: 1. if one do not have integral type of enough bits count then
// it has to interpret summation as a closed operation;
// 2. boost::int_t template parameter takes into account a sign bit.
///< integral value type below fixed-point number as a summ result type
struct value_type_info
{
///< in case if summ type is not closed under arithmetic operations
struct op
{
typedef typename if_<is_signed, typename boost::int_t<n + 2u>::least,
typename boost::uint_t<n + 1u>::least>::type type;
};
/// @brief in case if sum type is closed under arithmetic operations
struct cl
{
typedef T type;
};
};
///< integral value type that is below of fixed-point result type of the summ
typedef typename eval_if<is_closed, typename value_type_info::cl,
typename value_type_info::op>::type sum_value_type;
///< fixed-point type for summ result
typedef typename if_<is_closed, operand_type, number<sum_value_type, n + 1, f> >::type
sum_type;
};
}
#endif
<commit_msg>sum_info.hpp: keep code uniform -> 1 to 1u<commit_after>/// @brief provides fixed-point sum info
#ifndef INC_SUM_INFO_HPP_
#define INC_SUM_INFO_HPP_
#include <boost/integer.hpp>
#include <boost/static_assert.hpp>
#include <boost/concept_check.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/eval_if.hpp>
#include <limits>
#include <boost/cstdint.hpp>
namespace utils {
namespace {
using boost::mpl::if_;
using boost::mpl::eval_if;
}
template<typename storage_type, size_t total, size_t fractionals>
class number;
/// @brief tool for type inference of the summ result with fixed-point and
/// floating-point numbers
template<typename value_type>
class sum_info
{
public:
typedef value_type sum_type;
typedef value_type sum_value_type;
struct sign_info
{
enum { value = true };
};
struct closing_info
{
enum { value = true };
};
struct value_type_info
{
struct op
{
typedef value_type type;
};
struct cl
{
typedef value_type type;
};
};
};
/// @brief in case of fixed-point numbers
template<typename T, size_t n, size_t f>
class sum_info<number<T, n, f> >
{
typedef number<T, n, f> operand_type;
public:
///< is the type of summ a signed type?
struct is_signed
{
enum { value = std::numeric_limits<T>::is_signed };
};
///< is type of the summ closed under arithmetic operations?
struct is_closed
{
typedef typename if_<is_signed, boost::intmax_t, boost::uintmax_t>::type
max_type;
// total bits and std::numeric_limits do not count sign bit
enum { value = !(n + 1u <= std::numeric_limits<max_type>::digits) };
};
// brief: 1. if one do not have integral type of enough bits count then
// it has to interpret summation as a closed operation;
// 2. boost::int_t template parameter takes into account a sign bit.
///< integral value type below fixed-point number as a summ result type
struct value_type_info
{
///< in case if summ type is not closed under arithmetic operations
struct op
{
typedef typename if_<is_signed, typename boost::int_t<n + 2u>::least,
typename boost::uint_t<n + 1u>::least>::type type;
};
/// @brief in case if sum type is closed under arithmetic operations
struct cl
{
typedef T type;
};
};
///< integral value type that is below of fixed-point result type of the summ
typedef typename eval_if<is_closed, typename value_type_info::cl,
typename value_type_info::op>::type sum_value_type;
///< fixed-point type for summ result
typedef typename if_<is_closed, operand_type, number<sum_value_type, n + 1u, f> >::type
sum_type;
};
}
#endif
<|endoftext|> |
<commit_before>#pragma once
#include "CrestCacheEntry.hpp"
#include "CrestConnectionPool.hpp"
#include <string>
#include <unordered_map>
#include <mutex>
class CrestCache
{
public:
struct CacheLookupResults
{
CrestCacheEntry *entry;
/**Lock on entry->mutex*/
std::unique_lock<std::mutex> lock;
};
struct CacheLookupFutureResults
{
CrestCacheEntry *entry;
CrestCacheEntry::Status status;
std::vector<uint8_t> data;
void wait()
{
std::unique_lock<std::mutex> lock(entry->mutex);
entry->wait(lock);
status = entry->status;
data = entry->data;
}
};
CrestCache();
~CrestCache();
void stop();
CrestCacheEntry *get(const std::string &path);
/**Get CREST data.
* @param path The path to get from CREST.
*/
CacheLookupFutureResults get_future(const std::string &path);
CacheLookupResults get_now(const std::string &path);
/**Used by CrestConnectionPool to use up spare bandwidth by getting requests to cache in
* advance.
*/
CrestHttpRequest *get_preload_request();
private:
typedef std::unique_lock<std::mutex> unique_lock;
typedef std::unordered_map<std::string, CrestCacheEntry> Cache;
static const size_t MAX_CACHE_SIZE = 1024*1024*20//20MB
/**Lock for the cache map.
* @warning Never attempt to lock this if already holding any entry lock. Always lock this
* before locking an entry. Failure to do so may result in dead lock.
*/
std::mutex cache_mutex;
size_t cache_size;
Cache cache;
/**CrestConnectionPool for updating cache entries.*/
std::vector<CrestCacheEntry*> preload_entries;
size_t preload_request_next;
CrestConnectionPool crest_connection_pool;
CrestCacheEntry &get_entry(const std::string &path);
CrestCacheEntry *get_locked(const std::string &path, std::unique_lock<std::mutex> &lock);
void update_entry(CrestCacheEntry &entry);
void update_entry_completion(CrestCacheEntry *entry, CrestHttpRequest *request);
/**With the cache already locked, see if any data must be purged to remaining within
* cache size limits.
*/
void check_cache_purge();
};
<commit_msg>Corrected syntax error in cache limit<commit_after>#pragma once
#include "CrestCacheEntry.hpp"
#include "CrestConnectionPool.hpp"
#include <string>
#include <unordered_map>
#include <mutex>
class CrestCache
{
public:
struct CacheLookupResults
{
CrestCacheEntry *entry;
/**Lock on entry->mutex*/
std::unique_lock<std::mutex> lock;
};
struct CacheLookupFutureResults
{
CrestCacheEntry *entry;
CrestCacheEntry::Status status;
std::vector<uint8_t> data;
void wait()
{
std::unique_lock<std::mutex> lock(entry->mutex);
entry->wait(lock);
status = entry->status;
data = entry->data;
}
};
CrestCache();
~CrestCache();
void stop();
CrestCacheEntry *get(const std::string &path);
/**Get CREST data.
* @param path The path to get from CREST.
*/
CacheLookupFutureResults get_future(const std::string &path);
CacheLookupResults get_now(const std::string &path);
/**Used by CrestConnectionPool to use up spare bandwidth by getting requests to cache in
* advance.
*/
CrestHttpRequest *get_preload_request();
private:
typedef std::unique_lock<std::mutex> unique_lock;
typedef std::unordered_map<std::string, CrestCacheEntry> Cache;
static const size_t MAX_CACHE_SIZE = 1024*1024*20;//20MB
/**Lock for the cache map.
* @warning Never attempt to lock this if already holding any entry lock. Always lock this
* before locking an entry. Failure to do so may result in dead lock.
*/
std::mutex cache_mutex;
size_t cache_size;
Cache cache;
/**CrestConnectionPool for updating cache entries.*/
std::vector<CrestCacheEntry*> preload_entries;
size_t preload_request_next;
CrestConnectionPool crest_connection_pool;
CrestCacheEntry &get_entry(const std::string &path);
CrestCacheEntry *get_locked(const std::string &path, std::unique_lock<std::mutex> &lock);
void update_entry(CrestCacheEntry &entry);
void update_entry_completion(CrestCacheEntry *entry, CrestHttpRequest *request);
/**With the cache already locked, see if any data must be purged to remaining within
* cache size limits.
*/
void check_cache_purge();
};
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Matthew Harvey
*
* 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 "time_log.hpp"
#include "stint.hpp"
#include "string_utilities.hpp"
#include "time_point.hpp"
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstddef>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <ios>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
using std::cerr;
using std::endl;
using std::getline;
using std::ifstream;
using std::isspace;
using std::ios;
using std::move;
using std::ofstream;
using std::ostringstream;
using std::remove;
using std::runtime_error;
using std::size_t;
using std::string;
using std::stringstream;
using std::tm;
using std::upper_bound;
using std::vector;
namespace chrono = std::chrono;
namespace swx
{
TimeLog::TimeLog(string const& p_filepath):
m_is_loaded(false),
m_filepath(p_filepath)
{
assert (m_entries.empty());
assert (m_activities.empty());
assert (m_activity_map.empty());
}
void
TimeLog::append_entry
( string const& p_activity,
TimePoint const& p_time_point
)
{
// TODO Make this atomic?
mark_cache_as_stale();
ofstream outfile(m_filepath.c_str(), ios::app);
outfile << time_point_to_stamp(p_time_point)
<< ' ' << p_activity << endl;
return;
}
vector<Stint>
TimeLog::get_stints
( string const* p_activity,
TimePoint const* p_begin,
TimePoint const* p_end
)
{
load();
vector<Stint> ret;
auto const e = m_entries.end();
auto it = (p_begin? find_entry_just_before(*p_begin): m_entries.begin());
auto const n = now();
for ( ; (it != e) && (!p_end || (it->time_point < *p_end)); ++it)
{
auto const activity = id_to_activity(it->activity_id);
if (!p_activity || (*p_activity == activity))
{
auto tp = it->time_point;
if (p_begin && (tp < *p_begin)) tp = *p_begin;
auto const next_it = it + 1;
auto const done = (next_it == e);
auto default_next_tp = (n > tp? n: tp);
auto next_tp = (done? default_next_tp: next_it->time_point);
if (p_end && (next_tp > *p_end)) next_tp = *p_end;
assert (!p_begin || (tp >= *p_begin));
assert (!p_begin || (next_tp >= *p_begin));
assert (!p_end || (next_tp <= *p_end));
assert (next_tp >= tp);
auto const seconds = chrono::duration_cast<Seconds>(next_tp - tp);
Interval const interval(tp, seconds, done);
ret.push_back(Stint(activity, interval));
}
}
return ret;
}
void
TimeLog::clear_cache()
{
m_entries.clear();
m_activities.clear();
m_activity_map.clear();
return;
}
void
TimeLog::mark_cache_as_stale()
{
m_is_loaded = false;
}
void
TimeLog::load()
{
if (!m_is_loaded)
{
clear_cache();
ifstream infile(m_filepath.c_str());
string line;
size_t line_number = 1;
while (getline(infile, line))
{
load_entry(line, line_number);
++line_number;
}
m_is_loaded = true;
}
return;
}
TimeLog::ActivityId
TimeLog::register_activity(string const& p_activity)
{
auto const it = m_activity_map.find(p_activity);
if (it == m_activity_map.end())
{
// TODO Make this atomic?
auto const ret = m_activities.size();
m_activities.push_back(p_activity);
m_activity_map[p_activity] = ret;
return ret;
}
return it->second;
}
void
TimeLog::load_entry(string const& p_entry_string, size_t p_line_number)
{
static string const time_format("YYYY-MM-DDTHH:MM:SS");
if (p_entry_string.size() < time_format.size())
{
ostringstream oss;
oss << "TimeLog parsing error at line "
<< p_line_number << '.';
throw runtime_error(oss.str());
}
auto it = p_entry_string.begin() + time_format.size();
assert (it > p_entry_string.begin());
string const time_stamp(p_entry_string.begin(), it);
string const activity = trim(string(it, p_entry_string.end()));
auto const activity_id = register_activity(activity);
auto const time_point = time_stamp_to_point(time_stamp);
Entry entry(activity_id, time_point);
if (!m_entries.empty())
{
auto const last_time_point = m_entries.back().time_point;
if (entry.time_point < last_time_point)
{
ostringstream oss;
oss << "TimeLog entries out of order at line "
<< p_line_number << '.';
throw runtime_error(oss.str());
}
}
m_entries.push_back(entry);
return;
}
string
TimeLog::id_to_activity(ActivityId p_activity_id)
{
load();
return m_activities.at(p_activity_id);
}
vector<TimeLog::Entry>::const_iterator
TimeLog::find_entry_just_before(TimePoint const& p_time_point)
{
load();
typedef vector<TimeLog::Entry>::const_iterator Iter;
auto const comp = [](Entry const& lhs, Entry const& rhs)
{
return lhs.time_point < rhs.time_point;
};
Iter const b = m_entries.begin();
Iter const e = m_entries.end();
Entry const dummy(0, p_time_point);
Iter it = upper_bound(b, e, dummy, comp);
while ((it != b) && (it == e) || (it->time_point > p_time_point))
{
--it;
}
return it;
}
TimeLog::Entry::Entry(ActivityId p_activity_id, TimePoint const& p_time_point):
activity_id(p_activity_id),
time_point(p_time_point)
{
}
} // namespace swx
<commit_msg>Improved efficiency of TimeLog::get_stints().<commit_after>/*
* Copyright 2014 Matthew Harvey
*
* 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 "time_log.hpp"
#include "stint.hpp"
#include "string_utilities.hpp"
#include "time_point.hpp"
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstddef>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <ios>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
using std::cerr;
using std::endl;
using std::getline;
using std::ifstream;
using std::isspace;
using std::ios;
using std::move;
using std::ofstream;
using std::ostringstream;
using std::remove;
using std::runtime_error;
using std::size_t;
using std::string;
using std::stringstream;
using std::tm;
using std::upper_bound;
using std::vector;
namespace chrono = std::chrono;
namespace swx
{
TimeLog::TimeLog(string const& p_filepath):
m_is_loaded(false),
m_filepath(p_filepath)
{
assert (m_entries.empty());
assert (m_activities.empty());
assert (m_activity_map.empty());
}
void
TimeLog::append_entry
( string const& p_activity,
TimePoint const& p_time_point
)
{
// TODO Make this atomic?
mark_cache_as_stale();
ofstream outfile(m_filepath.c_str(), ios::app);
outfile << time_point_to_stamp(p_time_point)
<< ' ' << p_activity << endl;
return;
}
vector<Stint>
TimeLog::get_stints
( string const* p_activity,
TimePoint const* p_begin,
TimePoint const* p_end
)
{
load();
vector<Stint> ret;
auto const e = m_entries.end();
auto it = (p_begin? find_entry_just_before(*p_begin): m_entries.begin());
auto const n = now();
ActivityId const sought_activity_id =
(p_activity? register_activity(*p_activity): 0);
for ( ; (it != e) && (!p_end || (it->time_point < *p_end)); ++it)
{
ActivityId const current_activity_id = it->activity_id;
if (!p_activity || (sought_activity_id == current_activity_id))
{
auto tp = it->time_point;
if (p_begin && (tp < *p_begin)) tp = *p_begin;
auto const next_it = it + 1;
auto const done = (next_it == e);
auto default_next_tp = (n > tp? n: tp);
auto next_tp = (done? default_next_tp: next_it->time_point);
if (p_end && (next_tp > *p_end)) next_tp = *p_end;
assert (!p_begin || (tp >= *p_begin));
assert (!p_begin || (next_tp >= *p_begin));
assert (!p_end || (next_tp <= *p_end));
assert (next_tp >= tp);
auto const seconds = chrono::duration_cast<Seconds>(next_tp - tp);
Interval const interval(tp, seconds, done);
ret.push_back(Stint(id_to_activity(current_activity_id), interval));
}
}
return ret;
}
void
TimeLog::clear_cache()
{
m_entries.clear();
m_activities.clear();
m_activity_map.clear();
return;
}
void
TimeLog::mark_cache_as_stale()
{
m_is_loaded = false;
}
void
TimeLog::load()
{
if (!m_is_loaded)
{
clear_cache();
ifstream infile(m_filepath.c_str());
string line;
size_t line_number = 1;
while (getline(infile, line))
{
load_entry(line, line_number);
++line_number;
}
m_is_loaded = true;
}
return;
}
TimeLog::ActivityId
TimeLog::register_activity(string const& p_activity)
{
auto const it = m_activity_map.find(p_activity);
if (it == m_activity_map.end())
{
// TODO Make this atomic?
auto const ret = m_activities.size();
m_activities.push_back(p_activity);
m_activity_map[p_activity] = ret;
return ret;
}
return it->second;
}
void
TimeLog::load_entry(string const& p_entry_string, size_t p_line_number)
{
static string const time_format("YYYY-MM-DDTHH:MM:SS");
if (p_entry_string.size() < time_format.size())
{
ostringstream oss;
oss << "TimeLog parsing error at line "
<< p_line_number << '.';
throw runtime_error(oss.str());
}
auto it = p_entry_string.begin() + time_format.size();
assert (it > p_entry_string.begin());
string const time_stamp(p_entry_string.begin(), it);
string const activity = trim(string(it, p_entry_string.end()));
auto const activity_id = register_activity(activity);
auto const time_point = time_stamp_to_point(time_stamp);
Entry entry(activity_id, time_point);
if (!m_entries.empty())
{
auto const last_time_point = m_entries.back().time_point;
if (entry.time_point < last_time_point)
{
ostringstream oss;
oss << "TimeLog entries out of order at line "
<< p_line_number << '.';
throw runtime_error(oss.str());
}
}
m_entries.push_back(entry);
return;
}
string
TimeLog::id_to_activity(ActivityId p_activity_id)
{
load();
return m_activities.at(p_activity_id);
}
vector<TimeLog::Entry>::const_iterator
TimeLog::find_entry_just_before(TimePoint const& p_time_point)
{
load();
typedef vector<TimeLog::Entry>::const_iterator Iter;
auto const comp = [](Entry const& lhs, Entry const& rhs)
{
return lhs.time_point < rhs.time_point;
};
Iter const b = m_entries.begin();
Iter const e = m_entries.end();
Entry const dummy(0, p_time_point);
Iter it = upper_bound(b, e, dummy, comp);
while ((it != b) && (it == e) || (it->time_point > p_time_point))
{
--it;
}
return it;
}
TimeLog::Entry::Entry(ActivityId p_activity_id, TimePoint const& p_time_point):
activity_id(p_activity_id),
time_point(p_time_point)
{
}
} // namespace swx
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "timedata.h"
#include "netbase.h"
#include "sync.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"
#include <boost/foreach.hpp>
using namespace std;
static CCriticalSection cs_nTimeOffset;
static int64_t nTimeOffset = 0;
/**
* "Never go to sea with two chronometers; take one or three."
* Our three time sources are:
* - System clock
* - Median of other nodes clocks
* - The user (asking the user to fix the system clock if the first two disagree)
*/
int64_t GetTimeOffset()
{
LOCK(cs_nTimeOffset);
return nTimeOffset;
}
int64_t GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
static int64_t abs64(int64_t n)
{
return (n >= 0 ? n : -n);
}
void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
{
LOCK(cs_nTimeOffset);
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
static CMedianFilter<int64_t> vTimeOffsets(200,0);
vTimeOffsets.input(nOffsetSample);
LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
// There is a known issue here (see issue #4521):
//
// - The structure vTimeOffsets contains up to 200 elements, after which
// any new element added to it will not increase its size, replacing the
// oldest element.
//
// - The condition to update nTimeOffset includes checking whether the
// number of elements in vTimeOffsets is odd, which will never happen after
// there are 200 elements.
//
// But in this case the 'bug' is protective against some attacks, and may
// actually explain why we've never seen attacks which manipulate the
// clock offset.
//
// So we should hold off on fixing this and clean it up as part of
// a timing cleanup that strengthens it in a number of other ways.
//
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 70 * 60)
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64_t nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Unobtanium Core will not work properly.");
strMiscWarning = strMessage;
LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64_t n, vSorted)
LogPrintf("%+d ", n);
LogPrintf("| ");
}
LogPrintf("nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
<commit_msg>Do not store more than 200 timedata samples.<commit_after>// Copyright (c) 2014-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "timedata.h"
#include "netbase.h"
#include "sync.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"
#include <boost/foreach.hpp>
using namespace std;
static CCriticalSection cs_nTimeOffset;
static int64_t nTimeOffset = 0;
/**
* "Never go to sea with two chronometers; take one or three."
* Our three time sources are:
* - System clock
* - Median of other nodes clocks
* - The user (asking the user to fix the system clock if the first two disagree)
*/
int64_t GetTimeOffset()
{
LOCK(cs_nTimeOffset);
return nTimeOffset;
}
int64_t GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
static int64_t abs64(int64_t n)
{
return (n >= 0 ? n : -n);
}
#define BITCOIN_TIMEDATA_MAX_SAMPLES 200
void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
{
LOCK(cs_nTimeOffset);
// Ignore duplicates
static set<CNetAddr> setKnown;
if (setKnown.size() == BITCOIN_TIMEDATA_MAX_SAMPLES)
return;
if (!setKnown.insert(ip).second)
return;
// Add data
static CMedianFilter<int64_t> vTimeOffsets(BITCOIN_TIMEDATA_MAX_SAMPLES, 0);
vTimeOffsets.input(nOffsetSample);
LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
// There is a known issue here (see issue #4521):
//
// - The structure vTimeOffsets contains up to 200 elements, after which
// any new element added to it will not increase its size, replacing the
// oldest element.
//
// - The condition to update nTimeOffset includes checking whether the
// number of elements in vTimeOffsets is odd, which will never happen after
// there are 200 elements.
//
// But in this case the 'bug' is protective against some attacks, and may
// actually explain why we've never seen attacks which manipulate the
// clock offset.
//
// So we should hold off on fixing this and clean it up as part of
// a timing cleanup that strengthens it in a number of other ways.
//
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 70 * 60)
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64_t nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Unobtanium Core will not work properly.");
strMiscWarning = strMessage;
LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64_t n, vSorted)
LogPrintf("%+d ", n);
LogPrintf("| ");
}
LogPrintf("nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* *
* This software is published under the terms of the Apache Software *
* License version 1.1, a copy of which has been included with this *
* distribution in the license.apl file. *
***************************************************************************/
#include <log4cxx/helpers/timezone.h>
#include <locale>
int getYear(int64_t date)
{
time_t d = (time_t)(date / 1000);
return ::localtime(&d)->tm_year;
}
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(TimeZone)
TimeZonePtr TimeZone::defaultTimeZone = new TimeZone(_T(""));
TimeZone::TimeZone(const String& ID)
: ID(ID), rawOffset(0), DSTSavings(0)
{
String timeZoneEnv = _T("TZ=") + ID;
USES_CONVERSION;
::putenv((char *)T2A(timeZoneEnv.c_str()));
tzset();
time_t now = time(0);
tm localNow = *::localtime(&now);
tm utcNow = *::gmtime(&now);
rawOffset = (int)::difftime(::mktime(&localNow), ::mktime(&utcNow)) * 1000;
int year = localNow.tm_year;
Rule * rule = new Rule(year);
// we check if we found a daylight time
if (rule->startDate != 0 && rule->endDate != 0)
{
// since we have computed a rule, we store it
rules.insert(RuleMap::value_type(year, rule));
DSTSavings = 3600 * 1000; // 1 hour
}
else
{
delete rule;
}
}
TimeZone::~TimeZone()
{
for (RuleMap::iterator it = rules.begin(); it != rules.end(); it++)
{
Rule * rule = it->second;
delete rule;
}
}
int TimeZone::getOffset(int64_t date) const
{
if (inDaylightTime(date))
{
return rawOffset + DSTSavings;
}
else
{
return rawOffset;
}
}
TimeZonePtr TimeZone::getDefault()
{
return defaultTimeZone;
}
TimeZonePtr TimeZone::getTimeZone(const String& ID)
{
return new TimeZone(_T("ID"));
}
bool TimeZone::inDaylightTime(int64_t date) const
{
if (!useDaylightTime())
{
return false;
}
time_t d = (time_t)(date / 1000);
int year = ::localtime(&d)->tm_year;
RuleMap::iterator it = rules.find(year);
if (it == rules.end())
{
synchronized sync(this);
it = rules.find(year);
if (it == rules.end())
{
it = rules.insert(RuleMap::value_type(
year, new Rule(year))).first;
}
}
Rule * rule = it->second;
return (date >= rule->startDate && date <= rule->endDate);
}
TimeZone::Rule::Rule(int year)
: startDate(0), endDate(0)
{
tm tm;
memset (&tm, 0, sizeof (tm));
tm.tm_mday = 1;
tm.tm_year = year;
time_t t = ::mktime(&tm);
int isDST, day, hour, min;
for (day = 0; day < 365; day++)
{
t += 60 * 60 * 24;
isDST = ::localtime(&t)->tm_isdst;
if (startDate == 0)
{
if (isDST > 0)
{
t -= 60 * 60 * 24;
for (hour = 0; hour < 24; hour++)
{
t += 60 * 60;
isDST = ::localtime(&t)->tm_isdst;
if (isDST > 0)
{
t -= 60 * 60;
for (min = 0; min < 60; min++)
{
t += 60;
isDST = ::localtime(&t)->tm_isdst;
if (isDST > 0)
{
startDate = (int64_t)t * 1000;
break;
}
}
break;
}
}
}
}
else if (isDST == 0)
{
t -= 60 * 60 * 24;
for (hour = 0; hour < 24; hour++)
{
t += 60 * 60;
isDST = ::localtime(&t)->tm_isdst;
if (isDST == 0)
{
t -= 60 * 60;
for (min = 0; min < 60; min++)
{
t += 60;
isDST = ::localtime(&t)->tm_isdst;
if (isDST == 0)
{
endDate = (int64_t)t * 1000;
break;
}
}
break;
}
}
if (endDate != 0)
{
break;
}
}
}
}
<commit_msg>fixed daylight management and timezone instanciation<commit_after>/***************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* *
* This software is published under the terms of the Apache Software *
* License version 1.1, a copy of which has been included with this *
* distribution in the license.apl file. *
***************************************************************************/
#include <log4cxx/helpers/timezone.h>
#include <locale>
int getYear(int64_t date)
{
time_t d = (time_t)(date / 1000);
return ::localtime(&d)->tm_year;
}
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(TimeZone)
TimeZonePtr TimeZone::defaultTimeZone = new TimeZone(_T(""));
TimeZone::TimeZone(const String& ID)
: ID(ID), rawOffset(0), DSTSavings(0)
{
String timeZoneEnv = _T("TZ=") + ID;
USES_CONVERSION;
::putenv((char *)T2A(timeZoneEnv.c_str()));
tzset();
time_t now = time(0);
tm localNow = *::localtime(&now);
tm utcNow = *::gmtime(&now);
rawOffset = (int)::difftime(::mktime(&localNow), ::mktime(&utcNow)) * 1000;
int year = localNow.tm_year;
Rule * rule = new Rule(year);
// we check if we found a daylight time
if (rule->startDate != 0 && rule->endDate != 0)
{
// since we have computed a rule, we store it
rules.insert(RuleMap::value_type(year, rule));
DSTSavings = 3600 * 1000; // 1 hour
}
else
{
delete rule;
}
}
TimeZone::~TimeZone()
{
for (RuleMap::iterator it = rules.begin(); it != rules.end(); it++)
{
Rule * rule = it->second;
delete rule;
}
}
int TimeZone::getOffset(int64_t date) const
{
if (inDaylightTime(date))
{
return rawOffset + DSTSavings;
}
else
{
return rawOffset;
}
}
TimeZonePtr TimeZone::getDefault()
{
return defaultTimeZone;
}
TimeZonePtr TimeZone::getTimeZone(const String& ID)
{
return new TimeZone(ID);
}
bool TimeZone::inDaylightTime(int64_t date) const
{
if (!useDaylightTime())
{
return false;
}
time_t d = (time_t)(date / 1000);
int year = ::localtime(&d)->tm_year;
RuleMap::iterator it = rules.find(year);
if (it == rules.end())
{
synchronized sync(this);
it = rules.find(year);
if (it == rules.end())
{
it = rules.insert(RuleMap::value_type(
year, new Rule(year))).first;
}
}
Rule * rule = it->second;
return (date >= rule->startDate && date < rule->endDate);
}
TimeZone::Rule::Rule(int year)
: startDate(0), endDate(0)
{
tm tm;
memset (&tm, 0, sizeof (tm));
tm.tm_mday = 1;
tm.tm_year = year;
time_t t = ::mktime(&tm);
int isDST, day, hour, min;
for (day = 0; day < 365; day++)
{
t += 60 * 60 * 24;
isDST = ::localtime(&t)->tm_isdst;
if (startDate == 0)
{
if (isDST > 0)
{
t -= 60 * 60 * 24;
for (hour = 0; hour < 24; hour++)
{
t += 60 * 60;
isDST = ::localtime(&t)->tm_isdst;
if (isDST > 0)
{
t -= 60 * 60;
for (min = 0; min < 60; min++)
{
t += 60;
isDST = ::localtime(&t)->tm_isdst;
if (isDST > 0)
{
startDate = (int64_t)t * 1000;
break;
}
}
break;
}
}
}
}
else if (isDST == 0)
{
t -= 60 * 60 * 24;
for (hour = 0; hour < 24; hour++)
{
t += 60 * 60;
isDST = ::localtime(&t)->tm_isdst;
if (isDST == 0)
{
t -= 60 * 60;
for (min = 0; min < 60; min++)
{
t += 60;
isDST = ::localtime(&t)->tm_isdst;
if (isDST == 0)
{
endDate = (int64_t)t * 1000;
break;
}
}
break;
}
}
if (endDate != 0)
{
break;
}
}
}
}
<|endoftext|> |
<commit_before>#line 2 "togo/app.cpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#include <togo/config.hpp>
#include <togo/app_type.hpp>
#include <togo/log.hpp>
#include <togo/system.hpp>
#include <togo/memory.hpp>
#include <togo/gfx/init.hpp>
#include <togo/gfx/display.hpp>
#include <togo/input_buffer.hpp>
namespace togo {
AppBase::~AppBase() {}
AppBase::AppBase(
init_func_type func_init,
shutdown_func_type func_shutdown,
update_func_type func_update,
render_func_type func_render,
unsigned num_args,
char const* args[],
float update_freq
)
: _func_init(func_init)
, _func_shutdown(func_shutdown)
, _func_update(func_update)
, _func_render(func_render)
, _num_args(num_args)
, _args(args)
, _display(nullptr)
, _input_buffer(memory::default_allocator())
, _task_manager(
system::num_cores() - 1u,
memory::default_allocator()
)
, _update_freq(update_freq)
, _quit(false)
{}
namespace app {
void core_quit(AppBase& app_base);
void core_run(AppBase& app_base);
static void core_init(AppBase& app_base);
static void core_shutdown(AppBase& app_base);
static void core_update(AppBase& app_base, float dt);
static void core_render(AppBase& app_base);
static void core_init(AppBase& app_base) {
TOGO_LOG("App: initializing\n");
gfx::init(3, 2);
gfx::Config config{};
config.color_bits = {8, 8, 8, 0};
config.depth_bits = 16;
config.stencil_bits = 0;
config.msaa_num_buffers = 0;
config.msaa_num_samples = 0;
config.flags = gfx::ConfigFlags::double_buffered;
app_base._display = gfx::display::create(
"togo display",
1024, 768,
gfx::DisplayFlags::borderless |
gfx::DisplayFlags::resizable,
config
);
input_buffer::add_display(app_base._input_buffer, app_base._display);
gfx::display::set_mouse_lock(app_base._display, false);
app_base._quit = false;
app_base._func_init(app_base);
}
static void core_shutdown(AppBase& app_base) {
TOGO_LOG("App: shutting down\n");
app_base._func_shutdown(app_base);
input_buffer::remove_display(app_base._input_buffer, app_base._display);
gfx::display::destroy(app_base._display);
gfx::shutdown();
}
static void core_update(AppBase& app_base, float dt) {
InputEventType event_type{};
InputEvent const* event = nullptr;
while (input_buffer::poll(app_base._input_buffer, event_type, event)) {
if (
event_type == InputEventType::display_close_request &&
event->display == app_base._display
) {
app::core_quit(app_base);
}
}
app_base._func_update(app_base, dt);
}
static void core_render(AppBase& app_base) {
app_base._func_render(app_base);
gfx::display::swap_buffers(app_base._display);
}
void core_run(AppBase& app_base) {
app::core_init(app_base);
float const update_freq = app_base._update_freq;
float time_prev = system::time_monotonic();
float time_next;
float time_delta;
float time_accum = 0.0f;
while (!app_base._quit) {
time_next = system::time_monotonic();
time_delta = time_next - time_prev;
time_prev = time_next;
time_accum += time_delta;
while (time_accum >= update_freq) {
time_accum -= update_freq;
app::core_update(app_base, update_freq);
}
app::core_render(app_base);
system::sleep_ms(1);
}
app::core_shutdown(app_base);
}
void core_quit(AppBase& app_base) {
TOGO_LOG("App: quitting\n");
app_base._quit = true;
}
} // namespace app
} // namespace togo
<commit_msg>app::run: update immediately and only render when an update occurs.<commit_after>#line 2 "togo/app.cpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#include <togo/config.hpp>
#include <togo/app_type.hpp>
#include <togo/log.hpp>
#include <togo/system.hpp>
#include <togo/memory.hpp>
#include <togo/gfx/init.hpp>
#include <togo/gfx/display.hpp>
#include <togo/input_buffer.hpp>
namespace togo {
AppBase::~AppBase() {}
AppBase::AppBase(
init_func_type func_init,
shutdown_func_type func_shutdown,
update_func_type func_update,
render_func_type func_render,
unsigned num_args,
char const* args[],
float update_freq
)
: _func_init(func_init)
, _func_shutdown(func_shutdown)
, _func_update(func_update)
, _func_render(func_render)
, _num_args(num_args)
, _args(args)
, _display(nullptr)
, _input_buffer(memory::default_allocator())
, _task_manager(
system::num_cores() - 1u,
memory::default_allocator()
)
, _update_freq(update_freq)
, _quit(false)
{}
namespace app {
void core_quit(AppBase& app_base);
void core_run(AppBase& app_base);
static void core_init(AppBase& app_base);
static void core_shutdown(AppBase& app_base);
static void core_update(AppBase& app_base, float dt);
static void core_render(AppBase& app_base);
static void core_init(AppBase& app_base) {
TOGO_LOG("App: initializing\n");
gfx::init(3, 2);
gfx::Config config{};
config.color_bits = {8, 8, 8, 0};
config.depth_bits = 16;
config.stencil_bits = 0;
config.msaa_num_buffers = 0;
config.msaa_num_samples = 0;
config.flags = gfx::ConfigFlags::double_buffered;
app_base._display = gfx::display::create(
"togo display",
1024, 768,
gfx::DisplayFlags::borderless |
gfx::DisplayFlags::resizable,
config
);
input_buffer::add_display(app_base._input_buffer, app_base._display);
gfx::display::set_mouse_lock(app_base._display, false);
app_base._quit = false;
app_base._func_init(app_base);
}
static void core_shutdown(AppBase& app_base) {
TOGO_LOG("App: shutting down\n");
app_base._func_shutdown(app_base);
input_buffer::remove_display(app_base._input_buffer, app_base._display);
gfx::display::destroy(app_base._display);
gfx::shutdown();
}
static void core_update(AppBase& app_base, float dt) {
InputEventType event_type{};
InputEvent const* event = nullptr;
while (input_buffer::poll(app_base._input_buffer, event_type, event)) {
if (
event_type == InputEventType::display_close_request &&
event->display == app_base._display
) {
app::core_quit(app_base);
}
}
app_base._func_update(app_base, dt);
}
static void core_render(AppBase& app_base) {
app_base._func_render(app_base);
gfx::display::swap_buffers(app_base._display);
}
void core_run(AppBase& app_base) {
app::core_init(app_base);
float const update_freq = app_base._update_freq;
float time_prev = system::time_monotonic();
float time_next;
float time_delta;
float time_accum = update_freq;
bool do_render = false;
while (!app_base._quit) {
time_next = system::time_monotonic();
time_delta = time_next - time_prev;
time_prev = time_next;
time_accum += time_delta;
do_render = time_accum >= update_freq;
while (time_accum >= update_freq) {
time_accum -= update_freq;
app::core_update(app_base, update_freq);
}
if (do_render) {
app::core_render(app_base);
}
system::sleep_ms(1);
}
app::core_shutdown(app_base);
}
void core_quit(AppBase& app_base) {
TOGO_LOG("App: quitting\n");
app_base._quit = true;
}
} // namespace app
} // namespace togo
<|endoftext|> |
<commit_before>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2009-2015 The Regents of
the University of Michigan All rights reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.
* 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.
* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html
* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/
* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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.
*/
// Maintainer: csadorf,samnola
/*! \file CallbackAnalyzer.cc
\brief Defines the CallbackAnalyzer class
*/
#include "CallbackAnalyzer.h"
#include "HOOMDInitializer.h"
#ifdef ENABLE_MPI
#include "Communicator.h"
#endif
#include <boost/python.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
using namespace boost::python;
using namespace boost::filesystem;
#include <iomanip>
using namespace std;
/*! \param sysdef SystemDefinition containing the Particle data to analyze
\param fname File name to write output to
\param header_prefix String to print before the file header
\param overwrite Will overwite an exiting file if true (default is to append)
analyze()
*/
CallbackAnalyzer::CallbackAnalyzer(boost::shared_ptr<SystemDefinition> sysdef,
boost::python::object callback)
: Analyzer(sysdef), callback(callback)
{
m_exec_conf->msg->notice(5) << "Constructing CallbackAnalyzer" << endl;
}
CallbackAnalyzer::~CallbackAnalyzer()
{
m_exec_conf->msg->notice(5) << "Destroying CallbackAnalyzer" << endl;
}
/*!\param timestep Current time step of the simulation
analyze() will call the callback
*/
void CallbackAnalyzer::analyze(unsigned int timestep)
{
callback(timestep);
}
void export_CallbackAnalyzer()
{
class_<CallbackAnalyzer, boost::shared_ptr<CallbackAnalyzer>, bases<Analyzer>, boost::noncopyable>
("CallbackAnalyzer", init< boost::shared_ptr<SystemDefinition>, boost::python::object>())
;
}
<commit_msg>Fixed doxygen documentation.<commit_after>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2009-2015 The Regents of
the University of Michigan All rights reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.
* 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.
* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html
* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/
* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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.
*/
// Maintainer: csadorf,samnola
/*! \file CallbackAnalyzer.cc
\brief Defines the CallbackAnalyzer class
*/
#include "CallbackAnalyzer.h"
#include "HOOMDInitializer.h"
#ifdef ENABLE_MPI
#include "Communicator.h"
#endif
#include <boost/python.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
using namespace boost::python;
using namespace boost::filesystem;
#include <iomanip>
using namespace std;
/*! \param sysdef SystemDefinition containing the Particle data to analyze
\param callback A python functor object to be used as callback
*/
CallbackAnalyzer::CallbackAnalyzer(boost::shared_ptr<SystemDefinition> sysdef,
boost::python::object callback)
: Analyzer(sysdef), callback(callback)
{
m_exec_conf->msg->notice(5) << "Constructing CallbackAnalyzer" << endl;
}
CallbackAnalyzer::~CallbackAnalyzer()
{
m_exec_conf->msg->notice(5) << "Destroying CallbackAnalyzer" << endl;
}
/*!\param timestep Current time step of the simulation
analyze() will call the callback
*/
void CallbackAnalyzer::analyze(unsigned int timestep)
{
callback(timestep);
}
void export_CallbackAnalyzer()
{
class_<CallbackAnalyzer, boost::shared_ptr<CallbackAnalyzer>, bases<Analyzer>, boost::noncopyable>
("CallbackAnalyzer", init< boost::shared_ptr<SystemDefinition>, boost::python::object>())
;
}
<|endoftext|> |
<commit_before>#include "mbed.h"
#include "test_env.h"
class DevNull : public Stream {
public:
DevNull(const char *name = NULL) : Stream(name) {}
protected:
virtual int _getc() {return 0;}
virtual int _putc(int c) {return c;}
};
DevNull null("null");
int main() {
printf("MBED: re-routing stdout to /null\n");
freopen("/null", "w", stdout);
printf("MBED: printf redirected to /null\n"); // This shouldn't appear
// If failure message can be seen test should fail :)
notify_completion(false); // This is 'false' on purpose
return 0;
}
<commit_msg>Indented using AStyle<commit_after>#include "mbed.h"
#include "test_env.h"
class DevNull : public Stream
{
public:
DevNull(const char *name = NULL) : Stream(name) {}
protected:
virtual int _getc() {
return 0;
}
virtual int _putc(int c) {
return c;
}
};
DevNull null("null");
int main()
{
printf("MBED: re-routing stdout to /null\n");
freopen("/null", "w", stdout);
printf("MBED: printf redirected to /null\n"); // This shouldn't appear
// If failure message can be seen test should fail :)
notify_completion(false); // This is 'false' on purpose
return 0;
}
<|endoftext|> |
<commit_before>AliGenerator *AddMCGenAmpt(
Double_t Energy = 2760., // CM energy
Double_t bmin = 0.0, // minimum impact parameter
Double_t bmax = 20.0, // maximum impact parameter
Bool_t stringMelting = kTRUE, // string melting option
Bool_t useART = kTRUE, // use hadronic rescattering phase (ART)
)
{
// User defined generator
gSystem->Load("libampt.so");
gSystem->Load("libTAmpt.so");
AliGenAmpt *genAMPT = new AliGenAmpt(-1);
//=========================================================================
// User settings
Int_t Flag_SM = 4; // flag for string melting: 1 = default, 4 = String Melting
Int_t NTmax = 150; // NTMAX: number of timesteps (Default = 150), to turn off ART set it to 3
Double_t mu = 3.2264; // parton screening mass in fm^(-1) (Default = 3.2264)
Double_t alpha_s = 1./3.; // change mu and alpha_s (Default = 1./3.) to vary scattering cross-section
// mu = 3.2 fm^-1 and alpha_s = 0.33 ==> sigma_{partonic} = 1.5mb
if(!stringMelting)
Flag_SM = 1;
if(!useART)
NTmax = 3;
//=========================================================================
// Decayer
AliDecayer *decayer = new AliDecayerPythia();
genAMPT->SetForceDecay( kHadronicD );
genAMPT->SetDecayer( decayer );
//=========================================================================
// Collision system
genAMPT->SetEnergyCMS(Energy);
genAMPT->SetReferenceFrame("CMS");
genAMPT->SetProjectile("A", 208, 82);
genAMPT->SetTarget ("A", 208, 82);
genAMPT->SetPtHardMin (2);
genAMPT->SetImpactParameterRange(0.00,20.00);
//=========================================================================
// options
genAMPT->SetJetQuenching(0); // enable jet quenching
genAMPT->SetShadowing(1); // enable shadowing
genAMPT->SetDecaysOff(1); // neutral pion and heavy particle decays switched off
genAMPT->SetSpectators(0); // track spectators
genAMPT->SetIsoft(Flag_SM); // 4=string melting, 1=standard AMPT
genAMPT->SetXmu(mu); // parton xsection
genAMPT->SetNtMax(NTmax); // time bins
genAMPT->SetAlpha(alpha_s); // alpha =0.333
genAMPT->SetStringFrag(0.5,0.9); // string fragmentation parameters
genAMPT->SetIpop(1); // enable popcorn mechanism (net-baryon stopping)
//=========================================================================
// Boost into LHC lab frame
genAMPT->SetBoostLHC(1);
// randomize reaction plane
genAMPT->SetRandomReactionPlane(kTRUE);
return genAMPT;
}
<commit_msg>Small fix: - adding impact parameter range as optional<commit_after>AliGenerator *AddMCGenAmpt(
Double_t Energy = 2760., // CM energy
Double_t bmin = 0.0, // minimum impact parameter
Double_t bmax = 20.0, // maximum impact parameter
Bool_t stringMelting = kTRUE, // string melting option
Bool_t useART = kTRUE, // use hadronic rescattering phase (ART)
)
{
// User defined generator
gSystem->Load("libampt.so");
gSystem->Load("libTAmpt.so");
AliGenAmpt *genAMPT = new AliGenAmpt(-1);
//=========================================================================
// User settings
Int_t Flag_SM = 4; // flag for string melting: 1 = default, 4 = String Melting
Int_t NTmax = 150; // NTMAX: number of timesteps (Default = 150), to turn off ART set it to 3
Double_t mu = 3.2264; // parton screening mass in fm^(-1) (Default = 3.2264)
Double_t alpha_s = 1./3.; // change mu and alpha_s (Default = 1./3.) to vary scattering cross-section
// mu = 3.2 fm^-1 and alpha_s = 0.33 ==> sigma_{partonic} = 1.5mb
if(!stringMelting)
Flag_SM = 1;
if(!useART)
NTmax = 3;
//=========================================================================
// Decayer
AliDecayer *decayer = new AliDecayerPythia();
genAMPT->SetForceDecay( kHadronicD );
genAMPT->SetDecayer( decayer );
//=========================================================================
// Collision system
genAMPT->SetEnergyCMS(Energy);
genAMPT->SetReferenceFrame("CMS");
genAMPT->SetProjectile("A", 208, 82);
genAMPT->SetTarget ("A", 208, 82);
genAMPT->SetPtHardMin (2);
genAMPT->SetImpactParameterRange(bmin,bmax);
//=========================================================================
// options
genAMPT->SetJetQuenching(0); // enable jet quenching
genAMPT->SetShadowing(1); // enable shadowing
genAMPT->SetDecaysOff(1); // neutral pion and heavy particle decays switched off
genAMPT->SetSpectators(0); // track spectators
genAMPT->SetIsoft(Flag_SM); // 4=string melting, 1=standard AMPT
genAMPT->SetXmu(mu); // parton xsection
genAMPT->SetNtMax(NTmax); // time bins
genAMPT->SetAlpha(alpha_s); // alpha =0.333
genAMPT->SetStringFrag(0.5,0.9); // string fragmentation parameters
genAMPT->SetIpop(1); // enable popcorn mechanism (net-baryon stopping)
//=========================================================================
// Boost into LHC lab frame
genAMPT->SetBoostLHC(1);
// randomize reaction plane
genAMPT->SetRandomReactionPlane(kTRUE);
return genAMPT;
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <fstream>
#include <map>
#include <sstream>
#include <stdexcept>
#include "cvrp.h"
#include "tsplib_format.h"
namespace VrpSolver {
unsigned int Cvrp::demand(unsigned int node_id) const {
if ((1 > node_id) || (node_id > dimension_))
throw std::out_of_range("error: in Cvrp::demand");
return demands_[node_id];
}
int Cvrp::distance(unsigned int from, unsigned int to) const {
if ((1 > from) || (from > dimension_) ||
(1 > to) || (to > dimension_))
throw std::out_of_range("error: in Cvrp::distance");
const int index = (to > from) ? ((to-2)*(to-1)/2+(from-1)) :
((from-2)*(from-1)/2+(to-1));
return distances_[index];
}
// 文字列strからtrim_char文字列に含まれている文字を削除
void trim(std::string& str, const std::string& trim_char) {
size_t pos;
while ((pos = str.find_first_of(trim_char)) != std::string::npos)
str.erase(pos, 1);
}
// セミコロン以後の文字列(空白の直前まで)を読み取る
std::string get_parameter(std::ifstream& ifs) {
std::string param;
ifs >> param;
while (param == ":") ifs >> param; // ":"は読み飛ばす
return param;
}
enum TsplibKeyword {
NAME, TYPE, COMMENT, DIMENSION, CAPACITY,
EDGE_WEIGHT_TYPE, EDGE_WEIGHT_FORMAT, EDGE_DATA_FORMAT,
NODE_COORD_TYPE, DISPLAY_DATA_TYPE,
NODE_COORD_SECTION, DEPOT_SECTION, DEMAND_SECTION,
EDGE_DATA_SECTION, EDGE_WEIGHT_SECTION,
END_OF_FILE
};
std::map<std::string, TsplibKeyword> keyword_map = {
// The specification part
{ "NAME", NAME },
{ "TYPE", TYPE },
{ "COMMENT", COMMENT },
{ "DIMENSION", DIMENSION },
{ "CAPACITY", CAPACITY },
{ "EDGE_WEIGHT_TYPE", EDGE_WEIGHT_TYPE },
{ "EDGE_WEIGHT_FORMAT", EDGE_WEIGHT_FORMAT },
{ "EDGE_DATA_FORMAT", EDGE_DATA_FORMAT },
{ "NODE_COORD_TYPE", NODE_COORD_TYPE },
{ "DISPLAY_DATA_TYPE", DISPLAY_DATA_TYPE },
{ "EOF", END_OF_FILE },
// The data part
{ "NODE_COORD_SECTION", NODE_COORD_SECTION },
{ "DEPOT_SECTION", DEPOT_SECTION },
{ "DEMAND_SECTION", DEMAND_SECTION },
{ "EDGE_DATA_SECTION", EDGE_DATA_SECTION },
{ "EDGE_WEIGHT_SECTION", EDGE_WEIGHT_SECTION }
};
// infileから情報を読み取りCvrpクラスをセットアップする
void read_vrp(Cvrp& cvrp, const std::string &infile) {
std::ifstream ifs(infile.c_str());
if (!ifs)
throw std::runtime_error("error: can't open file " + infile);
std::string edge_weight_type,
edge_weight_format,
display_data_type;
while (ifs) {
std::string tsp_keyword;
ifs >> tsp_keyword;
if (ifs.eof()) break;
trim(tsp_keyword, " :");
switch (keyword_map[tsp_keyword]) {
// The specification part
case NAME :
cvrp.name_ = get_parameter(ifs);
break;
case TYPE :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case COMMENT :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case DIMENSION :
cvrp.dimension_ = stoi(get_parameter(ifs));
break;
case CAPACITY :
cvrp.capacity_ = stoi(get_parameter(ifs));
break;
case EDGE_WEIGHT_TYPE :
edge_weight_type = get_parameter(ifs);
break;
case EDGE_WEIGHT_FORMAT :
edge_weight_format = get_parameter(ifs);
break;
case EDGE_DATA_FORMAT :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case NODE_COORD_TYPE :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case DISPLAY_DATA_TYPE :
display_data_type = get_parameter(ifs);
break;
case END_OF_FILE :
// do nothing
break;
// The data part
case NODE_COORD_SECTION :
{
int n=0, m, x, y; // m do not use
for (int i=0; i != cvrp.dimension_; i++) {
ifs >> m >> x >> y;
std::pair<int,int> c(x,y);
cvrp.coords_.push_back(c);
}
}
break;
case DEPOT_SECTION :
{
cvrp.depot_ = stoi(get_parameter(ifs));
if (stoi(get_parameter(ifs)) != -1)
throw std::runtime_error("error:"
"can't handle multiple depots");
}
break;
case DEMAND_SECTION :
{
cvrp.demands_.push_back(0); // 0要素目は0にしておく
for (int i=1; i <= cvrp.dimension_; i++) {
unsigned int node_id, demand;
ifs >> node_id >> demand;
if (node_id != i)
throw std::runtime_error("error:"
"DEMAND_SECTION format may be different");
cvrp.demands_.push_back(demand);
}
}
break;
case EDGE_DATA_SECTION :
throw std::runtime_error("Sorry, can not handle 'EDGE_DATA_SECTION'");
break;
case EDGE_WEIGHT_SECTION :
{
if (edge_weight_format != "LOWER_ROW")
throw std::runtime_error("Sorry, can not handle except EDGE_WEIGHT_FORMAT == LOWER_ROW");
for (int i=0; i < cvrp.dimension_; i++) {
for (int j=0; j < i; j++) {
int distance;
ifs >> distance;
cvrp.distances_.push_back(distance);
}
}
}
break;
default :
throw std::runtime_error("error: unknown keyword '" + tsp_keyword + "'");
break;
}
}
// distancesの設定
if (edge_weight_type != Tsplib::EdgeWeightType::EXPLICIT) {
auto& distances = cvrp.distances_;
auto& coords = cvrp.coords_;
for (int i=0; i < cvrp.dimension_; i++) {
for (int j=0; j < i; j++) {
int dx = coords[j].first - coords[i].first;
int dy = coords[j].second - coords[i].second;
distances.push_back(floor(sqrt(dx*dx + dy*dy)+0.5));
}
}
}
}
} // namespace VrpSolver
<commit_msg>if文中のリテラル文字列をenumで置き換えた<commit_after>#include <cmath>
#include <fstream>
#include <map>
#include <sstream>
#include <stdexcept>
#include "cvrp.h"
#include "tsplib_format.h"
namespace VrpSolver {
unsigned int Cvrp::demand(unsigned int node_id) const {
if ((1 > node_id) || (node_id > dimension_))
throw std::out_of_range("error: in Cvrp::demand");
return demands_[node_id];
}
int Cvrp::distance(unsigned int from, unsigned int to) const {
if ((1 > from) || (from > dimension_) ||
(1 > to) || (to > dimension_))
throw std::out_of_range("error: in Cvrp::distance");
const int index = (to > from) ? ((to-2)*(to-1)/2+(from-1)) :
((from-2)*(from-1)/2+(to-1));
return distances_[index];
}
// 文字列strからtrim_char文字列に含まれている文字を削除
void trim(std::string& str, const std::string& trim_char) {
size_t pos;
while ((pos = str.find_first_of(trim_char)) != std::string::npos)
str.erase(pos, 1);
}
// セミコロン以後の文字列(空白の直前まで)を読み取る
std::string get_parameter(std::ifstream& ifs) {
std::string param;
ifs >> param;
while (param == ":") ifs >> param; // ":"は読み飛ばす
return param;
}
enum TsplibKeyword {
NAME, TYPE, COMMENT, DIMENSION, CAPACITY,
EDGE_WEIGHT_TYPE, EDGE_WEIGHT_FORMAT, EDGE_DATA_FORMAT,
NODE_COORD_TYPE, DISPLAY_DATA_TYPE,
NODE_COORD_SECTION, DEPOT_SECTION, DEMAND_SECTION,
EDGE_DATA_SECTION, EDGE_WEIGHT_SECTION,
END_OF_FILE
};
std::map<std::string, TsplibKeyword> keyword_map = {
// The specification part
{ "NAME", NAME },
{ "TYPE", TYPE },
{ "COMMENT", COMMENT },
{ "DIMENSION", DIMENSION },
{ "CAPACITY", CAPACITY },
{ "EDGE_WEIGHT_TYPE", EDGE_WEIGHT_TYPE },
{ "EDGE_WEIGHT_FORMAT", EDGE_WEIGHT_FORMAT },
{ "EDGE_DATA_FORMAT", EDGE_DATA_FORMAT },
{ "NODE_COORD_TYPE", NODE_COORD_TYPE },
{ "DISPLAY_DATA_TYPE", DISPLAY_DATA_TYPE },
{ "EOF", END_OF_FILE },
// The data part
{ "NODE_COORD_SECTION", NODE_COORD_SECTION },
{ "DEPOT_SECTION", DEPOT_SECTION },
{ "DEMAND_SECTION", DEMAND_SECTION },
{ "EDGE_DATA_SECTION", EDGE_DATA_SECTION },
{ "EDGE_WEIGHT_SECTION", EDGE_WEIGHT_SECTION }
};
enum EdgeWeightType {
EXPLICIT, EUC_2D
};
std::map<std::string, EdgeWeightType> ew_type_map = {
{ "EXPLICIT", EXPLICIT },
{ "EUC_2D", EUC_2D }
};
enum EdgeWeightFormat {
LOWER_ROW
};
std::map<std::string, EdgeWeightFormat> ew_format_map = {
{ "LOWER_ROW", LOWER_ROW }
};
// infileから情報を読み取りCvrpクラスをセットアップする
void read_vrp(Cvrp& cvrp, const std::string &infile) {
std::ifstream ifs(infile.c_str());
if (!ifs)
throw std::runtime_error("error: can't open file " + infile);
std::string display_data_type;
EdgeWeightType edge_weight_type;
EdgeWeightFormat edge_weight_format;
while (ifs) {
std::string tsp_keyword;
ifs >> tsp_keyword;
if (ifs.eof()) break;
trim(tsp_keyword, " :");
switch (keyword_map[tsp_keyword]) {
// The specification part
case NAME :
cvrp.name_ = get_parameter(ifs);
break;
case TYPE :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case COMMENT :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case DIMENSION :
cvrp.dimension_ = stoi(get_parameter(ifs));
break;
case CAPACITY :
cvrp.capacity_ = stoi(get_parameter(ifs));
break;
case EDGE_WEIGHT_TYPE :
edge_weight_type = ew_type_map[get_parameter(ifs)];
break;
case EDGE_WEIGHT_FORMAT :
edge_weight_format = ew_format_map[get_parameter(ifs)];
break;
case EDGE_DATA_FORMAT :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case NODE_COORD_TYPE :
{
std::string not_use;
getline(ifs, not_use);
}
break;
case DISPLAY_DATA_TYPE :
display_data_type = get_parameter(ifs);
break;
case END_OF_FILE :
// do nothing
break;
// The data part
case NODE_COORD_SECTION :
{
int n=0, m, x, y; // m do not use
for (int i=0; i != cvrp.dimension_; i++) {
ifs >> m >> x >> y;
std::pair<int,int> c(x,y);
cvrp.coords_.push_back(c);
}
}
break;
case DEPOT_SECTION :
{
cvrp.depot_ = stoi(get_parameter(ifs));
if (stoi(get_parameter(ifs)) != -1)
throw std::runtime_error("error:"
"can't handle multiple depots");
}
break;
case DEMAND_SECTION :
{
cvrp.demands_.push_back(0); // 0要素目は0にしておく
for (int i=1; i <= cvrp.dimension_; i++) {
unsigned int node_id, demand;
ifs >> node_id >> demand;
if (node_id != i)
throw std::runtime_error("error:"
"DEMAND_SECTION format may be different");
cvrp.demands_.push_back(demand);
}
}
break;
case EDGE_DATA_SECTION :
throw std::runtime_error("Sorry, can not handle 'EDGE_DATA_SECTION'");
break;
case EDGE_WEIGHT_SECTION :
{
if (edge_weight_format != LOWER_ROW)
throw std::runtime_error("Sorry, can not handle except EDGE_WEIGHT_FORMAT == LOWER_ROW");
for (int i=0; i < cvrp.dimension_; i++) {
for (int j=0; j < i; j++) {
int distance;
ifs >> distance;
cvrp.distances_.push_back(distance);
}
}
}
break;
default :
throw std::runtime_error("error: unknown keyword '" + tsp_keyword + "'");
break;
}
}
// distancesの設定
if (edge_weight_type != EXPLICIT) {
auto& distances = cvrp.distances_;
auto& coords = cvrp.coords_;
for (int i=0; i < cvrp.dimension_; i++) {
for (int j=0; j < i; j++) {
int dx = coords[j].first - coords[i].first;
int dy = coords[j].second - coords[i].second;
distances.push_back(floor(sqrt(dx*dx + dy*dy)+0.5));
}
}
}
}
} // namespace VrpSolver
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS vgbugs07 (1.47.70); FILE MERGED 2007/06/04 13:34:37 vg 1.47.70.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after><|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS toolbars2 (1.64.4); FILE MERGED 2004/08/30 09:26:19 mav 1.64.4.1: #i26282# replace all filter variable<commit_after><|endoftext|> |
<commit_before><commit_msg>dAllocDontReport() system<commit_after><|endoftext|> |
<commit_before>#include <gtest/gtest.h>
int main(int Fargc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Fix typo<commit_after>#include <gtest/gtest.h>
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>
<commit_msg>Delete nada.cpp<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>
using namespace std;
#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1
typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;
const double eps = 1e-6;
const ll LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;
#define x first
#define y second
#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);
int len;
char str[50];
void Init(){
cin>>len;
scanf("%s",str);
sort(str,str+len);
return ;
}
void Solve(){
int c=0;
do{
printf("%d %s",c++,str);
}while(next_permutation(str,str+len));
return ;
}
int main(){
freopen("uoj17086.in","r",stdin);
Init(),Solve();
return 0;
}<commit_msg>update uoj17086<commit_after>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>
using namespace std;
#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1
typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;
const double eps = 1e-6;
const ll LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;
#define x first
#define y second
#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);
int len;
char str[50];
void Init(){
cin>>len;
scanf("%s",str);
sort(str,str+len);
return ;
}
void Solve(){
int c=0;
do{
printf("%d %s",c++,str);
}while(next_permutation(str,str+len));
return ;
}
int main(){
freopen("uoj17086.in","r",stdin);
Init(),Solve();
return 0;
}<|endoftext|> |
<commit_before>/***********************************************************************
util.cpp - Utility functions required by several of the example
programs.
Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by
MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.
Others may also hold copyrights on code in this file. See the CREDITS
file in the top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include "util.h"
#include <iostream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
const char* kpcSampleDatabase = "mysql_cpp_data";
//// utf8_to_win32_ansi ////////////////////////////////////////////////
// Converts a Unicode string encoded in UTF-8 form (which the MySQL
// database uses) to Win32's ANSI character encoding using the current
// code page. A small modification to this function will turn it into
// a UTF-8 to UCS-2 function, since that's an intermediate form within
// this function. The Unicode chapter in the user manual explains why
// that double conversion is necessary.
#ifdef MYSQLPP_PLATFORM_WINDOWS
static bool
utf8_to_win32_ansi(const char* utf8_str, char* ansi_str,
int ansi_len)
{
wchar_t ucs2_buf[100];
static const int ub_chars = sizeof(ucs2_buf) / sizeof(ucs2_buf[0]);
int err = MultiByteToWideChar(CP_UTF8, 0, utf8_str, -1,
ucs2_buf, ub_chars);
if (err == 0) {
cerr << "Unknown error in Unicode translation: " <<
GetLastError() << endl;
return false;
}
else if (err == ERROR_NO_UNICODE_TRANSLATION) {
cerr << "Bad data in UTF-8 string" << endl;
return false;
}
else {
CPINFOEX cpi;
GetCPInfoEx(CP_OEMCP, 0, &cpi);
WideCharToMultiByte(cpi.CodePage, 0, ucs2_buf, -1,
ansi_str, ansi_len, 0, 0);
cout << ':' << ansi_str[0] << ':' << endl;
return true;
}
}
#endif
//// print_stock_header ////////////////////////////////////////////////
// Display a header suitable for use with print_stock_rows().
void
print_stock_header(int rows)
{
cout << "Records found: " << rows << endl << endl;
cout.setf(ios::left);
cout << setw(21) << "Item" <<
setw(10) << "Num" <<
setw(10) << "Weight" <<
setw(10) << "Price" <<
"Date" << endl << endl;
}
//// print_stock_row ///////////////////////////////////////////////////
// Print out a row of data from the stock table, in a format compatible
// with the header printed out in the previous function.
void
print_stock_row(const std::string& item, mysqlpp::longlong num,
double weight, double price, const mysqlpp::Date& date)
{
// Output item field. We treat it separately because there is
// Unicode data in this field in the sample database.
#ifdef MYSQLPP_PLATFORM_WINDOWS
// We're running on Windows, so convert the first column from UTF-8
// to UCS-2, and then to the local ANSI code page. The user manual
// explains why this double conversion is required.
char item_ansi[100];
if (utf8_to_win32_ansi(item.c_str(), item_ansi, sizeof(item_ansi))) {
cout << setw(20) << item_ansi << ' ';
}
#else
// Just send string to console. On modern Unices, the terminal code
// interprets UTF-8 directly, so no special handling is required.
cout << setw(20) << item << ' ';
#endif
// Output remaining columns
cout << setw(9) << num << ' ' <<
setw(9) << weight << ' ' <<
setw(9) << price << ' ' <<
date << endl;
}
//// print_stock_row ///////////////////////////////////////////////////
// Take a Row from the example 'stock' table, break it up into fields,
// and call the above version of this function.
void
print_stock_row(const mysqlpp::Row& row)
{
// Notice that only the string conversion has to be handled
// specially. (See Row::operator[]'s documentation for the reason.)
// As for the rest of the fields, Row::operator[] returns a ColData
// object, which can convert itself to any standard C type.
//
// We index the row by field name to demonstrate the feature, and
// also because it makes the code more robust in the face of schema
// changes. Use Row::at() instead if efficiency is paramount. To
// maintain efficiency while keeping robustness, use the SSQLS
// feature, demoed in the custom* examples.
string item(row["item"]);
print_stock_row(item, row["num"], row["weight"], row["price"],
row["sdate"]);
}
//// print_stock_rows //////////////////////////////////////////////////
// Print out a number of rows from the example 'stock' table.
void
print_stock_rows(mysqlpp::Result& res)
{
print_stock_header(res.size());
// Use the Result class's read-only random access iterator to walk
// through the query results.
mysqlpp::Result::iterator i;
for (i = res.begin(); i != res.end(); ++i) {
// Notice that a dereferenced result iterator can be converted
// to a Row object, which makes for easier element access.
print_stock_row(*i);
}
}
//// get_stock_table ///////////////////////////////////////////////////
// Retreive the entire contents of the example 'stock' table.
void
get_stock_table(mysqlpp::Query& query, mysqlpp::Result& res)
{
// Reset the query object, in case we're re-using it.
query.reset();
// You can write to the query object like you would any ostream.
query << "select * from stock";
// Show the query string. If you call preview(), it must be before
// you call execute() or store() or use().
cout << "Query: " << query.preview() << endl;
// Execute the query, storing the results in memory.
res = query.store();
}
//// connect_to_db /////////////////////////////////////////////////////
// Establishes a connection to a MySQL database server, optionally
// attaching to database kdb. This is basically a command-line parser
// for the examples, since the example programs' arguments give us the
// information we need to establish the server connection.
bool
connect_to_db(int argc, char *argv[], mysqlpp::Connection& con,
const char *kdb)
{
if (argc < 1) {
cerr << "Bad argument count: " << argc << '!' << endl;
return false;
}
if (!kdb) {
kdb = kpcSampleDatabase;
}
if ((argc > 1) && (argv[1][0] == '-')) {
cout << "usage: " << argv[0] <<
" [host] [user] [password] [port]" << endl;
cout << endl << "\tConnects to database ";
if (strlen(kdb) > 0) {
cout << '"' << kdb << '"';
}
else {
cout << "server";
}
cout << " on localhost using your user" << endl;
cout << "\tname and no password by default." << endl << endl;
return false;
}
if (argc == 1) {
con.connect(kdb);
}
else if (argc == 2) {
con.connect(kdb, argv[1]);
}
else if (argc == 3) {
con.connect(kdb, argv[1], argv[2]);
}
else if (argc == 4) {
con.connect(kdb, argv[1], argv[2], argv[3]);
}
else if (argc >= 5) {
con.connect(kdb, argv[1], argv[2], argv[3], atoi(argv[4]));
}
if (con) {
return true;
}
else {
cerr << "Database connection failed: " << con.error() << endl;
return false;
}
}
<commit_msg>utf8_to_win32_ansi() in util module was printing first char of line between colons before returning converted string for some strange reason. It was probably debug code that made it into the checkin... goes to show how popular the VC++ port is, I guess....<commit_after>/***********************************************************************
util.cpp - Utility functions required by several of the example
programs.
Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by
MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.
Others may also hold copyrights on code in this file. See the CREDITS
file in the top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include "util.h"
#include <iostream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
const char* kpcSampleDatabase = "mysql_cpp_data";
//// utf8_to_win32_ansi ////////////////////////////////////////////////
// Converts a Unicode string encoded in UTF-8 form (which the MySQL
// database uses) to Win32's ANSI character encoding using the current
// code page. A small modification to this function will turn it into
// a UTF-8 to UCS-2 function, since that's an intermediate form within
// this function. The Unicode chapter in the user manual explains why
// that double conversion is necessary.
#ifdef MYSQLPP_PLATFORM_WINDOWS
static bool
utf8_to_win32_ansi(const char* utf8_str, char* ansi_str,
int ansi_len)
{
wchar_t ucs2_buf[100];
static const int ub_chars = sizeof(ucs2_buf) / sizeof(ucs2_buf[0]);
int err = MultiByteToWideChar(CP_UTF8, 0, utf8_str, -1,
ucs2_buf, ub_chars);
if (err == 0) {
cerr << "Unknown error in Unicode translation: " <<
GetLastError() << endl;
return false;
}
else if (err == ERROR_NO_UNICODE_TRANSLATION) {
cerr << "Bad data in UTF-8 string" << endl;
return false;
}
else {
CPINFOEX cpi;
GetCPInfoEx(CP_OEMCP, 0, &cpi);
WideCharToMultiByte(cpi.CodePage, 0, ucs2_buf, -1,
ansi_str, ansi_len, 0, 0);
return true;
}
}
#endif
//// print_stock_header ////////////////////////////////////////////////
// Display a header suitable for use with print_stock_rows().
void
print_stock_header(int rows)
{
cout << "Records found: " << rows << endl << endl;
cout.setf(ios::left);
cout << setw(21) << "Item" <<
setw(10) << "Num" <<
setw(10) << "Weight" <<
setw(10) << "Price" <<
"Date" << endl << endl;
}
//// print_stock_row ///////////////////////////////////////////////////
// Print out a row of data from the stock table, in a format compatible
// with the header printed out in the previous function.
void
print_stock_row(const std::string& item, mysqlpp::longlong num,
double weight, double price, const mysqlpp::Date& date)
{
// Output item field. We treat it separately because there is
// Unicode data in this field in the sample database.
#ifdef MYSQLPP_PLATFORM_WINDOWS
// We're running on Windows, so convert the first column from UTF-8
// to UCS-2, and then to the local ANSI code page. The user manual
// explains why this double conversion is required.
char item_ansi[100];
if (utf8_to_win32_ansi(item.c_str(), item_ansi, sizeof(item_ansi))) {
cout << setw(20) << item_ansi << ' ';
}
#else
// Just send string to console. On modern Unices, the terminal code
// interprets UTF-8 directly, so no special handling is required.
cout << setw(20) << item << ' ';
#endif
// Output remaining columns
cout << setw(9) << num << ' ' <<
setw(9) << weight << ' ' <<
setw(9) << price << ' ' <<
date << endl;
}
//// print_stock_row ///////////////////////////////////////////////////
// Take a Row from the example 'stock' table, break it up into fields,
// and call the above version of this function.
void
print_stock_row(const mysqlpp::Row& row)
{
// Notice that only the string conversion has to be handled
// specially. (See Row::operator[]'s documentation for the reason.)
// As for the rest of the fields, Row::operator[] returns a ColData
// object, which can convert itself to any standard C type.
//
// We index the row by field name to demonstrate the feature, and
// also because it makes the code more robust in the face of schema
// changes. Use Row::at() instead if efficiency is paramount. To
// maintain efficiency while keeping robustness, use the SSQLS
// feature, demoed in the custom* examples.
string item(row["item"]);
print_stock_row(item, row["num"], row["weight"], row["price"],
row["sdate"]);
}
//// print_stock_rows //////////////////////////////////////////////////
// Print out a number of rows from the example 'stock' table.
void
print_stock_rows(mysqlpp::Result& res)
{
print_stock_header(res.size());
// Use the Result class's read-only random access iterator to walk
// through the query results.
mysqlpp::Result::iterator i;
for (i = res.begin(); i != res.end(); ++i) {
// Notice that a dereferenced result iterator can be converted
// to a Row object, which makes for easier element access.
print_stock_row(*i);
}
}
//// get_stock_table ///////////////////////////////////////////////////
// Retreive the entire contents of the example 'stock' table.
void
get_stock_table(mysqlpp::Query& query, mysqlpp::Result& res)
{
// Reset the query object, in case we're re-using it.
query.reset();
// You can write to the query object like you would any ostream.
query << "select * from stock";
// Show the query string. If you call preview(), it must be before
// you call execute() or store() or use().
cout << "Query: " << query.preview() << endl;
// Execute the query, storing the results in memory.
res = query.store();
}
//// connect_to_db /////////////////////////////////////////////////////
// Establishes a connection to a MySQL database server, optionally
// attaching to database kdb. This is basically a command-line parser
// for the examples, since the example programs' arguments give us the
// information we need to establish the server connection.
bool
connect_to_db(int argc, char *argv[], mysqlpp::Connection& con,
const char *kdb)
{
if (argc < 1) {
cerr << "Bad argument count: " << argc << '!' << endl;
return false;
}
if (!kdb) {
kdb = kpcSampleDatabase;
}
if ((argc > 1) && (argv[1][0] == '-')) {
cout << "usage: " << argv[0] <<
" [host] [user] [password] [port]" << endl;
cout << endl << "\tConnects to database ";
if (strlen(kdb) > 0) {
cout << '"' << kdb << '"';
}
else {
cout << "server";
}
cout << " on localhost using your user" << endl;
cout << "\tname and no password by default." << endl << endl;
return false;
}
if (argc == 1) {
con.connect(kdb);
}
else if (argc == 2) {
con.connect(kdb, argv[1]);
}
else if (argc == 3) {
con.connect(kdb, argv[1], argv[2]);
}
else if (argc == 4) {
con.connect(kdb, argv[1], argv[2], argv[3]);
}
else if (argc >= 5) {
con.connect(kdb, argv[1], argv[2], argv[3], atoi(argv[4]));
}
if (con) {
return true;
}
else {
cerr << "Database connection failed: " << con.error() << endl;
return false;
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Exception.h++
*****************************************************************************
* Base class for all exceptions thrown by me, DAC.
*****************************************************************************/
// Include guard.
#if !defined(EXCEPTION_tubu848xo9i)
#define EXCEPTION_tubu848xo9i
// STL includes
#include <exception>
#include <string>
#include <iostream>
// System includes.
#include <demangle.h++>
// Namespace wrapper.
namespace DAC {
/***************************************************************************
* Exception
***************************************************************************
* Base class for all exceptions thrown.
***************************************************************************/
class Exception : public std::exception {
/*
* Public members.
*/
public:
/***********************************************************************/
// Function members.
// Constructor.
Exception () throw();
// Destructor.
virtual ~Exception () throw();
// Get the cause of this error.
virtual char const* what () const throw();
// Get the type of this error.
std::string type () const throw();
// Reset to just-constructed state.
virtual Exception& clear () throw();
};
/*****************************************************************************
* Operators.
*****************************************************************************/
}
// Stream output operator.
std::ostream& operator << (std::ostream& left, DAC::Exception const& right);
namespace DAC {
/***************************************************************************
* Inline and template definitions.
****************************************************************************/
/***************************************************************************/
// Function members.
inline Exception::Exception () throw() { clear(); }
inline Exception::~Exception () throw() { /* Nothing. */ }
inline char const* Exception::what () const throw() { return "Undefined error."; }
inline std::string Exception::type() const throw() { return demangle(*this); }
inline Exception& Exception::clear() throw() { return *this; }
}
// Stream output operator.
inline std::ostream& operator << (std::ostream& left, DAC::Exception const& right) { left << right.what(); return left; }
// End include guard.
#endif
<commit_msg>About to try something dangerous.<commit_after>/*****************************************************************************
* Exception.h++
*****************************************************************************
* Base class for all exceptions thrown by me, DAC.
*****************************************************************************/
// Include guard.
#if !defined(EXCEPTION_tubu848xo9i)
#define EXCEPTION_tubu848xo9i
// STL includes
#include <exception>
#include <string>
#include <iostream>
// System includes.
#include <demangle.h++>
// Namespace wrapper.
namespace DAC {
/***************************************************************************
* Exception
***************************************************************************
* Base class for all exceptions thrown.
***************************************************************************/
class Exception : public std::exception {
/*
* Public members.
*/
public:
/***********************************************************************/
// Function members.
// Constructor.
Exception () throw();
// Destructor.
virtual ~Exception () throw();
// Get the cause of this error.
virtual char const* what () const throw();
// Get the type of this error.
std::string type () const throw();
// Reset to just-constructed state.
virtual Exception& clear () throw();
// Buffer a temporary string.
char const* buffer_message (std::string const& message);
/*
* Private members.
*/
private:
/***********************************************************************/
// Data members.
// Buffer for constructed error messages.
std::string _buffer;
};
/*****************************************************************************
* Operators.
*****************************************************************************/
}
// Stream output operator.
std::ostream& operator << (std::ostream& left, DAC::Exception const& right);
namespace DAC {
/***************************************************************************
* Inline and template definitions.
****************************************************************************/
/***************************************************************************/
// Function members.
inline Exception::Exception () throw() { clear(); }
inline Exception::~Exception () throw() { /* Nothing. */ }
inline char const* Exception::what () const throw() { return "Undefined error."; }
inline std::string Exception::type() const throw() { return demangle(*this); }
inline Exception& Exception::clear() throw() { return *this; }
/*
* Buffer a temporary string.
*/
inline char const* buffer_message (std::string const& message) {
// Swap the contents of the message with the buffer.
_buffer.swap(message);
// Return a pointer to the char array.
return _buffer.c_str();
}
}
// Stream output operator.
inline std::ostream& operator << (std::ostream& left, DAC::Exception const& right) { left << right.what(); return left; }
// End include guard.
#endif
<|endoftext|> |
<commit_before>/************************************************************************/
/* */
/* Copyright 2009 by Ullrich Koethe and Hans Meine */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
#define PY_ARRAY_UNIQUE_SYMBOL vigranumpycore_PyArray_API
#define NO_IMPORT_ARRAY
#include <Python.h>
#include <vigra/matrix.hxx>
#include <vigra/numpy_array.hxx>
#include <vigra/numpy_array_converters.hxx>
#include <boost/python.hpp>
#include <boost/python/to_python_converter.hpp>
namespace python = boost::python;
namespace vigra {
#define VIGRA_NUMPY_TYPECHECKER(type) \
if(python::object((python::detail::new_reference)PyArray_TypeObjectFromType(type)).ptr() == obj) \
return obj;
#define VIGRA_NUMPY_TYPECONVERTER(type) \
if(python::object((python::detail::new_reference)PyArray_TypeObjectFromType(type)).ptr() == obj) \
typeID = type;
struct NumpyTypenumConverter
{
NumpyTypenumConverter()
{
python::converter::registry::insert(&convertible, &construct,
python::type_id<NPY_TYPES>());
python::to_python_converter<NPY_TYPES, NumpyTypenumConverter>();
}
static void* convertible(PyObject* obj)
{
// FIXME: there should be a more elegant way to program this...
if(obj == 0)
return 0;
if(obj->ob_type == &PyArrayDescr_Type)
return obj;
if(!PyType_Check(obj))
return 0;
VIGRA_NUMPY_TYPECHECKER(NPY_BOOL)
VIGRA_NUMPY_TYPECHECKER(NPY_INT8)
VIGRA_NUMPY_TYPECHECKER(NPY_UINT8)
VIGRA_NUMPY_TYPECHECKER(NPY_INT16)
VIGRA_NUMPY_TYPECHECKER(NPY_UINT16)
VIGRA_NUMPY_TYPECHECKER(NPY_INT32)
VIGRA_NUMPY_TYPECHECKER(NPY_UINT32)
VIGRA_NUMPY_TYPECHECKER(NPY_INT)
VIGRA_NUMPY_TYPECHECKER(NPY_UINT)
VIGRA_NUMPY_TYPECHECKER(NPY_INT64)
VIGRA_NUMPY_TYPECHECKER(NPY_UINT64)
VIGRA_NUMPY_TYPECHECKER(NPY_FLOAT32)
VIGRA_NUMPY_TYPECHECKER(NPY_FLOAT64)
VIGRA_NUMPY_TYPECHECKER(NPY_LONGDOUBLE)
VIGRA_NUMPY_TYPECHECKER(NPY_CFLOAT)
VIGRA_NUMPY_TYPECHECKER(NPY_CDOUBLE)
VIGRA_NUMPY_TYPECHECKER(NPY_CLONGDOUBLE)
return 0;
}
// from Python
static void construct(PyObject* obj,
python::converter::rvalue_from_python_stage1_data* data)
{
void* const storage =
((python::converter::rvalue_from_python_storage<NumpyAnyArray>* ) data)->storage.bytes;
// FIXME: there should be a more elegant way to program this...
int typeID = -1;
if(obj->ob_type == &PyArrayDescr_Type)
typeID = (NPY_TYPES)((PyArray_Descr*)obj)->type_num;
VIGRA_NUMPY_TYPECONVERTER(NPY_BOOL)
VIGRA_NUMPY_TYPECONVERTER(NPY_INT8)
VIGRA_NUMPY_TYPECONVERTER(NPY_UINT8)
VIGRA_NUMPY_TYPECONVERTER(NPY_INT16)
VIGRA_NUMPY_TYPECONVERTER(NPY_UINT16)
VIGRA_NUMPY_TYPECONVERTER(NPY_INT32)
VIGRA_NUMPY_TYPECONVERTER(NPY_UINT32)
VIGRA_NUMPY_TYPECONVERTER(NPY_INT)
VIGRA_NUMPY_TYPECONVERTER(NPY_UINT)
VIGRA_NUMPY_TYPECONVERTER(NPY_INT64)
VIGRA_NUMPY_TYPECONVERTER(NPY_UINT64)
VIGRA_NUMPY_TYPECONVERTER(NPY_FLOAT32)
VIGRA_NUMPY_TYPECONVERTER(NPY_FLOAT64)
VIGRA_NUMPY_TYPECONVERTER(NPY_LONGDOUBLE)
VIGRA_NUMPY_TYPECONVERTER(NPY_CFLOAT)
VIGRA_NUMPY_TYPECONVERTER(NPY_CDOUBLE)
VIGRA_NUMPY_TYPECONVERTER(NPY_CLONGDOUBLE)
new (storage) NPY_TYPES((NPY_TYPES)typeID);
data->convertible = storage;
}
// to Python
static PyObject* convert(NPY_TYPES typeID)
{
return PyArray_TypeObjectFromType(typeID);
}
};
#undef VIGRA_NUMPY_TYPECHECKER
#undef VIGRA_NUMPY_TYPECONVERTER
struct NumpyAnyArrayConverter
{
NumpyAnyArrayConverter()
{
python::converter::registry::insert(&convertible, &construct,
python::type_id<NumpyAnyArray>());
python::to_python_converter<NumpyAnyArray, NumpyAnyArrayConverter>();
}
static void* convertible(PyObject* obj)
{
return obj && (obj == Py_None || PyArray_Check(obj))
? obj
: 0;
}
// from Python
static void construct(PyObject* obj,
python::converter::rvalue_from_python_stage1_data* data)
{
void* const storage =
((python::converter::rvalue_from_python_storage<NumpyAnyArray>* ) data)->storage.bytes;
if(obj == Py_None)
obj = 0;
new (storage) NumpyAnyArray(obj);
data->convertible = storage;
}
static PyObject* convert(NumpyAnyArray const& a)
{
return returnNumpyArray(a);
}
};
namespace detail {
template <int N, class T>
struct MultiArrayShapeConverterTraits
{
typedef TinyVector<T, N> ShapeType;
static void construct(void* const storage, PyObject * obj)
{
ShapeType * shape = new (storage) ShapeType();
for(int i=0; i<PySequence_Length(obj); ++i)
(*shape)[i] = python::extract<T>(PySequence_ITEM(obj, i));
}
};
template <class T>
struct MultiArrayShapeConverterTraits<0, T>
{
typedef ArrayVector<T> ShapeType;
static void construct(void* const storage, PyObject * obj)
{
int len = (obj == Py_None)
? 0
: PySequence_Length(obj);
ShapeType * shape = new (storage) ShapeType(len);
for(int i=0; i<len; ++i)
(*shape)[i] = python::extract<T>(PySequence_ITEM(obj, i));
}
};
} // namespace detail
template <int M, class T>
struct MultiArrayShapeConverter
{
typedef typename detail::MultiArrayShapeConverterTraits<M, T>::ShapeType ShapeType;
MultiArrayShapeConverter()
{
python::converter::registry::insert(&convertible, &construct,
python::type_id<ShapeType>());
python::to_python_converter<ShapeType, MultiArrayShapeConverter>();
}
static void* convertible(PyObject* obj)
{
if(obj == 0)
return 0;
if(M == 0 && obj == Py_None)
return obj;
if(!PySequence_Check(obj) || (M != 0 && PySequence_Length(obj) != M))
return 0;
for(int i=0; i<PySequence_Length(obj); ++i)
if(!PyNumber_Check(PySequence_ITEM(obj, i)))
return 0;
return obj;
}
// from Python
static void construct(PyObject* obj,
python::converter::rvalue_from_python_stage1_data* data)
{
void* const storage =
((python::converter::rvalue_from_python_storage<ShapeType>* ) data)->storage.bytes;
detail::MultiArrayShapeConverterTraits<M, T>::construct(storage, obj);
data->convertible = storage;
}
// to Python
static PyObject* convert(ShapeType const& shape)
{
return shapeToPythonTuple(shape).release();
}
};
python_ptr point2DToPythonTuple(Point2D const & point)
{
python_ptr tuple(PyTuple_New(2), python_ptr::keep_count);
pythonToCppException(tuple);
PyTuple_SET_ITEM((PyTupleObject *)tuple.get(), 0 ,pythonFromData(point.x).release());
PyTuple_SET_ITEM((PyTupleObject *)tuple.get(), 1 ,pythonFromData(point.y).release());
return tuple;
}
struct Point2DConverter
{
Point2DConverter()
{
python::converter::registry::insert(&convertible, &construct,
python::type_id<Point2D>());
python::to_python_converter<Point2D, Point2DConverter>();
}
static void* convertible(PyObject* obj)
{
if(obj == 0 || !PySequence_Check(obj) || (PySequence_Length(obj) !=2))
return 0;
if(!PyNumber_Check(PySequence_Fast_GET_ITEM(obj,0)))
return 0;
if(!PyNumber_Check(PySequence_Fast_GET_ITEM(obj,0)))
return 0;
return obj;
}
//from python
static void construct(PyObject* obj, python::converter::rvalue_from_python_stage1_data* data)
{
void* const storage =
((python::converter::rvalue_from_python_storage<Point2D>*) data)->storage.bytes;
new (storage) Point2D(python::extract<int>(PySequence_Fast_GET_ITEM(obj,0)),
python::extract<int>(PySequence_Fast_GET_ITEM(obj,1)));
data->convertible = storage;
}
//to python
static PyObject* convert(Point2D const& p)
{
return point2DToPythonTuple(p).release();
}
};
void registerNumpyPoint2DConverter()
{
Point2DConverter();
}
template <class T>
void registerNumpyShapeConvertersOneType()
{
MultiArrayShapeConverter<0, T>();
MultiArrayShapeConverter<1, T>();
MultiArrayShapeConverter<2, T>();
MultiArrayShapeConverter<3, T>();
MultiArrayShapeConverter<4, T>();
MultiArrayShapeConverter<5, T>();
MultiArrayShapeConverter<6, T>();
MultiArrayShapeConverter<7, T>();
}
void registerNumpyShapeConvertersAllTypes()
{
registerNumpyShapeConvertersOneType<MultiArrayIndex>();
registerNumpyShapeConvertersOneType<float>();
registerNumpyShapeConvertersOneType<double>();
if(typeid(npy_intp) != typeid(MultiArrayIndex))
MultiArrayShapeConverter<0, npy_intp>();
}
#if 0 // FIXME: reimplement to replace the Python versions for consistence?
PyObject *
constructNumpyArrayFromShape(python::object type, ArrayVector<npy_intp> const & shape,
unsigned int spatialDimensions, unsigned int channels,
NPY_TYPES typeCode, std::string order, bool init)
{
PyObject * obj = type.ptr();
vigra_precondition(obj && PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, &PyArray_Type),
"constructNumpyArray(type, ...): first argument was not an array type.");
return detail::constructNumpyArrayImpl((PyTypeObject *)obj, shape, spatialDimensions, channels, typeCode, order, init).release();
}
PyObject *
constructNumpyArrayFromArray(python::object type, NumpyAnyArray array,
unsigned int spatialDimensions, unsigned int channels,
NPY_TYPES typeCode, std::string order, bool init)
{
PyObject * obj = type.ptr();
vigra_precondition(obj && PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, &PyArray_Type),
"constructNumpyArray(type, ...): first argument was not an array type.");
PyObject * res = detail::constructNumpyArrayImpl((PyTypeObject *)obj, array.shape(), spatialDimensions, channels,
typeCode, order, false, array.strideOrdering()).release();
if(init)
{
NumpyAnyArray lhs(res);
lhs = array;
}
return res;
}
#endif
PyObject *
constructArrayFromAxistags(python::object type, ArrayVector<npy_intp> const & shape,
NPY_TYPES typeCode, AxisTags const & axistags, bool init)
{
PyAxisTags pyaxistags(python_ptr(python::object(axistags).ptr()));
ArrayVector<npy_intp> norm_shape(shape);
if(pyaxistags.size() > 0)
{
ArrayVector<npy_intp> permutation(pyaxistags.permutationToNormalOrder());
applyPermutation(permutation.begin(), permutation.end(), shape.begin(), norm_shape.begin());
}
TaggedShape tagged_shape(norm_shape, pyaxistags);
// FIXME: check that type is an array class?
return constructArray(tagged_shape, typeCode, init, python_ptr(type.ptr()));
}
template <class T>
struct MatrixConverter
{
typedef linalg::Matrix<T> ArrayType;
MatrixConverter();
// to Python
static PyObject* convert(ArrayType const& a)
{
return returnNumpyArray(NumpyArray<2, T>(a));
}
};
template <class T>
MatrixConverter<T>::MatrixConverter()
{
using namespace boost::python;
converter::registration const * reg = converter::registry::query(type_id<ArrayType>());
// register the to_python_converter only once
if(!reg || !reg->rvalue_chain)
{
to_python_converter<ArrayType, MatrixConverter>();
}
}
void registerNumpyArrayConverters()
{
NumpyTypenumConverter();
registerNumpyShapeConvertersAllTypes();
registerNumpyPoint2DConverter();
NumpyAnyArrayConverter();
MatrixConverter<float>();
MatrixConverter<double>();
python::docstring_options doc_options(true, true, false);
doc_options.disable_all();
python::def("constructArrayFromAxistags", &constructArrayFromAxistags);
// python::def("constructNumpyArray", &constructNumpyArrayFromArray);
}
} // namespace vigra
<commit_msg>export TinyVector with short type, too<commit_after>/************************************************************************/
/* */
/* Copyright 2009 by Ullrich Koethe and Hans Meine */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
#define PY_ARRAY_UNIQUE_SYMBOL vigranumpycore_PyArray_API
#define NO_IMPORT_ARRAY
#include <Python.h>
#include <vigra/matrix.hxx>
#include <vigra/numpy_array.hxx>
#include <vigra/numpy_array_converters.hxx>
#include <boost/python.hpp>
#include <boost/python/to_python_converter.hpp>
namespace python = boost::python;
namespace vigra {
#define VIGRA_NUMPY_TYPECHECKER(type) \
if(python::object((python::detail::new_reference)PyArray_TypeObjectFromType(type)).ptr() == obj) \
return obj;
#define VIGRA_NUMPY_TYPECONVERTER(type) \
if(python::object((python::detail::new_reference)PyArray_TypeObjectFromType(type)).ptr() == obj) \
typeID = type;
struct NumpyTypenumConverter
{
NumpyTypenumConverter()
{
python::converter::registry::insert(&convertible, &construct,
python::type_id<NPY_TYPES>());
python::to_python_converter<NPY_TYPES, NumpyTypenumConverter>();
}
static void* convertible(PyObject* obj)
{
// FIXME: there should be a more elegant way to program this...
if(obj == 0)
return 0;
if(obj->ob_type == &PyArrayDescr_Type)
return obj;
if(!PyType_Check(obj))
return 0;
VIGRA_NUMPY_TYPECHECKER(NPY_BOOL)
VIGRA_NUMPY_TYPECHECKER(NPY_INT8)
VIGRA_NUMPY_TYPECHECKER(NPY_UINT8)
VIGRA_NUMPY_TYPECHECKER(NPY_INT16)
VIGRA_NUMPY_TYPECHECKER(NPY_UINT16)
VIGRA_NUMPY_TYPECHECKER(NPY_INT32)
VIGRA_NUMPY_TYPECHECKER(NPY_UINT32)
VIGRA_NUMPY_TYPECHECKER(NPY_INT)
VIGRA_NUMPY_TYPECHECKER(NPY_UINT)
VIGRA_NUMPY_TYPECHECKER(NPY_INT64)
VIGRA_NUMPY_TYPECHECKER(NPY_UINT64)
VIGRA_NUMPY_TYPECHECKER(NPY_FLOAT32)
VIGRA_NUMPY_TYPECHECKER(NPY_FLOAT64)
VIGRA_NUMPY_TYPECHECKER(NPY_LONGDOUBLE)
VIGRA_NUMPY_TYPECHECKER(NPY_CFLOAT)
VIGRA_NUMPY_TYPECHECKER(NPY_CDOUBLE)
VIGRA_NUMPY_TYPECHECKER(NPY_CLONGDOUBLE)
return 0;
}
// from Python
static void construct(PyObject* obj,
python::converter::rvalue_from_python_stage1_data* data)
{
void* const storage =
((python::converter::rvalue_from_python_storage<NumpyAnyArray>* ) data)->storage.bytes;
// FIXME: there should be a more elegant way to program this...
int typeID = -1;
if(obj->ob_type == &PyArrayDescr_Type)
typeID = (NPY_TYPES)((PyArray_Descr*)obj)->type_num;
VIGRA_NUMPY_TYPECONVERTER(NPY_BOOL)
VIGRA_NUMPY_TYPECONVERTER(NPY_INT8)
VIGRA_NUMPY_TYPECONVERTER(NPY_UINT8)
VIGRA_NUMPY_TYPECONVERTER(NPY_INT16)
VIGRA_NUMPY_TYPECONVERTER(NPY_UINT16)
VIGRA_NUMPY_TYPECONVERTER(NPY_INT32)
VIGRA_NUMPY_TYPECONVERTER(NPY_UINT32)
VIGRA_NUMPY_TYPECONVERTER(NPY_INT)
VIGRA_NUMPY_TYPECONVERTER(NPY_UINT)
VIGRA_NUMPY_TYPECONVERTER(NPY_INT64)
VIGRA_NUMPY_TYPECONVERTER(NPY_UINT64)
VIGRA_NUMPY_TYPECONVERTER(NPY_FLOAT32)
VIGRA_NUMPY_TYPECONVERTER(NPY_FLOAT64)
VIGRA_NUMPY_TYPECONVERTER(NPY_LONGDOUBLE)
VIGRA_NUMPY_TYPECONVERTER(NPY_CFLOAT)
VIGRA_NUMPY_TYPECONVERTER(NPY_CDOUBLE)
VIGRA_NUMPY_TYPECONVERTER(NPY_CLONGDOUBLE)
new (storage) NPY_TYPES((NPY_TYPES)typeID);
data->convertible = storage;
}
// to Python
static PyObject* convert(NPY_TYPES typeID)
{
return PyArray_TypeObjectFromType(typeID);
}
};
#undef VIGRA_NUMPY_TYPECHECKER
#undef VIGRA_NUMPY_TYPECONVERTER
struct NumpyAnyArrayConverter
{
NumpyAnyArrayConverter()
{
python::converter::registry::insert(&convertible, &construct,
python::type_id<NumpyAnyArray>());
python::to_python_converter<NumpyAnyArray, NumpyAnyArrayConverter>();
}
static void* convertible(PyObject* obj)
{
return obj && (obj == Py_None || PyArray_Check(obj))
? obj
: 0;
}
// from Python
static void construct(PyObject* obj,
python::converter::rvalue_from_python_stage1_data* data)
{
void* const storage =
((python::converter::rvalue_from_python_storage<NumpyAnyArray>* ) data)->storage.bytes;
if(obj == Py_None)
obj = 0;
new (storage) NumpyAnyArray(obj);
data->convertible = storage;
}
static PyObject* convert(NumpyAnyArray const& a)
{
return returnNumpyArray(a);
}
};
namespace detail {
template <int N, class T>
struct MultiArrayShapeConverterTraits
{
typedef TinyVector<T, N> ShapeType;
static void construct(void* const storage, PyObject * obj)
{
ShapeType * shape = new (storage) ShapeType();
for(int i=0; i<PySequence_Length(obj); ++i)
(*shape)[i] = python::extract<T>(PySequence_ITEM(obj, i));
}
};
template <class T>
struct MultiArrayShapeConverterTraits<0, T>
{
typedef ArrayVector<T> ShapeType;
static void construct(void* const storage, PyObject * obj)
{
int len = (obj == Py_None)
? 0
: PySequence_Length(obj);
ShapeType * shape = new (storage) ShapeType(len);
for(int i=0; i<len; ++i)
(*shape)[i] = python::extract<T>(PySequence_ITEM(obj, i));
}
};
} // namespace detail
template <int M, class T>
struct MultiArrayShapeConverter
{
typedef typename detail::MultiArrayShapeConverterTraits<M, T>::ShapeType ShapeType;
MultiArrayShapeConverter()
{
python::converter::registry::insert(&convertible, &construct,
python::type_id<ShapeType>());
python::to_python_converter<ShapeType, MultiArrayShapeConverter>();
}
static void* convertible(PyObject* obj)
{
if(obj == 0)
return 0;
if(M == 0 && obj == Py_None)
return obj;
if(!PySequence_Check(obj) || (M != 0 && PySequence_Length(obj) != M))
return 0;
for(int i=0; i<PySequence_Length(obj); ++i)
if(!PyNumber_Check(PySequence_ITEM(obj, i)))
return 0;
return obj;
}
// from Python
static void construct(PyObject* obj,
python::converter::rvalue_from_python_stage1_data* data)
{
void* const storage =
((python::converter::rvalue_from_python_storage<ShapeType>* ) data)->storage.bytes;
detail::MultiArrayShapeConverterTraits<M, T>::construct(storage, obj);
data->convertible = storage;
}
// to Python
static PyObject* convert(ShapeType const& shape)
{
return shapeToPythonTuple(shape).release();
}
};
python_ptr point2DToPythonTuple(Point2D const & point)
{
python_ptr tuple(PyTuple_New(2), python_ptr::keep_count);
pythonToCppException(tuple);
PyTuple_SET_ITEM((PyTupleObject *)tuple.get(), 0 ,pythonFromData(point.x).release());
PyTuple_SET_ITEM((PyTupleObject *)tuple.get(), 1 ,pythonFromData(point.y).release());
return tuple;
}
struct Point2DConverter
{
Point2DConverter()
{
python::converter::registry::insert(&convertible, &construct,
python::type_id<Point2D>());
python::to_python_converter<Point2D, Point2DConverter>();
}
static void* convertible(PyObject* obj)
{
if(obj == 0 || !PySequence_Check(obj) || (PySequence_Length(obj) !=2))
return 0;
if(!PyNumber_Check(PySequence_Fast_GET_ITEM(obj,0)))
return 0;
if(!PyNumber_Check(PySequence_Fast_GET_ITEM(obj,0)))
return 0;
return obj;
}
//from python
static void construct(PyObject* obj, python::converter::rvalue_from_python_stage1_data* data)
{
void* const storage =
((python::converter::rvalue_from_python_storage<Point2D>*) data)->storage.bytes;
new (storage) Point2D(python::extract<int>(PySequence_Fast_GET_ITEM(obj,0)),
python::extract<int>(PySequence_Fast_GET_ITEM(obj,1)));
data->convertible = storage;
}
//to python
static PyObject* convert(Point2D const& p)
{
return point2DToPythonTuple(p).release();
}
};
void registerNumpyPoint2DConverter()
{
Point2DConverter();
}
template <class T>
void registerNumpyShapeConvertersOneType()
{
MultiArrayShapeConverter<0, T>();
MultiArrayShapeConverter<1, T>();
MultiArrayShapeConverter<2, T>();
MultiArrayShapeConverter<3, T>();
MultiArrayShapeConverter<4, T>();
MultiArrayShapeConverter<5, T>();
MultiArrayShapeConverter<6, T>();
MultiArrayShapeConverter<7, T>();
}
void registerNumpyShapeConvertersAllTypes()
{
registerNumpyShapeConvertersOneType<MultiArrayIndex>();
registerNumpyShapeConvertersOneType<float>();
registerNumpyShapeConvertersOneType<double>();
registerNumpyShapeConvertersOneType<short>();
if(typeid(npy_intp) != typeid(MultiArrayIndex))
MultiArrayShapeConverter<0, npy_intp>();
}
#if 0 // FIXME: reimplement to replace the Python versions for consistence?
PyObject *
constructNumpyArrayFromShape(python::object type, ArrayVector<npy_intp> const & shape,
unsigned int spatialDimensions, unsigned int channels,
NPY_TYPES typeCode, std::string order, bool init)
{
PyObject * obj = type.ptr();
vigra_precondition(obj && PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, &PyArray_Type),
"constructNumpyArray(type, ...): first argument was not an array type.");
return detail::constructNumpyArrayImpl((PyTypeObject *)obj, shape, spatialDimensions, channels, typeCode, order, init).release();
}
PyObject *
constructNumpyArrayFromArray(python::object type, NumpyAnyArray array,
unsigned int spatialDimensions, unsigned int channels,
NPY_TYPES typeCode, std::string order, bool init)
{
PyObject * obj = type.ptr();
vigra_precondition(obj && PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, &PyArray_Type),
"constructNumpyArray(type, ...): first argument was not an array type.");
PyObject * res = detail::constructNumpyArrayImpl((PyTypeObject *)obj, array.shape(), spatialDimensions, channels,
typeCode, order, false, array.strideOrdering()).release();
if(init)
{
NumpyAnyArray lhs(res);
lhs = array;
}
return res;
}
#endif
PyObject *
constructArrayFromAxistags(python::object type, ArrayVector<npy_intp> const & shape,
NPY_TYPES typeCode, AxisTags const & axistags, bool init)
{
PyAxisTags pyaxistags(python_ptr(python::object(axistags).ptr()));
ArrayVector<npy_intp> norm_shape(shape);
if(pyaxistags.size() > 0)
{
ArrayVector<npy_intp> permutation(pyaxistags.permutationToNormalOrder());
applyPermutation(permutation.begin(), permutation.end(), shape.begin(), norm_shape.begin());
}
TaggedShape tagged_shape(norm_shape, pyaxistags);
// FIXME: check that type is an array class?
return constructArray(tagged_shape, typeCode, init, python_ptr(type.ptr()));
}
template <class T>
struct MatrixConverter
{
typedef linalg::Matrix<T> ArrayType;
MatrixConverter();
// to Python
static PyObject* convert(ArrayType const& a)
{
return returnNumpyArray(NumpyArray<2, T>(a));
}
};
template <class T>
MatrixConverter<T>::MatrixConverter()
{
using namespace boost::python;
converter::registration const * reg = converter::registry::query(type_id<ArrayType>());
// register the to_python_converter only once
if(!reg || !reg->rvalue_chain)
{
to_python_converter<ArrayType, MatrixConverter>();
}
}
void registerNumpyArrayConverters()
{
NumpyTypenumConverter();
registerNumpyShapeConvertersAllTypes();
registerNumpyPoint2DConverter();
NumpyAnyArrayConverter();
MatrixConverter<float>();
MatrixConverter<double>();
python::docstring_options doc_options(true, true, false);
doc_options.disable_all();
python::def("constructArrayFromAxistags", &constructArrayFromAxistags);
// python::def("constructNumpyArray", &constructNumpyArrayFromArray);
}
} // namespace vigra
<|endoftext|> |
<commit_before>#include <cstring>
#include <cassert>
#include <string>
#include <atomic>
#include <memory>
#include <set>
#include <boost/asio.hpp>
#include <mutex>
#include "I2PService.h"
#include "Destination.h"
#include "HTTPProxy.h"
#include "util.h"
#include "Identity.h"
#include "Streaming.h"
#include "Destination.h"
#include "ClientContext.h"
#include "I2PEndian.h"
#include "I2PTunnel.h"
#include "Config.h"
#include "HTTP.h"
namespace i2p {
namespace proxy {
bool str_rmatch(std::string & str, const char *suffix) {
auto pos = str.rfind (suffix);
if (pos == std::string::npos)
return false; /* not found */
if (str.length() == (pos + std::strlen(suffix)))
return true; /* match */
return false;
}
static const size_t http_buffer_size = 8192;
class HTTPReqHandler: public i2p::client::I2PServiceHandler, public std::enable_shared_from_this<HTTPReqHandler>
{
private:
enum state
{
GET_METHOD,
GET_HOSTNAME,
GET_HTTPV,
GET_HTTPVNL, //TODO: fallback to finding HOst: header if needed
DONE
};
void EnterState(state nstate);
bool HandleData(uint8_t *http_buff, std::size_t len);
void HandleSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered);
void Terminate();
void AsyncSockRead();
void HTTPRequestFailed(const char *message);
void RedirectToJumpService(std::string & host);
bool ValidateHTTPRequest();
bool ExtractAddressHelper(i2p::http::URL & url, std::string & b64);
bool CreateHTTPRequest(uint8_t *http_buff, std::size_t len);
void SentHTTPFailed(const boost::system::error_code & ecode);
void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream);
uint8_t m_http_buff[http_buffer_size];
std::shared_ptr<boost::asio::ip::tcp::socket> m_sock;
std::string m_request; //Data left to be sent
std::string m_url; //URL
std::string m_method; //Method
std::string m_version; //HTTP version
std::string m_address; //Address
std::string m_path; //Path
int m_port; //Port
state m_state;//Parsing state
public:
HTTPReqHandler(HTTPProxy * parent, std::shared_ptr<boost::asio::ip::tcp::socket> sock) :
I2PServiceHandler(parent), m_sock(sock)
{ EnterState(GET_METHOD); }
~HTTPReqHandler() { Terminate(); }
void Handle () { AsyncSockRead(); }
};
void HTTPReqHandler::AsyncSockRead()
{
LogPrint(eLogDebug, "HTTPProxy: async sock read");
if (!m_sock) {
LogPrint(eLogError, "HTTPProxy: no socket for read");
return;
}
m_sock->async_receive(boost::asio::buffer(m_http_buff, http_buffer_size),
std::bind(&HTTPReqHandler::HandleSockRecv, shared_from_this(),
std::placeholders::_1, std::placeholders::_2));
}
void HTTPReqHandler::Terminate() {
if (Kill()) return;
if (m_sock)
{
LogPrint(eLogDebug, "HTTPProxy: close sock");
m_sock->close();
m_sock = nullptr;
}
Done(shared_from_this());
}
/* All hope is lost beyond this point */
//TODO: handle this apropriately
void HTTPReqHandler::HTTPRequestFailed(const char *message)
{
i2p::http::HTTPRes res;
res.code = 500;
res.add_header("Content-Type", "text/plain");
res.add_header("Connection", "close");
res.body = message;
res.body += "\r\n";
std::string response = res.to_string();
boost::asio::async_write(*m_sock, boost::asio::buffer(response),
std::bind(&HTTPReqHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1));
}
void HTTPReqHandler::RedirectToJumpService(std::string & host)
{
i2p::http::HTTPRes res;
i2p::http::URL url;
/* TODO: don't redirect to webconsole, it's not always work, handle jumpservices here */
i2p::config::GetOption("http.address", url.host);
i2p::config::GetOption("http.port", url.port);
url.schema = "http";
url.path = "/";
url.query = "page=jumpservices&address=";
url.query += host;
res.code = 302; /* redirect */
res.add_header("Location", url.to_string().c_str());
res.add_header("Connection", "close");
std::string response = res.to_string();
boost::asio::async_write(*m_sock, boost::asio::buffer(response),
std::bind(&HTTPReqHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1));
}
void HTTPReqHandler::EnterState(HTTPReqHandler::state nstate)
{
m_state = nstate;
}
bool HTTPReqHandler::ValidateHTTPRequest()
{
if ( m_version != "HTTP/1.0" && m_version != "HTTP/1.1" )
{
LogPrint(eLogError, "HTTPProxy: unsupported version: ", m_version);
HTTPRequestFailed("unsupported HTTP version");
return false;
}
return true;
}
bool HTTPReqHandler::ExtractAddressHelper(i2p::http::URL & url, std::string & b64)
{
const char *param = "i2paddresshelper=";
std::size_t pos = url.query.find(param);
std::size_t len = std::strlen(param);
std::map<std::string, std::string> params;
if (pos == std::string::npos)
return false; /* not found */
if (!url.parse_query(params))
return false;
std::string value = params["i2paddresshelper"];
len += value.length();
b64 = i2p::http::UrlDecode(value);
url.query.replace(pos, len, "");
return true;
}
bool HTTPReqHandler::CreateHTTPRequest(uint8_t *http_buff, std::size_t len)
{
std::string b64;
i2p::http::URL url;
url.parse(m_url);
m_address = url.host; /* < compatibility */
m_port = url.port; /* < compatibility */
if (!m_port) {
m_port = (url.schema == "https") ? 443 : 80;
}
url.schema = "";
url.host = "";
m_path = url.to_string(); /* < compatibility */
if (!ValidateHTTPRequest()) return false;
/* TODO: notify user */
if (ExtractAddressHelper(url, b64)) {
i2p::client::context.GetAddressBook ().InsertAddress (url.host, b64);
LogPrint (eLogInfo, "HTTPProxy: added b64 from addresshelper for ", url.host, " to address book");
}
i2p::data::IdentHash identHash;
if (str_rmatch(m_address, ".i2p"))
{
if (!i2p::client::context.GetAddressBook ().GetIdentHash (m_address, identHash)){
RedirectToJumpService(m_address);
return false;
}
}
m_request = m_method;
m_request.push_back(' ');
m_request += m_path;
m_request.push_back(' ');
m_request += m_version;
m_request.push_back('\r');
m_request.push_back('\n');
m_request.append("Connection: close\r\n");
// TODO: temporary shortcut. Must be implemented properly
uint8_t * eol = nullptr;
bool isEndOfHeader = false;
while (!isEndOfHeader && len && (eol = (uint8_t *)memchr (http_buff, '\r', len)))
{
if (eol)
{
*eol = 0; eol++;
if (strncmp ((const char *)http_buff, "Referer", 7) && strncmp ((const char *)http_buff, "Connection", 10)) // strip out referer and connection
{
if (!strncmp ((const char *)http_buff, "User-Agent", 10)) // replace UserAgent
m_request.append("User-Agent: MYOB/6.66 (AN/ON)");
else
m_request.append ((const char *)http_buff);
m_request.append ("\r\n");
}
isEndOfHeader = !http_buff[0];
auto l = eol - http_buff;
http_buff = eol;
len -= l;
if (len > 0) // \r
{
http_buff++;
len--;
}
}
}
m_request.append(reinterpret_cast<const char *>(http_buff),len);
return true;
}
bool HTTPReqHandler::HandleData(uint8_t *http_buff, std::size_t len)
{
while (len > 0)
{
//TODO: fallback to finding HOst: header if needed
switch (m_state)
{
case GET_METHOD:
switch (*http_buff)
{
case ' ': EnterState(GET_HOSTNAME); break;
default: m_method.push_back(*http_buff); break;
}
break;
case GET_HOSTNAME:
switch (*http_buff)
{
case ' ': EnterState(GET_HTTPV); break;
default: m_url.push_back(*http_buff); break;
}
break;
case GET_HTTPV:
switch (*http_buff)
{
case '\r': EnterState(GET_HTTPVNL); break;
default: m_version.push_back(*http_buff); break;
}
break;
case GET_HTTPVNL:
switch (*http_buff)
{
case '\n': EnterState(DONE); break;
default:
LogPrint(eLogError, "HTTPProxy: rejected invalid request ending with: ", ((int)*http_buff));
HTTPRequestFailed("rejected invalid request");
return false;
}
break;
default:
LogPrint(eLogError, "HTTPProxy: invalid state: ", m_state);
HTTPRequestFailed("invalid parser state");
return false;
}
http_buff++;
len--;
if (m_state == DONE)
return CreateHTTPRequest(http_buff,len);
}
return true;
}
void HTTPReqHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len)
{
LogPrint(eLogDebug, "HTTPProxy: sock recv: ", len, " bytes");
if(ecode)
{
LogPrint(eLogWarning, "HTTPProxy: sock recv got error: ", ecode);
Terminate();
return;
}
if (HandleData(m_http_buff, len))
{
if (m_state == DONE)
{
LogPrint(eLogDebug, "HTTPProxy: requested: ", m_url);
GetOwner()->CreateStream (std::bind (&HTTPReqHandler::HandleStreamRequestComplete,
shared_from_this(), std::placeholders::_1), m_address, m_port);
}
else
AsyncSockRead();
}
}
void HTTPReqHandler::SentHTTPFailed(const boost::system::error_code & ecode)
{
if (ecode)
LogPrint (eLogError, "HTTPProxy: Closing socket after sending failure because: ", ecode.message ());
Terminate();
}
void HTTPReqHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream)
{
if (!stream) {
LogPrint (eLogError, "HTTPProxy: error when creating the stream, check the previous warnings for more info");
HTTPRequestFailed("error when creating the stream, check logs");
return;
}
if (Kill())
return;
LogPrint (eLogDebug, "HTTPProxy: New I2PTunnel connection");
auto connection = std::make_shared<i2p::client::I2PTunnelConnection>(GetOwner(), m_sock, stream);
GetOwner()->AddHandler (connection);
connection->I2PConnect (reinterpret_cast<const uint8_t*>(m_request.data()), m_request.size());
Done (shared_from_this());
}
HTTPProxy::HTTPProxy(const std::string& address, int port, std::shared_ptr<i2p::client::ClientDestination> localDestination):
TCPIPAcceptor(address, port, localDestination ? localDestination : i2p::client::context.GetSharedLocalDestination ())
{
}
std::shared_ptr<i2p::client::I2PServiceHandler> HTTPProxy::CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket)
{
return std::make_shared<HTTPReqHandler> (this, socket);
}
} // http
} // i2p
<commit_msg>* HTTPProxy.cpp : rename variable<commit_after>#include <cstring>
#include <cassert>
#include <string>
#include <atomic>
#include <memory>
#include <set>
#include <boost/asio.hpp>
#include <mutex>
#include "I2PService.h"
#include "Destination.h"
#include "HTTPProxy.h"
#include "util.h"
#include "Identity.h"
#include "Streaming.h"
#include "Destination.h"
#include "ClientContext.h"
#include "I2PEndian.h"
#include "I2PTunnel.h"
#include "Config.h"
#include "HTTP.h"
namespace i2p {
namespace proxy {
bool str_rmatch(std::string & str, const char *suffix) {
auto pos = str.rfind (suffix);
if (pos == std::string::npos)
return false; /* not found */
if (str.length() == (pos + std::strlen(suffix)))
return true; /* match */
return false;
}
class HTTPReqHandler: public i2p::client::I2PServiceHandler, public std::enable_shared_from_this<HTTPReqHandler>
{
private:
enum state
{
GET_METHOD,
GET_HOSTNAME,
GET_HTTPV,
GET_HTTPVNL, //TODO: fallback to finding HOst: header if needed
DONE
};
void EnterState(state nstate);
bool HandleData(uint8_t *http_buff, std::size_t len);
void HandleSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered);
void Terminate();
void AsyncSockRead();
void HTTPRequestFailed(const char *message);
void RedirectToJumpService(std::string & host);
bool ValidateHTTPRequest();
bool ExtractAddressHelper(i2p::http::URL & url, std::string & b64);
bool CreateHTTPRequest(uint8_t *http_buff, std::size_t len);
void SentHTTPFailed(const boost::system::error_code & ecode);
void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream);
uint8_t m_recv_buf[8192];
std::string m_request; //Data left to be sent. TODO: rename to m_send_buf
std::shared_ptr<boost::asio::ip::tcp::socket> m_sock;
std::string m_url; //URL
std::string m_method; //Method
std::string m_version; //HTTP version
std::string m_address; //Address
std::string m_path; //Path
int m_port; //Port
state m_state;//Parsing state
public:
HTTPReqHandler(HTTPProxy * parent, std::shared_ptr<boost::asio::ip::tcp::socket> sock) :
I2PServiceHandler(parent), m_sock(sock)
{ EnterState(GET_METHOD); }
~HTTPReqHandler() { Terminate(); }
void Handle () { AsyncSockRead(); }
};
void HTTPReqHandler::AsyncSockRead()
{
LogPrint(eLogDebug, "HTTPProxy: async sock read");
if (!m_sock) {
LogPrint(eLogError, "HTTPProxy: no socket for read");
return;
}
m_sock->async_receive(boost::asio::buffer(m_recv_buf, sizeof(m_recv_buf)),
std::bind(&HTTPReqHandler::HandleSockRecv, shared_from_this(),
std::placeholders::_1, std::placeholders::_2));
}
void HTTPReqHandler::Terminate() {
if (Kill()) return;
if (m_sock)
{
LogPrint(eLogDebug, "HTTPProxy: close sock");
m_sock->close();
m_sock = nullptr;
}
Done(shared_from_this());
}
/* All hope is lost beyond this point */
//TODO: handle this apropriately
void HTTPReqHandler::HTTPRequestFailed(const char *message)
{
i2p::http::HTTPRes res;
res.code = 500;
res.add_header("Content-Type", "text/plain");
res.add_header("Connection", "close");
res.body = message;
res.body += "\r\n";
std::string response = res.to_string();
boost::asio::async_write(*m_sock, boost::asio::buffer(response),
std::bind(&HTTPReqHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1));
}
void HTTPReqHandler::RedirectToJumpService(std::string & host)
{
i2p::http::HTTPRes res;
i2p::http::URL url;
/* TODO: don't redirect to webconsole, it's not always work, handle jumpservices here */
i2p::config::GetOption("http.address", url.host);
i2p::config::GetOption("http.port", url.port);
url.schema = "http";
url.path = "/";
url.query = "page=jumpservices&address=";
url.query += host;
res.code = 302; /* redirect */
res.add_header("Location", url.to_string().c_str());
res.add_header("Connection", "close");
std::string response = res.to_string();
boost::asio::async_write(*m_sock, boost::asio::buffer(response),
std::bind(&HTTPReqHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1));
}
void HTTPReqHandler::EnterState(HTTPReqHandler::state nstate)
{
m_state = nstate;
}
bool HTTPReqHandler::ValidateHTTPRequest()
{
if ( m_version != "HTTP/1.0" && m_version != "HTTP/1.1" )
{
LogPrint(eLogError, "HTTPProxy: unsupported version: ", m_version);
HTTPRequestFailed("unsupported HTTP version");
return false;
}
return true;
}
bool HTTPReqHandler::ExtractAddressHelper(i2p::http::URL & url, std::string & b64)
{
const char *param = "i2paddresshelper=";
std::size_t pos = url.query.find(param);
std::size_t len = std::strlen(param);
std::map<std::string, std::string> params;
if (pos == std::string::npos)
return false; /* not found */
if (!url.parse_query(params))
return false;
std::string value = params["i2paddresshelper"];
len += value.length();
b64 = i2p::http::UrlDecode(value);
url.query.replace(pos, len, "");
return true;
}
bool HTTPReqHandler::CreateHTTPRequest(uint8_t *http_buff, std::size_t len)
{
std::string b64;
i2p::http::URL url;
url.parse(m_url);
m_address = url.host; /* < compatibility */
m_port = url.port; /* < compatibility */
if (!m_port) {
m_port = (url.schema == "https") ? 443 : 80;
}
url.schema = "";
url.host = "";
m_path = url.to_string(); /* < compatibility */
if (!ValidateHTTPRequest()) return false;
/* TODO: notify user */
if (ExtractAddressHelper(url, b64)) {
i2p::client::context.GetAddressBook ().InsertAddress (url.host, b64);
LogPrint (eLogInfo, "HTTPProxy: added b64 from addresshelper for ", url.host, " to address book");
}
i2p::data::IdentHash identHash;
if (str_rmatch(m_address, ".i2p"))
{
if (!i2p::client::context.GetAddressBook ().GetIdentHash (m_address, identHash)){
RedirectToJumpService(m_address);
return false;
}
}
m_request = m_method;
m_request.push_back(' ');
m_request += m_path;
m_request.push_back(' ');
m_request += m_version;
m_request.push_back('\r');
m_request.push_back('\n');
m_request.append("Connection: close\r\n");
// TODO: temporary shortcut. Must be implemented properly
uint8_t * eol = nullptr;
bool isEndOfHeader = false;
while (!isEndOfHeader && len && (eol = (uint8_t *)memchr (http_buff, '\r', len)))
{
if (eol)
{
*eol = 0; eol++;
if (strncmp ((const char *)http_buff, "Referer", 7) && strncmp ((const char *)http_buff, "Connection", 10)) // strip out referer and connection
{
if (!strncmp ((const char *)http_buff, "User-Agent", 10)) // replace UserAgent
m_request.append("User-Agent: MYOB/6.66 (AN/ON)");
else
m_request.append ((const char *)http_buff);
m_request.append ("\r\n");
}
isEndOfHeader = !http_buff[0];
auto l = eol - http_buff;
http_buff = eol;
len -= l;
if (len > 0) // \r
{
http_buff++;
len--;
}
}
}
m_request.append(reinterpret_cast<const char *>(http_buff),len);
return true;
}
bool HTTPReqHandler::HandleData(uint8_t *http_buff, std::size_t len)
{
while (len > 0)
{
//TODO: fallback to finding HOst: header if needed
switch (m_state)
{
case GET_METHOD:
switch (*http_buff)
{
case ' ': EnterState(GET_HOSTNAME); break;
default: m_method.push_back(*http_buff); break;
}
break;
case GET_HOSTNAME:
switch (*http_buff)
{
case ' ': EnterState(GET_HTTPV); break;
default: m_url.push_back(*http_buff); break;
}
break;
case GET_HTTPV:
switch (*http_buff)
{
case '\r': EnterState(GET_HTTPVNL); break;
default: m_version.push_back(*http_buff); break;
}
break;
case GET_HTTPVNL:
switch (*http_buff)
{
case '\n': EnterState(DONE); break;
default:
LogPrint(eLogError, "HTTPProxy: rejected invalid request ending with: ", ((int)*http_buff));
HTTPRequestFailed("rejected invalid request");
return false;
}
break;
default:
LogPrint(eLogError, "HTTPProxy: invalid state: ", m_state);
HTTPRequestFailed("invalid parser state");
return false;
}
http_buff++;
len--;
if (m_state == DONE)
return CreateHTTPRequest(http_buff,len);
}
return true;
}
void HTTPReqHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len)
{
LogPrint(eLogDebug, "HTTPProxy: sock recv: ", len, " bytes");
if(ecode)
{
LogPrint(eLogWarning, "HTTPProxy: sock recv got error: ", ecode);
Terminate();
return;
}
if (HandleData(m_recv_buf, len))
{
if (m_state == DONE)
{
LogPrint(eLogDebug, "HTTPProxy: requested: ", m_url);
GetOwner()->CreateStream (std::bind (&HTTPReqHandler::HandleStreamRequestComplete,
shared_from_this(), std::placeholders::_1), m_address, m_port);
}
else
AsyncSockRead();
}
}
void HTTPReqHandler::SentHTTPFailed(const boost::system::error_code & ecode)
{
if (ecode)
LogPrint (eLogError, "HTTPProxy: Closing socket after sending failure because: ", ecode.message ());
Terminate();
}
void HTTPReqHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream)
{
if (!stream) {
LogPrint (eLogError, "HTTPProxy: error when creating the stream, check the previous warnings for more info");
HTTPRequestFailed("error when creating the stream, check logs");
return;
}
if (Kill())
return;
LogPrint (eLogDebug, "HTTPProxy: New I2PTunnel connection");
auto connection = std::make_shared<i2p::client::I2PTunnelConnection>(GetOwner(), m_sock, stream);
GetOwner()->AddHandler (connection);
connection->I2PConnect (reinterpret_cast<const uint8_t*>(m_request.data()), m_request.size());
Done (shared_from_this());
}
HTTPProxy::HTTPProxy(const std::string& address, int port, std::shared_ptr<i2p::client::ClientDestination> localDestination):
TCPIPAcceptor(address, port, localDestination ? localDestination : i2p::client::context.GetSharedLocalDestination ())
{
}
std::shared_ptr<i2p::client::I2PServiceHandler> HTTPProxy::CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket)
{
return std::make_shared<HTTPReqHandler> (this, socket);
}
} // http
} // i2p
<|endoftext|> |
<commit_before>#include <boost/bind.hpp>
#include "base64.h"
#include "Log.h"
#include "NetDb.h"
#include "I2PTunnel.h"
namespace i2p
{
namespace stream
{
I2PTunnelConnection::I2PTunnelConnection (I2PTunnel * owner,
boost::asio::ip::tcp::socket * socket, const i2p::data::LeaseSet * leaseSet):
m_Socket (socket), m_Owner (owner)
{
m_Stream = m_Owner->GetLocalDestination ()->CreateNewOutgoingStream (*leaseSet);
m_Stream->Send (m_Buffer, 0); // connect
StreamReceive ();
Receive ();
}
I2PTunnelConnection::I2PTunnelConnection (I2PTunnel * owner, Stream * stream,
boost::asio::ip::tcp::socket * socket, const boost::asio::ip::tcp::endpoint& target):
m_Socket (socket), m_Stream (stream), m_Owner (owner)
{
if (m_Socket)
m_Socket->async_connect (target, boost::bind (&I2PTunnelConnection::HandleConnect,
this, boost::asio::placeholders::error));
}
I2PTunnelConnection::~I2PTunnelConnection ()
{
if (m_Stream)
{
m_Stream->Close ();
DeleteStream (m_Stream);
m_Stream = nullptr;
}
delete m_Socket;
}
void I2PTunnelConnection::Terminate ()
{
m_Socket->close ();
if (m_Owner)
m_Owner->RemoveConnection (this);
// TODO: delete
}
void I2PTunnelConnection::Receive ()
{
m_Socket->async_read_some (boost::asio::buffer(m_Buffer, I2P_TUNNEL_CONNECTION_BUFFER_SIZE),
boost::bind(&I2PTunnelConnection::HandleReceived, this,
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
void I2PTunnelConnection::HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (ecode)
{
LogPrint ("I2PTunnel read error: ", ecode.message ());
m_Stream->Close ();
Terminate ();
}
else
{
if (m_Stream)
m_Stream->Send (m_Buffer, bytes_transferred);
Receive ();
}
}
void I2PTunnelConnection::HandleWrite (const boost::system::error_code& ecode)
{
if (ecode)
{
LogPrint ("I2PTunnel write error: ", ecode.message ());
m_Stream->Close ();
Terminate ();
}
else
StreamReceive ();
}
void I2PTunnelConnection::StreamReceive ()
{
if (m_Stream)
m_Stream->AsyncReceive (boost::asio::buffer (m_StreamBuffer, I2P_TUNNEL_CONNECTION_BUFFER_SIZE),
boost::bind (&I2PTunnelConnection::HandleStreamReceive, this,
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred),
I2P_TUNNEL_CONNECTION_MAX_IDLE);
}
void I2PTunnelConnection::HandleStreamReceive (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (ecode)
{
LogPrint ("I2PTunnel stream read error: ", ecode.message ());
Terminate ();
}
else
{
boost::asio::async_write (*m_Socket, boost::asio::buffer (m_StreamBuffer, bytes_transferred),
boost::bind (&I2PTunnelConnection::HandleWrite, this, boost::asio::placeholders::error));
}
}
void I2PTunnelConnection::HandleConnect (const boost::system::error_code& ecode)
{
if (ecode)
{
LogPrint ("I2PTunnel connect error: ", ecode.message ());
if (m_Stream) m_Stream->Close ();
DeleteStream (m_Stream);
m_Stream = nullptr;
}
else
{
LogPrint ("I2PTunnel connected");
StreamReceive ();
Receive ();
}
}
void I2PTunnel::AddConnection (I2PTunnelConnection * conn)
{
m_Connections.insert (conn);
}
void I2PTunnel::RemoveConnection (I2PTunnelConnection * conn)
{
m_Connections.erase (conn);
}
void I2PTunnel::ClearConnections ()
{
for (auto it: m_Connections)
delete it;
m_Connections.clear ();
}
I2PClientTunnel::I2PClientTunnel (boost::asio::io_service& service, const std::string& destination,
int port, StreamingDestination * localDestination):
I2PTunnel (service, localDestination ? localDestination : GetSharedLocalDestination ()),
m_Acceptor (service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port)),
m_Destination (destination), m_DestinationIdentHash (nullptr), m_RemoteLeaseSet (nullptr)
{
}
I2PClientTunnel::~I2PClientTunnel ()
{
Stop ();
}
void I2PClientTunnel::Start ()
{
i2p::data::IdentHash identHash;
if (i2p::data::netdb.GetAddressBook ().GetIdentHash (m_Destination, identHash))
m_DestinationIdentHash = new i2p::data::IdentHash (identHash);
if (m_DestinationIdentHash)
{
i2p::data::netdb.Subscribe (*m_DestinationIdentHash, GetLocalDestination ()->GetTunnelPool ());
m_RemoteLeaseSet = i2p::data::netdb.FindLeaseSet (*m_DestinationIdentHash);
}
else
LogPrint ("I2PTunnel unknown destination ", m_Destination);
m_Acceptor.listen ();
Accept ();
}
void I2PClientTunnel::Stop ()
{
m_Acceptor.close();
ClearConnections ();
m_DestinationIdentHash = nullptr;
}
void I2PClientTunnel::Accept ()
{
auto newSocket = new boost::asio::ip::tcp::socket (GetService ());
m_Acceptor.async_accept (*newSocket, boost::bind (&I2PClientTunnel::HandleAccept, this,
boost::asio::placeholders::error, newSocket));
}
void I2PClientTunnel::HandleAccept (const boost::system::error_code& ecode, boost::asio::ip::tcp::socket * socket)
{
if (!ecode)
{
if (!m_RemoteLeaseSet)
{
// try to get it
if (m_DestinationIdentHash)
m_RemoteLeaseSet = i2p::data::netdb.FindLeaseSet (*m_DestinationIdentHash);
else
{
i2p::data::IdentHash identHash;
if (i2p::data::netdb.GetAddressBook ().GetIdentHash (m_Destination, identHash))
{
m_DestinationIdentHash = new i2p::data::IdentHash (identHash);
i2p::data::netdb.Subscribe (*m_DestinationIdentHash, GetSharedLocalDestination ()->GetTunnelPool ());
}
}
}
if (m_RemoteLeaseSet) // leaseSet found
{
LogPrint ("New I2PTunnel connection");
auto connection = new I2PTunnelConnection (this, socket, m_RemoteLeaseSet);
AddConnection (connection);
}
else
{
LogPrint ("LeaseSet for I2PTunnel destination not found");
delete socket;
}
Accept ();
}
else
delete socket;
}
I2PServerTunnel::I2PServerTunnel (boost::asio::io_service& service, const std::string& address, int port,
StreamingDestination * localDestination): I2PTunnel (service, localDestination),
m_Endpoint (boost::asio::ip::address::from_string (address), port)
{
}
void I2PServerTunnel::Start ()
{
Accept ();
}
void I2PServerTunnel::Stop ()
{
ClearConnections ();
}
void I2PServerTunnel::Accept ()
{
auto localDestination = GetLocalDestination ();
if (localDestination)
localDestination->SetAcceptor (std::bind (&I2PServerTunnel::HandleAccept, this, std::placeholders::_1));
else
LogPrint ("Local destination not set for server tunnel");
}
void I2PServerTunnel::HandleAccept (i2p::stream::Stream * stream)
{
if (stream)
new I2PTunnelConnection (this, stream, new boost::asio::ip::tcp::socket (GetService ()), m_Endpoint);
}
}
}
<commit_msg>use own pool for request of destination of new I2P client tunnel<commit_after>#include <boost/bind.hpp>
#include "base64.h"
#include "Log.h"
#include "NetDb.h"
#include "I2PTunnel.h"
namespace i2p
{
namespace stream
{
I2PTunnelConnection::I2PTunnelConnection (I2PTunnel * owner,
boost::asio::ip::tcp::socket * socket, const i2p::data::LeaseSet * leaseSet):
m_Socket (socket), m_Owner (owner)
{
m_Stream = m_Owner->GetLocalDestination ()->CreateNewOutgoingStream (*leaseSet);
m_Stream->Send (m_Buffer, 0); // connect
StreamReceive ();
Receive ();
}
I2PTunnelConnection::I2PTunnelConnection (I2PTunnel * owner, Stream * stream,
boost::asio::ip::tcp::socket * socket, const boost::asio::ip::tcp::endpoint& target):
m_Socket (socket), m_Stream (stream), m_Owner (owner)
{
if (m_Socket)
m_Socket->async_connect (target, boost::bind (&I2PTunnelConnection::HandleConnect,
this, boost::asio::placeholders::error));
}
I2PTunnelConnection::~I2PTunnelConnection ()
{
if (m_Stream)
{
m_Stream->Close ();
DeleteStream (m_Stream);
m_Stream = nullptr;
}
delete m_Socket;
}
void I2PTunnelConnection::Terminate ()
{
m_Socket->close ();
if (m_Owner)
m_Owner->RemoveConnection (this);
// TODO: delete
}
void I2PTunnelConnection::Receive ()
{
m_Socket->async_read_some (boost::asio::buffer(m_Buffer, I2P_TUNNEL_CONNECTION_BUFFER_SIZE),
boost::bind(&I2PTunnelConnection::HandleReceived, this,
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
void I2PTunnelConnection::HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (ecode)
{
LogPrint ("I2PTunnel read error: ", ecode.message ());
m_Stream->Close ();
Terminate ();
}
else
{
if (m_Stream)
m_Stream->Send (m_Buffer, bytes_transferred);
Receive ();
}
}
void I2PTunnelConnection::HandleWrite (const boost::system::error_code& ecode)
{
if (ecode)
{
LogPrint ("I2PTunnel write error: ", ecode.message ());
m_Stream->Close ();
Terminate ();
}
else
StreamReceive ();
}
void I2PTunnelConnection::StreamReceive ()
{
if (m_Stream)
m_Stream->AsyncReceive (boost::asio::buffer (m_StreamBuffer, I2P_TUNNEL_CONNECTION_BUFFER_SIZE),
boost::bind (&I2PTunnelConnection::HandleStreamReceive, this,
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred),
I2P_TUNNEL_CONNECTION_MAX_IDLE);
}
void I2PTunnelConnection::HandleStreamReceive (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (ecode)
{
LogPrint ("I2PTunnel stream read error: ", ecode.message ());
Terminate ();
}
else
{
boost::asio::async_write (*m_Socket, boost::asio::buffer (m_StreamBuffer, bytes_transferred),
boost::bind (&I2PTunnelConnection::HandleWrite, this, boost::asio::placeholders::error));
}
}
void I2PTunnelConnection::HandleConnect (const boost::system::error_code& ecode)
{
if (ecode)
{
LogPrint ("I2PTunnel connect error: ", ecode.message ());
if (m_Stream) m_Stream->Close ();
DeleteStream (m_Stream);
m_Stream = nullptr;
}
else
{
LogPrint ("I2PTunnel connected");
StreamReceive ();
Receive ();
}
}
void I2PTunnel::AddConnection (I2PTunnelConnection * conn)
{
m_Connections.insert (conn);
}
void I2PTunnel::RemoveConnection (I2PTunnelConnection * conn)
{
m_Connections.erase (conn);
}
void I2PTunnel::ClearConnections ()
{
for (auto it: m_Connections)
delete it;
m_Connections.clear ();
}
I2PClientTunnel::I2PClientTunnel (boost::asio::io_service& service, const std::string& destination,
int port, StreamingDestination * localDestination):
I2PTunnel (service, localDestination ? localDestination : GetSharedLocalDestination ()),
m_Acceptor (service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port)),
m_Destination (destination), m_DestinationIdentHash (nullptr), m_RemoteLeaseSet (nullptr)
{
}
I2PClientTunnel::~I2PClientTunnel ()
{
Stop ();
}
void I2PClientTunnel::Start ()
{
i2p::data::IdentHash identHash;
if (i2p::data::netdb.GetAddressBook ().GetIdentHash (m_Destination, identHash))
m_DestinationIdentHash = new i2p::data::IdentHash (identHash);
if (m_DestinationIdentHash)
{
i2p::data::netdb.Subscribe (*m_DestinationIdentHash, GetLocalDestination ()->GetTunnelPool ());
m_RemoteLeaseSet = i2p::data::netdb.FindLeaseSet (*m_DestinationIdentHash);
}
else
LogPrint ("I2PTunnel unknown destination ", m_Destination);
m_Acceptor.listen ();
Accept ();
}
void I2PClientTunnel::Stop ()
{
m_Acceptor.close();
ClearConnections ();
m_DestinationIdentHash = nullptr;
}
void I2PClientTunnel::Accept ()
{
auto newSocket = new boost::asio::ip::tcp::socket (GetService ());
m_Acceptor.async_accept (*newSocket, boost::bind (&I2PClientTunnel::HandleAccept, this,
boost::asio::placeholders::error, newSocket));
}
void I2PClientTunnel::HandleAccept (const boost::system::error_code& ecode, boost::asio::ip::tcp::socket * socket)
{
if (!ecode)
{
if (!m_RemoteLeaseSet)
{
// try to get it
if (m_DestinationIdentHash)
m_RemoteLeaseSet = i2p::data::netdb.FindLeaseSet (*m_DestinationIdentHash);
else
{
i2p::data::IdentHash identHash;
if (i2p::data::netdb.GetAddressBook ().GetIdentHash (m_Destination, identHash))
{
m_DestinationIdentHash = new i2p::data::IdentHash (identHash);
i2p::data::netdb.Subscribe (*m_DestinationIdentHash, GetLocalDestination ()->GetTunnelPool ());
}
}
}
if (m_RemoteLeaseSet) // leaseSet found
{
LogPrint ("New I2PTunnel connection");
auto connection = new I2PTunnelConnection (this, socket, m_RemoteLeaseSet);
AddConnection (connection);
}
else
{
LogPrint ("LeaseSet for I2PTunnel destination not found");
delete socket;
}
Accept ();
}
else
delete socket;
}
I2PServerTunnel::I2PServerTunnel (boost::asio::io_service& service, const std::string& address, int port,
StreamingDestination * localDestination): I2PTunnel (service, localDestination),
m_Endpoint (boost::asio::ip::address::from_string (address), port)
{
}
void I2PServerTunnel::Start ()
{
Accept ();
}
void I2PServerTunnel::Stop ()
{
ClearConnections ();
}
void I2PServerTunnel::Accept ()
{
auto localDestination = GetLocalDestination ();
if (localDestination)
localDestination->SetAcceptor (std::bind (&I2PServerTunnel::HandleAccept, this, std::placeholders::_1));
else
LogPrint ("Local destination not set for server tunnel");
}
void I2PServerTunnel::HandleAccept (i2p::stream::Stream * stream)
{
if (stream)
new I2PTunnelConnection (this, stream, new boost::asio::ip::tcp::socket (GetService ()), m_Endpoint);
}
}
}
<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2011
\file rdoprocess.inl
\author (dluschan@rk9.bmstu.ru)
\date 24.07.2011
\brief
\indent 4T
*/
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo.h"
#include "simulator/runtime/rdo_runtime.h"
#include "simulator/runtime/rdoprocess_i.h"
#include "simulator/runtime/rdo_logic.h"
// --------------------------------------------------------------------------------
OPEN_RDO_RUNTIME_NAMESPACE
// --------------------------------------------------------------------------------
// -------------------- RDOPROCBlock
// --------------------------------------------------------------------------------
inline RDOPROCBlock::~RDOPROCBlock()
{}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCTransact
// --------------------------------------------------------------------------------
inline LPRDOPROCResource RDOPROCTransact::getRes()
{
return m_res;
}
inline void RDOPROCTransact::setRes(CREF(LPRDOPROCResource) pResource)
{
m_res = pResource;
}
inline REF(LPIPROCBlock) RDOPROCTransact::getBlock()
{
return m_block;
}
inline void RDOPROCTransact::setBlock(CREF(LPIPROCBlock) block)
{
m_block = block;
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCResource
// --------------------------------------------------------------------------------
inline tstring RDOPROCResource::whoAreYou()
{
return "procRes";
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCGenerate
// --------------------------------------------------------------------------------
inline RDOPROCGenerate::RDOPROCGenerate(LPIPROCProcess process, CREF(LPRDOCalc) pTime, int maxTransCount)
: RDOPROCBlock (process )
, timeNext (0 )
, pTimeCalc (pTime )
, m_maxTransCount(maxTransCount)
{
m_TransCount = 0;
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCQueue
// --------------------------------------------------------------------------------
inline RDOPROCQueue::RDOPROCQueue(LPIPROCProcess process, parser_for_Queue From_Par)
: RDOPROCBlockForQueue(process, From_Par)
{}
inline ruint RDOPROCQueue::getDefaultValue()
{
return 0;
}
inline tstring RDOPROCQueue::getQueueParamName()
{
return "_";
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCDepart
// --------------------------------------------------------------------------------
inline RDOPROCDepart::RDOPROCDepart(LPIPROCProcess process, parser_for_Queue From_Par)
: RDOPROCBlockForQueue(process, From_Par)
{}
inline ruint RDOPROCDepart::getDefaultValue()
{
return 0;
}
inline tstring RDOPROCDepart::getDepartParamName()
{
return "_";
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCBlockForSeize
// --------------------------------------------------------------------------------
inline tstring RDOPROCBlockForSeize::getStateParamName()
{
return "";
}
inline tstring RDOPROCBlockForSeize::getStateEnumFree()
{
return "";
}
inline tstring RDOPROCBlockForSeize::getStateEnumBuzy()
{
return "";
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCSeize
// --------------------------------------------------------------------------------
inline RDOPROCSeize::RDOPROCSeize(LPIPROCProcess process, std::vector<parser_for_Seize> From_Par)
: RDOPROCBlockForSeize(process, From_Par)
{
static ruint g_index = 1;
index = g_index++;
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCRelease
// --------------------------------------------------------------------------------
inline RDOPROCRelease::RDOPROCRelease(LPIPROCProcess process, std::vector<parser_for_Seize> From_Par)
: RDOPROCBlockForSeize(process, From_Par)
{
static ruint g_index = 1;
index = g_index++;
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCAdvance
// --------------------------------------------------------------------------------
inline RDOPROCAdvance::RDOPROCAdvance(LPIPROCProcess process, CREF(LPRDOCalc) _pDelayCalc)
: RDOPROCBlock(process )
, pDelayCalc (_pDelayCalc)
{}
inline RDOPROCAdvance::LeaveTr::LeaveTr(CREF(LPRDOPROCTransact) _transact, double _timeLeave)
: transact (_transact )
, timeLeave(_timeLeave)
{}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCTerminate
// --------------------------------------------------------------------------------
inline RDOPROCTerminate::RDOPROCTerminate(LPIPROCProcess process, ruint _term)
: RDOPROCBlock(process)
, term (_term )
{}
inline int RDOPROCTerminate::getTerm()
{
return term;
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCAssign
// --------------------------------------------------------------------------------
inline RDOPROCAssign::RDOPROCAssign(LPIPROCProcess process, CREF(LPRDOCalc) pValue, int Id_res, int Id_param)
: RDOPROCBlock(process )
, pParamValue (pValue )
, t_resId (Id_res )
, t_parId (Id_param)
{}
CLOSE_RDO_RUNTIME_NAMESPACE
<commit_msg> - форматирование<commit_after>/*!
\copyright (c) RDO-Team, 2011
\file rdoprocess.inl
\author (dluschan@rk9.bmstu.ru)
\date 24.07.2011
\brief
\indent 4T
*/
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo.h"
#include "simulator/runtime/rdo_runtime.h"
#include "simulator/runtime/rdoprocess_i.h"
#include "simulator/runtime/rdo_logic.h"
// --------------------------------------------------------------------------------
OPEN_RDO_RUNTIME_NAMESPACE
// --------------------------------------------------------------------------------
// -------------------- RDOPROCBlock
// --------------------------------------------------------------------------------
inline RDOPROCBlock::~RDOPROCBlock()
{}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCTransact
// --------------------------------------------------------------------------------
inline LPRDOPROCResource RDOPROCTransact::getRes()
{
return m_res;
}
inline void RDOPROCTransact::setRes(CREF(LPRDOPROCResource) pResource)
{
m_res = pResource;
}
inline REF(LPIPROCBlock) RDOPROCTransact::getBlock()
{
return m_block;
}
inline void RDOPROCTransact::setBlock(CREF(LPIPROCBlock) block)
{
m_block = block;
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCResource
// --------------------------------------------------------------------------------
inline tstring RDOPROCResource::whoAreYou()
{
return "procRes";
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCGenerate
// --------------------------------------------------------------------------------
inline RDOPROCGenerate::RDOPROCGenerate(LPIPROCProcess process, CREF(LPRDOCalc) pTime, int maxTransCount)
: RDOPROCBlock (process )
, timeNext (0.0 )
, pTimeCalc (pTime )
, m_maxTransCount(maxTransCount)
{
m_TransCount = 0;
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCQueue
// --------------------------------------------------------------------------------
inline RDOPROCQueue::RDOPROCQueue(LPIPROCProcess process, parser_for_Queue From_Par)
: RDOPROCBlockForQueue(process, From_Par)
{}
inline ruint RDOPROCQueue::getDefaultValue()
{
return 0;
}
inline tstring RDOPROCQueue::getQueueParamName()
{
return "_";
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCDepart
// --------------------------------------------------------------------------------
inline RDOPROCDepart::RDOPROCDepart(LPIPROCProcess process, parser_for_Queue From_Par)
: RDOPROCBlockForQueue(process, From_Par)
{}
inline ruint RDOPROCDepart::getDefaultValue()
{
return 0;
}
inline tstring RDOPROCDepart::getDepartParamName()
{
return "_";
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCBlockForSeize
// --------------------------------------------------------------------------------
inline tstring RDOPROCBlockForSeize::getStateParamName()
{
return "";
}
inline tstring RDOPROCBlockForSeize::getStateEnumFree()
{
return "";
}
inline tstring RDOPROCBlockForSeize::getStateEnumBuzy()
{
return "";
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCSeize
// --------------------------------------------------------------------------------
inline RDOPROCSeize::RDOPROCSeize(LPIPROCProcess process, std::vector<parser_for_Seize> From_Par)
: RDOPROCBlockForSeize(process, From_Par)
{
static ruint g_index = 1;
index = g_index++;
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCRelease
// --------------------------------------------------------------------------------
inline RDOPROCRelease::RDOPROCRelease(LPIPROCProcess process, std::vector<parser_for_Seize> From_Par)
: RDOPROCBlockForSeize(process, From_Par)
{
static ruint g_index = 1;
index = g_index++;
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCAdvance
// --------------------------------------------------------------------------------
inline RDOPROCAdvance::RDOPROCAdvance(LPIPROCProcess process, CREF(LPRDOCalc) _pDelayCalc)
: RDOPROCBlock(process )
, pDelayCalc (_pDelayCalc)
{}
inline RDOPROCAdvance::LeaveTr::LeaveTr(CREF(LPRDOPROCTransact) _transact, double _timeLeave)
: transact (_transact )
, timeLeave(_timeLeave)
{}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCTerminate
// --------------------------------------------------------------------------------
inline RDOPROCTerminate::RDOPROCTerminate(LPIPROCProcess process, ruint _term)
: RDOPROCBlock(process)
, term (_term )
{}
inline int RDOPROCTerminate::getTerm()
{
return term;
}
// --------------------------------------------------------------------------------
// -------------------- RDOPROCAssign
// --------------------------------------------------------------------------------
inline RDOPROCAssign::RDOPROCAssign(LPIPROCProcess process, CREF(LPRDOCalc) pValue, int Id_res, int Id_param)
: RDOPROCBlock(process )
, pParamValue (pValue )
, t_resId (Id_res )
, t_parId (Id_param)
{}
CLOSE_RDO_RUNTIME_NAMESPACE
<|endoftext|> |
<commit_before>/**************************************************************************
*
* Copyright 2011 Zack Rusin
* All Rights Reserved.
*
* 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 "trace_snappyfile.hpp"
#include <snappy.h>
#include <assert.h>
#include <string.h>
#include <stdint.h>
using namespace Trace;
/*
* Snappy file format.
* -------------------
*
* Snappy at its core is just a compressoin algorithm so we're
* creating a new file format which uses snappy compression
* to hold the trace data.
*
* The file is composed of a number of chunks, they are:
* chunk {
* uint32 - specifying the length of the compressed data
* compressed data
* }
* File can contain any number of such chunks.
* The default size of an uncompressed chunk is specified in
* SNAPPY_CHUNK_SIZE.
*
* Note:
* Currently the default size for a a to-be-compressed data is
* 1mb, meaning that the compressed data will be <= 1mb.
* The reason it's 1mb is because it seems
* to offer a pretty good compression/disk io speed ratio
* but that might change.
*
*/
SnappyFile::SnappyFile(const std::string &filename,
File::Mode mode)
: File(),
m_cache(0),
m_cachePtr(0),
m_cacheSize(0)
{
size_t maxCompressedLength =
snappy::MaxCompressedLength(SNAPPY_CHUNK_SIZE);
m_compressedCache = new char[maxCompressedLength];
}
SnappyFile::~SnappyFile()
{
delete [] m_compressedCache;
}
bool SnappyFile::rawOpen(const std::string &filename, File::Mode mode)
{
std::ios_base::openmode fmode = std::fstream::binary;
if (mode == File::Write) {
fmode |= (std::fstream::out | std::fstream::trunc);
createCache(SNAPPY_CHUNK_SIZE);
} else if (mode == File::Read) {
fmode |= std::fstream::in;
}
m_stream.open(filename.c_str(), fmode);
//read in the initial buffer if we're reading
if (m_stream.is_open() && mode == File::Read) {
// read the snappy file identifier
unsigned char byte1, byte2;
m_stream >> byte1;
m_stream >> byte2;
assert(byte1 == SNAPPY_BYTE1 && byte2 == SNAPPY_BYTE2);
flushCache();
} else if (m_stream.is_open() && mode == File::Write) {
// write the snappy file identifier
m_stream << SNAPPY_BYTE1;
m_stream << SNAPPY_BYTE2;
}
return m_stream.is_open();
}
bool SnappyFile::rawWrite(const void *buffer, size_t length)
{
if (freeCacheSize() > length) {
memcpy(m_cachePtr, buffer, length);
m_cachePtr += length;
} else if (freeCacheSize() == length) {
memcpy(m_cachePtr, buffer, length);
m_cachePtr += length;
flushCache();
} else {
int sizeToWrite = length;
while (sizeToWrite >= freeCacheSize()) {
int endSize = freeCacheSize();
int offset = length - sizeToWrite;
memcpy(m_cachePtr, (const char*)buffer + offset, endSize);
sizeToWrite -= endSize;
m_cachePtr += endSize;
flushCache();
}
if (sizeToWrite) {
int offset = length - sizeToWrite;
memcpy(m_cachePtr, (const char*)buffer + offset, sizeToWrite);
m_cachePtr += sizeToWrite;
}
}
return true;
}
bool SnappyFile::rawRead(void *buffer, size_t length)
{
if (endOfData()) {
return false;
}
if (freeCacheSize() >= length) {
memcpy(buffer, m_cachePtr, length);
m_cachePtr += length;
} else {
size_t sizeToRead = length;
size_t offset = 0;
while (sizeToRead) {
size_t chunkSize = std::min(freeCacheSize(), sizeToRead);
offset = length - sizeToRead;
memcpy((char*)buffer + offset, m_cachePtr, chunkSize);
m_cachePtr += chunkSize;
sizeToRead -= chunkSize;
if (sizeToRead > 0)
flushCache();
if (!m_cacheSize)
break;
}
}
return true;
}
int SnappyFile::rawGetc()
{
int c = 0;
if (!rawRead(&c, 1))
return -1;
return c;
}
void SnappyFile::rawClose()
{
flushCache();
m_stream.close();
delete [] m_cache;
m_cache = NULL;
m_cachePtr = NULL;
}
void SnappyFile::rawFlush()
{
flushCache();
m_stream.flush();
}
void SnappyFile::flushCache()
{
if (m_mode == File::Write) {
size_t compressedLength;
::snappy::RawCompress(m_cache, SNAPPY_CHUNK_SIZE - freeCacheSize(),
m_compressedCache, &compressedLength);
writeCompressedLength(compressedLength);
m_stream.write(m_compressedCache, compressedLength);
m_cachePtr = m_cache;
} else if (m_mode == File::Read) {
if (m_stream.eof())
return;
//assert(m_cachePtr == m_cache + m_cacheSize);
size_t compressedLength;
compressedLength = readCompressedLength();
m_stream.read((char*)m_compressedCache, compressedLength);
/*
* The reason we peek here is because the last read will
* read all the way until the last character, but that will not
* trigger m_stream.eof() to be set, so by calling peek
* we assure that if we in fact have read the entire stream
* then the m_stream.eof() is always set.
*/
m_stream.peek();
::snappy::GetUncompressedLength(m_compressedCache, compressedLength,
&m_cacheSize);
if (m_cache)
delete [] m_cache;
createCache(m_cacheSize);
::snappy::RawUncompress(m_compressedCache, compressedLength,
m_cache);
}
}
void SnappyFile::createCache(size_t size)
{
m_cache = new char[size];
m_cachePtr = m_cache;
m_cacheSize = size;
}
void SnappyFile::writeCompressedLength(size_t length)
{
uint32_t value = length;
assert(value == length);
m_stream.write((const char*)&value, sizeof value);
}
size_t SnappyFile::readCompressedLength()
{
uint32_t length = 0;
m_stream.read((char*)&length, sizeof length);
return length;
}
<commit_msg>Always write snappy chunk lengths in little endian.<commit_after>/**************************************************************************
*
* Copyright 2011 Zack Rusin
* All Rights Reserved.
*
* 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 "trace_snappyfile.hpp"
#include <snappy.h>
#include <assert.h>
#include <string.h>
using namespace Trace;
/*
* Snappy file format.
* -------------------
*
* Snappy at its core is just a compressoin algorithm so we're
* creating a new file format which uses snappy compression
* to hold the trace data.
*
* The file is composed of a number of chunks, they are:
* chunk {
* uint32 - specifying the length of the compressed data
* compressed data, in little endian
* }
* File can contain any number of such chunks.
* The default size of an uncompressed chunk is specified in
* SNAPPY_CHUNK_SIZE.
*
* Note:
* Currently the default size for a a to-be-compressed data is
* 1mb, meaning that the compressed data will be <= 1mb.
* The reason it's 1mb is because it seems
* to offer a pretty good compression/disk io speed ratio
* but that might change.
*
*/
SnappyFile::SnappyFile(const std::string &filename,
File::Mode mode)
: File(),
m_cache(0),
m_cachePtr(0),
m_cacheSize(0)
{
size_t maxCompressedLength =
snappy::MaxCompressedLength(SNAPPY_CHUNK_SIZE);
m_compressedCache = new char[maxCompressedLength];
}
SnappyFile::~SnappyFile()
{
delete [] m_compressedCache;
}
bool SnappyFile::rawOpen(const std::string &filename, File::Mode mode)
{
std::ios_base::openmode fmode = std::fstream::binary;
if (mode == File::Write) {
fmode |= (std::fstream::out | std::fstream::trunc);
createCache(SNAPPY_CHUNK_SIZE);
} else if (mode == File::Read) {
fmode |= std::fstream::in;
}
m_stream.open(filename.c_str(), fmode);
//read in the initial buffer if we're reading
if (m_stream.is_open() && mode == File::Read) {
// read the snappy file identifier
unsigned char byte1, byte2;
m_stream >> byte1;
m_stream >> byte2;
assert(byte1 == SNAPPY_BYTE1 && byte2 == SNAPPY_BYTE2);
flushCache();
} else if (m_stream.is_open() && mode == File::Write) {
// write the snappy file identifier
m_stream << SNAPPY_BYTE1;
m_stream << SNAPPY_BYTE2;
}
return m_stream.is_open();
}
bool SnappyFile::rawWrite(const void *buffer, size_t length)
{
if (freeCacheSize() > length) {
memcpy(m_cachePtr, buffer, length);
m_cachePtr += length;
} else if (freeCacheSize() == length) {
memcpy(m_cachePtr, buffer, length);
m_cachePtr += length;
flushCache();
} else {
int sizeToWrite = length;
while (sizeToWrite >= freeCacheSize()) {
int endSize = freeCacheSize();
int offset = length - sizeToWrite;
memcpy(m_cachePtr, (const char*)buffer + offset, endSize);
sizeToWrite -= endSize;
m_cachePtr += endSize;
flushCache();
}
if (sizeToWrite) {
int offset = length - sizeToWrite;
memcpy(m_cachePtr, (const char*)buffer + offset, sizeToWrite);
m_cachePtr += sizeToWrite;
}
}
return true;
}
bool SnappyFile::rawRead(void *buffer, size_t length)
{
if (endOfData()) {
return false;
}
if (freeCacheSize() >= length) {
memcpy(buffer, m_cachePtr, length);
m_cachePtr += length;
} else {
size_t sizeToRead = length;
size_t offset = 0;
while (sizeToRead) {
size_t chunkSize = std::min(freeCacheSize(), sizeToRead);
offset = length - sizeToRead;
memcpy((char*)buffer + offset, m_cachePtr, chunkSize);
m_cachePtr += chunkSize;
sizeToRead -= chunkSize;
if (sizeToRead > 0)
flushCache();
if (!m_cacheSize)
break;
}
}
return true;
}
int SnappyFile::rawGetc()
{
int c = 0;
if (!rawRead(&c, 1))
return -1;
return c;
}
void SnappyFile::rawClose()
{
flushCache();
m_stream.close();
delete [] m_cache;
m_cache = NULL;
m_cachePtr = NULL;
}
void SnappyFile::rawFlush()
{
flushCache();
m_stream.flush();
}
void SnappyFile::flushCache()
{
if (m_mode == File::Write) {
size_t compressedLength;
::snappy::RawCompress(m_cache, SNAPPY_CHUNK_SIZE - freeCacheSize(),
m_compressedCache, &compressedLength);
writeCompressedLength(compressedLength);
m_stream.write(m_compressedCache, compressedLength);
m_cachePtr = m_cache;
} else if (m_mode == File::Read) {
if (m_stream.eof())
return;
//assert(m_cachePtr == m_cache + m_cacheSize);
size_t compressedLength;
compressedLength = readCompressedLength();
m_stream.read((char*)m_compressedCache, compressedLength);
/*
* The reason we peek here is because the last read will
* read all the way until the last character, but that will not
* trigger m_stream.eof() to be set, so by calling peek
* we assure that if we in fact have read the entire stream
* then the m_stream.eof() is always set.
*/
m_stream.peek();
::snappy::GetUncompressedLength(m_compressedCache, compressedLength,
&m_cacheSize);
if (m_cache)
delete [] m_cache;
createCache(m_cacheSize);
::snappy::RawUncompress(m_compressedCache, compressedLength,
m_cache);
}
}
void SnappyFile::createCache(size_t size)
{
m_cache = new char[size];
m_cachePtr = m_cache;
m_cacheSize = size;
}
void SnappyFile::writeCompressedLength(size_t length)
{
unsigned char buf[4];
buf[0] = length & 0xff; length >>= 8;
buf[1] = length & 0xff; length >>= 8;
buf[2] = length & 0xff; length >>= 8;
buf[3] = length & 0xff; length >>= 8;
assert(length == 0);
m_stream.write((const char *)buf, sizeof buf);
}
size_t SnappyFile::readCompressedLength()
{
unsigned char buf[4];
size_t length;
m_stream.read((char *)buf, sizeof buf);
if (m_stream.fail()) {
length = 0;
} else {
length = (size_t)buf[0];
length |= ((size_t)buf[1] << 8);
length |= ((size_t)buf[2] << 16);
length |= ((size_t)buf[3] << 24);
}
return length;
}
<|endoftext|> |
<commit_before>#include "ModernGL.hpp"
#include "OpenGL.hpp"
PyObject * NewFramebuffer(PyObject * self, PyObject * args, PyObject * kwargs) {
int width = 0;
int height = 0;
int colors = 1;
bool depth = true;
static const char * kwlist[] = {"width", "height", "colors", "depth", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|iiip:NewFramebuffer", (char **)kwlist, &width, &height, &colors, &depth)) {
return 0;
}
if (!width && !height) {
width = activeViewportWidth;
height = activeViewportHeight;
}
CHECK_AND_REPORT_ARG_VALUE_ERROR(width < 1, "width", width);
CHECK_AND_REPORT_ARG_VALUE_ERROR(height < 1, "height", height);
CHECK_AND_REPORT_ARG_VALUE_ERROR(colors < 0 || colors > 8, "colors", colors);
int framebuffer = 0;
OpenGL::glGenFramebuffers(1, (OpenGL::GLuint *)&framebuffer);
OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, framebuffer);
int depthTex = 0;
OpenGL::glGenTextures(1, (OpenGL::GLuint *)&depthTex);
OpenGL::glBindTexture(OpenGL::GL_TEXTURE_2D, depthTex);
OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MIN_FILTER, OpenGL::GL_LINEAR);
OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MAG_FILTER, OpenGL::GL_LINEAR);
OpenGL::glTexImage2D(OpenGL::GL_TEXTURE_2D, 0, OpenGL::GL_DEPTH_COMPONENT, width, height, 0, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, 0);
OpenGL::glFramebufferTexture2D(OpenGL::GL_FRAMEBUFFER, OpenGL::GL_DEPTH_ATTACHMENT, OpenGL::GL_TEXTURE_2D, depthTex, 0);
int colorTex[8] = {};
OpenGL::glGenTextures(colors, (OpenGL::GLuint *)colorTex);
for (int i = 0; i < colors; ++i) {
OpenGL::glBindTexture(OpenGL::GL_TEXTURE_2D, colorTex);
OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MIN_FILTER, OpenGL::GL_LINEAR);
OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MAG_FILTER, OpenGL::GL_LINEAR);
OpenGL::glTexImage2D(OpenGL::GL_TEXTURE_2D, 0, OpenGL::GL_RGBA, width, height, 0, OpenGL::GL_RGBA, OpenGL::GL_FLOAT, 0);
OpenGL::glFramebufferTexture2D(OpenGL::GL_FRAMEBUFFER, OpenGL::GL_COLOR_ATTACHMENT0 + i, OpenGL::GL_TEXTURE_2D, colorTex, 0);
}
OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, defaultFramebuffer);
PyObject * tuple = PyTuple_New(2 + colors);
PyTuple_SET_ITEM(tuple, 0, CreateFramebufferType(framebuffer, colorTex, depthTex));
for (int i = 0; i < colors; ++i) {
PyObject * colorTexture = CreateTextureType(colorTex[i], width, height, 4);
PyTuple_SET_ITEM(tuple, i + 1, colorTexture);
}
PyTuple_SET_ITEM(tuple, colors + 1, CreateTextureType(depthTex, width, height, 1));
return tuple;
}
PyObject * DeleteFramebuffer(PyObject * self, PyObject * args) {
Framebuffer * fbo;
if (!PyArg_ParseTuple(args, "O:DeleteFramebuffer", &fbo)) {
return 0;
}
CHECK_AND_REPORT_ARG_TYPE_ERROR("fbo", fbo, FramebufferType);
OpenGL::glDeleteFramebuffers(1, (OpenGL::GLuint *)&fbo->fbo);
OpenGL::glDeleteTextures(1, (OpenGL::GLuint *)&fbo->color);
OpenGL::glDeleteTextures(1, (OpenGL::GLuint *)&fbo->depth);
Py_RETURN_NONE;
}
PyObject * UseFramebuffer(PyObject * self, PyObject * args) {
Framebuffer * fbo;
if (!PyArg_ParseTuple(args, "O:UseFramebuffer", &fbo)) {
return 0;
}
CHECK_AND_REPORT_ARG_TYPE_ERROR("fbo", fbo, FramebufferType);
OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, fbo->fbo);
activeProgram = fbo->fbo;
Py_RETURN_NONE;
}
PyObject * GetDefaultFramebuffer(PyObject * self) {
OpenGL::glGetIntegerv(OpenGL::GL_DRAW_FRAMEBUFFER_BINDING, (OpenGL::GLint *)&defaultFramebuffer);
Py_RETURN_NONE;
}
PyObject * UseDefaultFramebuffer(PyObject * self) {
OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, defaultFramebuffer);
Py_RETURN_NONE;
}
PyObject * ReadPixels(PyObject * self, PyObject * args, PyObject * kwargs) {
int x;
int y;
int width;
int height;
int components = 3;
static const char * kwlist[] = {"x", "y", "width", "height", "components", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iiii|i:ReadPixels", (char **)kwlist, &x, &y, &width, &height, &components)) {
return 0;
}
CHECK_AND_REPORT_ARG_VALUE_ERROR(width < 1, "width", width);
CHECK_AND_REPORT_ARG_VALUE_ERROR(height < 1, "height", height);
CHECK_AND_REPORT_ARG_VALUE_ERROR(components < 1 || components > 4, "components", components);
int size = height * ((width * components + 3) & ~3);
const int formats[] = {0, OpenGL::GL_RED, OpenGL::GL_RG, OpenGL::GL_RGB, OpenGL::GL_RGBA};
int format = formats[components];
PyObject * bytes = PyBytes_FromStringAndSize(0, size);
char * data = PyBytes_AS_STRING(bytes);
OpenGL::glReadPixels(x, y, width, height, format, OpenGL::GL_UNSIGNED_BYTE, data);
data[size] = 0;
return bytes;
}
PyObject * ReadDepthPixels(PyObject * self, PyObject * args, PyObject * kwargs) {
int x;
int y;
int width;
int height;
static const char * kwlist[] = {"x", "y", "width", "height", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iiii:ReadDepthPixels", (char **)kwlist, &x, &y, &width, &height)) {
return 0;
}
CHECK_AND_REPORT_ARG_VALUE_ERROR(width < 1, "width", width);
CHECK_AND_REPORT_ARG_VALUE_ERROR(height < 1, "height", height);
int size = height * height * 4;
float * pixels = ModernGL::ReadDepthPixels(x, y, width, height);
PyObject * data = PyBytes_FromStringAndSize((const char *)pixels, size);
free(pixels);
PyObject * bytes = PyBytes_FromStringAndSize(0, size);
char * data = PyBytes_AS_STRING(bytes);
OpenGL::glReadPixels(x, y, width, height, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, data);
data[size] = 0;
return bytes;
}
PyObject * ReadPixel(PyObject * self, PyObject * args, PyObject * kwargs) {
int x;
int y;
static const char * kwlist[] = {"x", "y", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii:ReadPixel", (char **)kwlist, &x, &y)) {
return 0;
}
unsigned rgba = 0;
OpenGL::glReadPixels(x, y, 1, 1, OpenGL::GL_RGBA, OpenGL::GL_UNSIGNED_BYTE, &rgba);
return PyLong_FromUnsignedLong(rgba);
}
PyObject * ReadDepthPixel(PyObject * self, PyObject * args, PyObject * kwargs) {
int x;
int y;
static const char * kwlist[] = {"x", "y", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii:ReadDepthPixel", (char **)kwlist, &x, &y)) {
return 0;
}
float depth = 0.0;
OpenGL::glReadPixels(x, y, 1, 1, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, &depth);
return PyFloat_FromDouble(depth);
}
<commit_msg>Revert "solved #6"<commit_after>#include "ModernGL.hpp"
#include "OpenGL.hpp"
PyObject * NewFramebuffer(PyObject * self, PyObject * args, PyObject * kwargs) {
int width = 0;
int height = 0;
static const char * kwlist[] = {"width", "height", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ii:NewFramebuffer", (char **)kwlist, &width, &height)) {
return 0;
}
int framebuffer = 0;
int color = 0;
int depth = 0;
OpenGL::glGenFramebuffers(1, (OpenGL::GLuint *)&framebuffer);
OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, framebuffer);
if (!width && !height) {
width = activeViewportWidth;
height = activeViewportHeight;
}
OpenGL::glGenTextures(1, (OpenGL::GLuint *)&color);
OpenGL::glBindTexture(OpenGL::GL_TEXTURE_2D, color);
OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MIN_FILTER, OpenGL::GL_LINEAR);
OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MAG_FILTER, OpenGL::GL_LINEAR);
OpenGL::glTexImage2D(OpenGL::GL_TEXTURE_2D, 0, OpenGL::GL_RGBA, width, height, 0, OpenGL::GL_RGBA, OpenGL::GL_FLOAT, 0);
OpenGL::glFramebufferTexture2D(OpenGL::GL_FRAMEBUFFER, OpenGL::GL_COLOR_ATTACHMENT0, OpenGL::GL_TEXTURE_2D, color, 0);
OpenGL::glGenTextures(1, (OpenGL::GLuint *)&depth);
OpenGL::glBindTexture(OpenGL::GL_TEXTURE_2D, depth);
OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MIN_FILTER, OpenGL::GL_LINEAR);
OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MAG_FILTER, OpenGL::GL_LINEAR);
OpenGL::glTexImage2D(OpenGL::GL_TEXTURE_2D, 0, OpenGL::GL_DEPTH_COMPONENT, width, height, 0, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, 0);
OpenGL::glFramebufferTexture2D(OpenGL::GL_FRAMEBUFFER, OpenGL::GL_DEPTH_ATTACHMENT, OpenGL::GL_TEXTURE_2D, depth, 0);
OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, defaultFramebuffer);
PyObject * fbo = CreateFramebufferType(framebuffer, color, depth);
PyObject * colorTexture = CreateTextureType(color, width, height, 4);
PyObject * depthTexture = CreateTextureType(depth, width, height, 1);
return Py_BuildValue("OOO", fbo, colorTexture, depthTexture);
}
PyObject * DeleteFramebuffer(PyObject * self, PyObject * args) {
Framebuffer * fbo;
if (!PyArg_ParseTuple(args, "O:DeleteFramebuffer", &fbo)) {
return 0;
}
CHECK_AND_REPORT_ARG_TYPE_ERROR("fbo", fbo, FramebufferType);
OpenGL::glDeleteFramebuffers(1, (OpenGL::GLuint *)&fbo->fbo);
OpenGL::glDeleteTextures(1, (OpenGL::GLuint *)&fbo->color);
OpenGL::glDeleteTextures(1, (OpenGL::GLuint *)&fbo->depth);
Py_RETURN_NONE;
}
PyObject * UseFramebuffer(PyObject * self, PyObject * args) {
Framebuffer * fbo;
if (!PyArg_ParseTuple(args, "O:UseFramebuffer", &fbo)) {
return 0;
}
CHECK_AND_REPORT_ARG_TYPE_ERROR("fbo", fbo, FramebufferType);
OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, fbo->fbo);
activeProgram = fbo->fbo;
Py_RETURN_NONE;
}
PyObject * GetDefaultFramebuffer(PyObject * self) {
OpenGL::glGetIntegerv(OpenGL::GL_DRAW_FRAMEBUFFER_BINDING, (OpenGL::GLint *)&defaultFramebuffer);
Py_RETURN_NONE;
}
PyObject * UseDefaultFramebuffer(PyObject * self) {
OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, defaultFramebuffer);
Py_RETURN_NONE;
}
PyObject * ReadPixels(PyObject * self, PyObject * args, PyObject * kwargs) {
int x;
int y;
int width;
int height;
int components = 3;
static const char * kwlist[] = {"x", "y", "width", "height", "components", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iiii|i:ReadPixels", (char **)kwlist, &x, &y, &width, &height, &components)) {
return 0;
}
CHECK_AND_REPORT_ARG_VALUE_ERROR(width < 1, "width", width);
CHECK_AND_REPORT_ARG_VALUE_ERROR(height < 1, "height", height);
CHECK_AND_REPORT_ARG_VALUE_ERROR(components < 1 || components > 4, "components", components);
int size = height * ((width * components + 3) & ~3);
const int formats[] = {0, OpenGL::GL_RED, OpenGL::GL_RG, OpenGL::GL_RGB, OpenGL::GL_RGBA};
int format = formats[components];
PyObject * bytes = PyBytes_FromStringAndSize(0, size);
char * data = PyBytes_AS_STRING(bytes);
OpenGL::glReadPixels(x, y, width, height, format, OpenGL::GL_UNSIGNED_BYTE, data);
data[size] = 0;
return bytes;
}
PyObject * ReadDepthPixels(PyObject * self, PyObject * args, PyObject * kwargs) {
int x;
int y;
int width;
int height;
static const char * kwlist[] = {"x", "y", "width", "height", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iiii:ReadDepthPixels", (char **)kwlist, &x, &y, &width, &height)) {
return 0;
}
CHECK_AND_REPORT_ARG_VALUE_ERROR(width < 1, "width", width);
CHECK_AND_REPORT_ARG_VALUE_ERROR(height < 1, "height", height);
int size = height * height * 4;
float * pixels = ModernGL::ReadDepthPixels(x, y, width, height);
PyObject * data = PyBytes_FromStringAndSize((const char *)pixels, size);
free(pixels);
PyObject * bytes = PyBytes_FromStringAndSize(0, size);
char * data = PyBytes_AS_STRING(bytes);
OpenGL::glReadPixels(x, y, width, height, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, data);
data[size] = 0;
return bytes;
}
PyObject * ReadPixel(PyObject * self, PyObject * args, PyObject * kwargs) {
int x;
int y;
static const char * kwlist[] = {"x", "y", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii:ReadPixel", (char **)kwlist, &x, &y)) {
return 0;
}
unsigned rgba = 0;
OpenGL::glReadPixels(x, y, 1, 1, OpenGL::GL_RGBA, OpenGL::GL_UNSIGNED_BYTE, &rgba);
return PyLong_FromUnsignedLong(rgba);
}
PyObject * ReadDepthPixel(PyObject * self, PyObject * args, PyObject * kwargs) {
int x;
int y;
static const char * kwlist[] = {"x", "y", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii:ReadDepthPixel", (char **)kwlist, &x, &y)) {
return 0;
}
float depth = 0.0;
OpenGL::glReadPixels(x, y, 1, 1, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, &depth);
return PyFloat_FromDouble(depth);
}
<|endoftext|> |
<commit_before><commit_msg>String release first<commit_after><|endoftext|> |
<commit_before>#include "databasecontroller.h"
#include "app.h"
#include <QtSql>
#include <QtConcurrent>
DatabaseController::DatabaseController(QObject *parent) :
QObject(parent),
multiThreaded(false),
threadStore()
{
QtConcurrent::run(this, &DatabaseController::initDatabase);
}
QUuid DatabaseController::createIdentity(const QUuid &deviceId)
{
auto db = threadStore.localData().database();
if(!db.transaction()) {
qCritical() << "Failed to create transaction with error:"
<< qPrintable(db.lastError().text());
return {};
}
auto identity = QUuid::createUuid();
QSqlQuery createIdentityQuery(db);
createIdentityQuery.prepare(QStringLiteral("INSERT INTO users (identity) VALUES(?)"));
createIdentityQuery.addBindValue(identity);
if(!createIdentityQuery.exec()) {
qCritical() << "Failed to add new user identity with error:"
<< qPrintable(createIdentityQuery.lastError().text());
db.rollback();
return {};
}
QSqlQuery createDeviceQuery(db);
createDeviceQuery.prepare(QStringLiteral("INSERT INTO devices (deviceid, userid) VALUES(?, ?)"));
createDeviceQuery.addBindValue(deviceId);
createDeviceQuery.addBindValue(identity);
if(!createDeviceQuery.exec()) {
qCritical() << "Failed to add new device with error:"
<< qPrintable(createDeviceQuery.lastError().text());
db.rollback();
return {};
}
if(db.commit())
return identity;
else {
qCritical() << "Failed to commit transaction with error:"
<< qPrintable(db.lastError().text());
return {};
}
}
bool DatabaseController::identify(const QUuid &identity, const QUuid &deviceId)
{
auto db = threadStore.localData().database();
QSqlQuery identifyQuery(db);
identifyQuery.prepare(QStringLiteral("SELECT EXISTS(SELECT identity FROM users WHERE identity = ?) AS exists"));
identifyQuery.addBindValue(identity);
if(!identifyQuery.exec() || !identifyQuery.first()) {
qCritical() << "Failed to identify user with error:"
<< qPrintable(identifyQuery.lastError().text());
return false;
}
if(identifyQuery.value(0).toBool()) {
QSqlQuery createDeviceQuery(db);
createDeviceQuery.prepare(QStringLiteral("INSERT INTO devices (deviceid, userid) VALUES(?, ?) "
"ON CONFLICT DO NOTHING"));
createDeviceQuery.addBindValue(deviceId);
createDeviceQuery.addBindValue(identity);
if(!createDeviceQuery.exec()) {
qCritical() << "Failed to add (new) device with error:"
<< qPrintable(createDeviceQuery.lastError().text());
return false;
} else
return true;
} else
return false;
}
bool DatabaseController::save(const QUuid &userId, const QUuid &deviceId, const QString &type, const QString &key, const QJsonObject &object)
{
auto db = threadStore.localData().database();
if(!db.transaction()) {
qCritical() << "Failed to create transaction with error:"
<< qPrintable(db.lastError().text());
return false;
}
//check if key exists
QSqlQuery getIdQuery(db);
getIdQuery.prepare(QStringLiteral("SELECT index FROM data WHERE userid = ? AND type = ? AND key = ?"));
getIdQuery.addBindValue(userId);
getIdQuery.addBindValue(type);
getIdQuery.addBindValue(key);
if(!getIdQuery.exec()) {
qCritical() << "Failed to check if data exists with error:"
<< qPrintable(getIdQuery.lastError().text());
db.rollback();
return false;
}
quint64 index = 0;
if(getIdQuery.first()) {// if exists -> update
index = getIdQuery.value(0).toULongLong();
QSqlQuery updateQuery(db);
updateQuery.prepare(QStringLiteral("UPDATE data SET data = ? WHERE index = ?"));
updateQuery.addBindValue(jsonToString(object));
updateQuery.addBindValue(index);
if(!updateQuery.exec()) {
qCritical() << "Failed to update data with error:"
<< qPrintable(updateQuery.lastError().text());
db.rollback();
return false;
}
} else {// if not exists -> insert
QSqlQuery insertQuery(db);
insertQuery.prepare(QStringLiteral("INSERT INTO data (userid, type, key, data) VALUES(?, ?, ?, ?) RETURNING index"));
insertQuery.addBindValue(userId);
insertQuery.addBindValue(type);
insertQuery.addBindValue(key);
insertQuery.addBindValue(jsonToString(object));
if(!insertQuery.exec() || !insertQuery.first()) {
qCritical() << "Failed to insert data with error:"
<< qPrintable(insertQuery.lastError().text());
db.rollback();
return false;
}
index = insertQuery.value(0).toULongLong();
}
//update the change state
QSqlQuery updateStateQuery(db);
updateStateQuery.prepare(QStringLiteral("INSERT INTO states (dataindex, deviceid) "
"SELECT ?, id FROM devices "
"WHERE userid = ? AND deviceid != ? "
"ON CONFLICT DO NOTHING"));
updateStateQuery.addBindValue(index);
updateStateQuery.addBindValue(userId);
updateStateQuery.addBindValue(deviceId);
if(!updateStateQuery.exec()) {
qCritical() << "Failed to update device states with error:"
<< qPrintable(updateStateQuery.lastError().text());
db.rollback();
return false;
}
//notify all connected devices
if(db.commit())
return true;
else {
qCritical() << "Failed to commit transaction with error:"
<< qPrintable(db.lastError().text());
return false;
}
}
void DatabaseController::initDatabase()
{
auto db = threadStore.localData().database();
if(!db.tables().contains("users")) {
QSqlQuery createUsers(db);
if(!createUsers.exec(QStringLiteral("CREATE TABLE users ( "
" identity UUID PRIMARY KEY NOT NULL UNIQUE "
")"))) {
qCritical() << "Failed to create users table with error:"
<< qPrintable(createUsers.lastError().text());
return;
}
}
if(!db.tables().contains("devices")) {
QSqlQuery createDevices(db);
if(!createDevices.exec(QStringLiteral("CREATE TABLE devices ( "
" id SERIAL PRIMARY KEY NOT NULL, "
" deviceid UUID NOT NULL, "
" userid UUID NOT NULL REFERENCES users(identity), "
" CONSTRAINT device_id UNIQUE (deviceid, userid)"
")"))) {
qCritical() << "Failed to create devices table with error:"
<< qPrintable(createDevices.lastError().text());
return;
}
}
if(!db.tables().contains("data")) {
QSqlQuery createData(db);
if(!createData.exec(QStringLiteral("CREATE TABLE data ( "
" index SERIAL PRIMARY KEY NOT NULL, "
" userid UUID NOT NULL REFERENCES users(identity), "
" type TEXT NOT NULL, "
" key TEXT NOT NULL, "
" data JSONB, "
" CONSTRAINT data_id UNIQUE (userid, type, key)"
")"))) {
qCritical() << "Failed to create data table with error:"
<< qPrintable(createData.lastError().text());
return;
}
}
if(!db.tables().contains("states")) {
QSqlQuery createStates(db);
if(!createStates.exec(QStringLiteral("CREATE TABLE states ( "
" dataindex INTEGER NOT NULL REFERENCES data(index), "
" deviceid INTEGER NOT NULL REFERENCES devices(id), "
" PRIMARY KEY (dataindex, deviceid)"
")"))) {
qCritical() << "Failed to create states table with error:"
<< qPrintable(createStates.lastError().text());
return;
}
}
}
QString DatabaseController::jsonToString(const QJsonObject &object) const
{
return QJsonDocument(object).toJson(QJsonDocument::Compact);
}
DatabaseController::DatabaseWrapper::DatabaseWrapper() :
dbName(QUuid::createUuid().toString())
{
auto config = qApp->configuration();
auto db = QSqlDatabase::addDatabase(config->value("database/driver", "QPSQL").toString(), dbName);
db.setDatabaseName(config->value("database/name", "QtDataSync").toString());
db.setHostName(config->value("database/host").toString());
db.setPort(config->value("database/port").toInt());
db.setUserName(config->value("database/username").toString());
db.setPassword(config->value("database/password").toString());
db.setConnectOptions(config->value("database/options").toString());
if(!db.open()) {
qCritical() << "Failed to open database with error:"
<< qPrintable(db.lastError().text());
} else
qInfo() << "DB connected for thread" << QThread::currentThreadId();
}
DatabaseController::DatabaseWrapper::~DatabaseWrapper()
{
QSqlDatabase::database(dbName).close();
QSqlDatabase::removeDatabase(dbName);
qInfo() << "DB disconnected for thread" << QThread::currentThreadId();
}
QSqlDatabase DatabaseController::DatabaseWrapper::database() const
{
return QSqlDatabase::database(dbName);
}
<commit_msg>simplified data update<commit_after>#include "databasecontroller.h"
#include "app.h"
#include <QtSql>
#include <QtConcurrent>
DatabaseController::DatabaseController(QObject *parent) :
QObject(parent),
multiThreaded(false),
threadStore()
{
QtConcurrent::run(this, &DatabaseController::initDatabase);
}
QUuid DatabaseController::createIdentity(const QUuid &deviceId)
{
auto db = threadStore.localData().database();
if(!db.transaction()) {
qCritical() << "Failed to create transaction with error:"
<< qPrintable(db.lastError().text());
return {};
}
auto identity = QUuid::createUuid();
QSqlQuery createIdentityQuery(db);
createIdentityQuery.prepare(QStringLiteral("INSERT INTO users (identity) VALUES(?)"));
createIdentityQuery.addBindValue(identity);
if(!createIdentityQuery.exec()) {
qCritical() << "Failed to add new user identity with error:"
<< qPrintable(createIdentityQuery.lastError().text());
db.rollback();
return {};
}
QSqlQuery createDeviceQuery(db);
createDeviceQuery.prepare(QStringLiteral("INSERT INTO devices (deviceid, userid) VALUES(?, ?)"));
createDeviceQuery.addBindValue(deviceId);
createDeviceQuery.addBindValue(identity);
if(!createDeviceQuery.exec()) {
qCritical() << "Failed to add new device with error:"
<< qPrintable(createDeviceQuery.lastError().text());
db.rollback();
return {};
}
if(db.commit())
return identity;
else {
qCritical() << "Failed to commit transaction with error:"
<< qPrintable(db.lastError().text());
return {};
}
}
bool DatabaseController::identify(const QUuid &identity, const QUuid &deviceId)
{
auto db = threadStore.localData().database();
QSqlQuery identifyQuery(db);
identifyQuery.prepare(QStringLiteral("SELECT EXISTS(SELECT identity FROM users WHERE identity = ?) AS exists"));
identifyQuery.addBindValue(identity);
if(!identifyQuery.exec() || !identifyQuery.first()) {
qCritical() << "Failed to identify user with error:"
<< qPrintable(identifyQuery.lastError().text());
return false;
}
if(identifyQuery.value(0).toBool()) {
QSqlQuery createDeviceQuery(db);
createDeviceQuery.prepare(QStringLiteral("INSERT INTO devices (deviceid, userid) VALUES(?, ?) "
"ON CONFLICT DO NOTHING"));
createDeviceQuery.addBindValue(deviceId);
createDeviceQuery.addBindValue(identity);
if(!createDeviceQuery.exec()) {
qCritical() << "Failed to add (new) device with error:"
<< qPrintable(createDeviceQuery.lastError().text());
return false;
} else
return true;
} else
return false;
}
bool DatabaseController::save(const QUuid &userId, const QUuid &deviceId, const QString &type, const QString &key, const QJsonObject &object)
{
auto db = threadStore.localData().database();
if(!db.transaction()) {
qCritical() << "Failed to create transaction with error:"
<< qPrintable(db.lastError().text());
return false;
}
// insert/update the data
QSqlQuery saveQuery(db);
saveQuery.prepare(QStringLiteral("INSERT INTO data (userid, type, key, data) VALUES(?, ?, ?, ?) "
"ON CONFLICT (userid, type, key) DO UPDATE "
"SET data = EXCLUDED.data "
"RETURNING index"));
saveQuery.addBindValue(userId);
saveQuery.addBindValue(type);
saveQuery.addBindValue(key);
saveQuery.addBindValue(jsonToString(object));
if(!saveQuery.exec() || !saveQuery.first()) {
qCritical() << "Failed to insert/update data with error:"
<< qPrintable(saveQuery.lastError().text());
db.rollback();
return false;
}
auto index = saveQuery.value(0).toULongLong();
//update the change state
QSqlQuery updateStateQuery(db);
updateStateQuery.prepare(QStringLiteral("INSERT INTO states (dataindex, deviceid) "
"SELECT ?, id FROM devices "
"WHERE userid = ? AND deviceid != ? "
"ON CONFLICT DO NOTHING"));
updateStateQuery.addBindValue(index);
updateStateQuery.addBindValue(userId);
updateStateQuery.addBindValue(deviceId);
if(!updateStateQuery.exec()) {
qCritical() << "Failed to update device states with error:"
<< qPrintable(updateStateQuery.lastError().text());
db.rollback();
return false;
}
//notify all connected devices
if(db.commit())
return true;
else {
qCritical() << "Failed to commit transaction with error:"
<< qPrintable(db.lastError().text());
return false;
}
}
void DatabaseController::initDatabase()
{
auto db = threadStore.localData().database();
if(!db.tables().contains("users")) {
QSqlQuery createUsers(db);
if(!createUsers.exec(QStringLiteral("CREATE TABLE users ( "
" identity UUID PRIMARY KEY NOT NULL UNIQUE "
")"))) {
qCritical() << "Failed to create users table with error:"
<< qPrintable(createUsers.lastError().text());
return;
}
}
if(!db.tables().contains("devices")) {
QSqlQuery createDevices(db);
if(!createDevices.exec(QStringLiteral("CREATE TABLE devices ( "
" id SERIAL PRIMARY KEY NOT NULL, "
" deviceid UUID NOT NULL, "
" userid UUID NOT NULL REFERENCES users(identity), "
" CONSTRAINT device_id UNIQUE (deviceid, userid)"
")"))) {
qCritical() << "Failed to create devices table with error:"
<< qPrintable(createDevices.lastError().text());
return;
}
}
if(!db.tables().contains("data")) {
QSqlQuery createData(db);
if(!createData.exec(QStringLiteral("CREATE TABLE data ( "
" index SERIAL PRIMARY KEY NOT NULL, "
" userid UUID NOT NULL REFERENCES users(identity), "
" type TEXT NOT NULL, "
" key TEXT NOT NULL, "
" data JSONB, "
" CONSTRAINT data_id UNIQUE (userid, type, key)"
")"))) {
qCritical() << "Failed to create data table with error:"
<< qPrintable(createData.lastError().text());
return;
}
}
if(!db.tables().contains("states")) {
QSqlQuery createStates(db);
if(!createStates.exec(QStringLiteral("CREATE TABLE states ( "
" dataindex INTEGER NOT NULL REFERENCES data(index), "
" deviceid INTEGER NOT NULL REFERENCES devices(id), "
" PRIMARY KEY (dataindex, deviceid)"
")"))) {
qCritical() << "Failed to create states table with error:"
<< qPrintable(createStates.lastError().text());
return;
}
}
}
QString DatabaseController::jsonToString(const QJsonObject &object) const
{
return QJsonDocument(object).toJson(QJsonDocument::Compact);
}
DatabaseController::DatabaseWrapper::DatabaseWrapper() :
dbName(QUuid::createUuid().toString())
{
auto config = qApp->configuration();
auto db = QSqlDatabase::addDatabase(config->value("database/driver", "QPSQL").toString(), dbName);
db.setDatabaseName(config->value("database/name", "QtDataSync").toString());
db.setHostName(config->value("database/host").toString());
db.setPort(config->value("database/port").toInt());
db.setUserName(config->value("database/username").toString());
db.setPassword(config->value("database/password").toString());
db.setConnectOptions(config->value("database/options").toString());
if(!db.open()) {
qCritical() << "Failed to open database with error:"
<< qPrintable(db.lastError().text());
} else
qInfo() << "DB connected for thread" << QThread::currentThreadId();
}
DatabaseController::DatabaseWrapper::~DatabaseWrapper()
{
QSqlDatabase::database(dbName).close();
QSqlDatabase::removeDatabase(dbName);
qInfo() << "DB disconnected for thread" << QThread::currentThreadId();
}
QSqlDatabase DatabaseController::DatabaseWrapper::database() const
{
return QSqlDatabase::database(dbName);
}
<|endoftext|> |
<commit_before>/***********************************************************************
created: Sep 15 2014
author: Luca Ebach <lucaebach@gmail.com>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
*
* 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 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.
***************************************************************************/
/**************************************************************************
* The following libs (and corresponding headers) are needed to compile and to link:
* CEGUIBase
* CEGUIOpenGLRenderer
* CEGUICoreWindowRendererSet
* default CEGUI xml parser (and dependencies)
* GLFW3
* OpengGL
* glm headers (as part of CEGUIBase)
***************************************************************************/
#include <iostream>
#include <CEGUI/CEGUI.h>
#include <CEGUI/RendererModules/OpenGL/GL3Renderer.h>
#include <GLFW/glfw3.h>
static GLFWwindow* window;
CEGUI::MouseButton toCEGUIButton(int button)
{
switch (button)
{
case GLFW_MOUSE_BUTTON_LEFT:
return CEGUI::LeftButton;
case GLFW_MOUSE_BUTTON_MIDDLE:
return CEGUI::MiddleButton;
case GLFW_MOUSE_BUTTON_RIGHT:
return CEGUI::RightButton;
default:
return CEGUI::MouseButtonCount;
}
}
CEGUI::Key::Scan toCEGUIKey(int glfwKey)
{
switch (glfwKey)
{
case GLFW_KEY_ESCAPE: return CEGUI::Key::Escape;
case GLFW_KEY_F1: return CEGUI::Key::F1;
case GLFW_KEY_F2: return CEGUI::Key::F2;
case GLFW_KEY_F3: return CEGUI::Key::F3;
case GLFW_KEY_F4: return CEGUI::Key::F4;
case GLFW_KEY_F5: return CEGUI::Key::F5;
case GLFW_KEY_F6: return CEGUI::Key::F6;
case GLFW_KEY_F7: return CEGUI::Key::F7;
case GLFW_KEY_F8: return CEGUI::Key::F8;
case GLFW_KEY_F9: return CEGUI::Key::F9;
case GLFW_KEY_F10: return CEGUI::Key::F10;
case GLFW_KEY_F11: return CEGUI::Key::F11;
case GLFW_KEY_F12: return CEGUI::Key::F12;
case GLFW_KEY_F13: return CEGUI::Key::F13;
case GLFW_KEY_F14: return CEGUI::Key::F14;
case GLFW_KEY_F15: return CEGUI::Key::F15;
case GLFW_KEY_UP: return CEGUI::Key::ArrowUp;
case GLFW_KEY_DOWN: return CEGUI::Key::ArrowDown;
case GLFW_KEY_LEFT: return CEGUI::Key::ArrowLeft;
case GLFW_KEY_RIGHT: return CEGUI::Key::ArrowRight;
case GLFW_KEY_LEFT_SHIFT: return CEGUI::Key::LeftShift;
case GLFW_KEY_RIGHT_SHIFT: return CEGUI::Key::RightShift;
case GLFW_KEY_LEFT_CONTROL: return CEGUI::Key::LeftControl;
case GLFW_KEY_RIGHT_CONTROL: return CEGUI::Key::RightControl;
case GLFW_KEY_LEFT_ALT: return CEGUI::Key::LeftAlt;
case GLFW_KEY_RIGHT_ALT: return CEGUI::Key::RightAlt;
case GLFW_KEY_TAB: return CEGUI::Key::Tab;
case GLFW_KEY_ENTER: return CEGUI::Key::Return;
case GLFW_KEY_BACKSPACE: return CEGUI::Key::Backspace;
case GLFW_KEY_INSERT: return CEGUI::Key::Insert;
case GLFW_KEY_DELETE: return CEGUI::Key::Delete;
case GLFW_KEY_PAGE_UP: return CEGUI::Key::PageUp;
case GLFW_KEY_PAGE_DOWN: return CEGUI::Key::PageDown;
case GLFW_KEY_HOME: return CEGUI::Key::Home;
case GLFW_KEY_END: return CEGUI::Key::End;
case GLFW_KEY_KP_ENTER: return CEGUI::Key::NumpadEnter;
case GLFW_KEY_SPACE: return CEGUI::Key::Space;
case 'A': return CEGUI::Key::A;
case 'B': return CEGUI::Key::B;
case 'C': return CEGUI::Key::C;
case 'D': return CEGUI::Key::D;
case 'E': return CEGUI::Key::E;
case 'F': return CEGUI::Key::F;
case 'G': return CEGUI::Key::G;
case 'H': return CEGUI::Key::H;
case 'I': return CEGUI::Key::I;
case 'J': return CEGUI::Key::J;
case 'K': return CEGUI::Key::K;
case 'L': return CEGUI::Key::L;
case 'M': return CEGUI::Key::M;
case 'N': return CEGUI::Key::N;
case 'O': return CEGUI::Key::O;
case 'P': return CEGUI::Key::P;
case 'Q': return CEGUI::Key::Q;
case 'R': return CEGUI::Key::R;
case 'S': return CEGUI::Key::S;
case 'T': return CEGUI::Key::T;
case 'U': return CEGUI::Key::U;
case 'V': return CEGUI::Key::V;
case 'W': return CEGUI::Key::W;
case 'X': return CEGUI::Key::X;
case 'Y': return CEGUI::Key::Y;
case 'Z': return CEGUI::Key::Z;
default: return CEGUI::Key::Unknown;
}
}
void charCallback(GLFWwindow* window, unsigned int char_pressed)
{
CEGUI::System::getSingleton().getDefaultGUIContext().injectChar(char_pressed);
}
void cursorPosCallback(GLFWwindow* window, double x, double y)
{
CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(x, y);
}
void keyCallback(GLFWwindow* window, int key, int scan, int action, int mod)
{
CEGUI::Key::Scan cegui_key = toCEGUIKey(key);
if (action == GLFW_PRESS)
{
CEGUI::System::getSingleton().getDefaultGUIContext().injectKeyDown(cegui_key);
}
else
{
CEGUI::System::getSingleton().getDefaultGUIContext().injectKeyUp(cegui_key);
}
}
void mouseButtonCallback(GLFWwindow* window, int button, int state, int mod)
{
if (state == GLFW_PRESS)
{
CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseButtonDown(toCEGUIButton(button));
}
else
{
CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseButtonUp(toCEGUIButton(button));
}
}
void mouseWheelCallback(GLFWwindow* window, double x, double y)
{
if (y < 0.f)
CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseWheelChange(-1.f);
else
CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseWheelChange(+1.f);
}
void windowResizedCallback(GLFWwindow* window, int width, int height)
{
CEGUI::System::getSingleton().notifyDisplaySizeChanged(
CEGUI::Sizef(static_cast<float>(width), static_cast<float>(height)));
glViewport(0, 0, width, height);
}
void errorCallback(int error, const char* message)
{
CEGUI::Logger::getSingleton().logEvent(message, CEGUI::Errors);
}
void setupCallbacks()
{
// input callbacks
glfwSetCharCallback(window, charCallback);
glfwSetCursorPosCallback(window, cursorPosCallback);
glfwSetKeyCallback(window, keyCallback);
glfwSetMouseButtonCallback(window, mouseButtonCallback);
glfwSetScrollCallback(window, mouseWheelCallback);
// window callback
glfwSetWindowSizeCallback(window, windowResizedCallback);
// error callback
glfwSetErrorCallback(errorCallback);
}
void initGLFW()
{
// init everything from glfw
if (glfwInit() != GL_TRUE)
{
std::cerr << "glfw could not be initialized!" << std::endl;
exit(1);
}
// create glfw window with size of 800x600px
window = glfwCreateWindow(800, 600, "CEGUI + glfw3 window", NULL, NULL);
if (!window)
{
std::cerr << "Could not create glfw window!" << std::endl;
glfwTerminate();
exit(1);
}
// makes this window's gl context the current one
glfwMakeContextCurrent(window);
// hide native mouse cursor when it is over the window
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
// disable VSYNC
glfwSwapInterval(0);
// clear error messages
glGetError();
}
void initCEGUI()
{
using namespace CEGUI;
// create renderer and enable extra states
OpenGL3Renderer& cegui_renderer = OpenGL3Renderer::create(Sizef(800.f, 600.f));
cegui_renderer.enableExtraStateSettings(true);
// create CEGUI system object
CEGUI::System::create(cegui_renderer);
// setup resource directories
DefaultResourceProvider* rp = static_cast<DefaultResourceProvider*>(System::getSingleton().getResourceProvider());
rp->setResourceGroupDirectory("schemes", "datafiles/schemes/");
rp->setResourceGroupDirectory("imagesets", "datafiles/imagesets/");
rp->setResourceGroupDirectory("fonts", "datafiles/fonts/");
rp->setResourceGroupDirectory("layouts", "datafiles/layouts/");
rp->setResourceGroupDirectory("looknfeels", "datafiles/looknfeel/");
rp->setResourceGroupDirectory("lua_scripts", "datafiles/lua_scripts/");
rp->setResourceGroupDirectory("schemas", "datafiles/xml_schemas/");
// set default resource groups
ImageManager::setImagesetDefaultResourceGroup("imagesets");
Font::setDefaultResourceGroup("fonts");
Scheme::setDefaultResourceGroup("schemes");
WidgetLookManager::setDefaultResourceGroup("looknfeels");
WindowManager::setDefaultResourceGroup("layouts");
ScriptModule::setDefaultResourceGroup("lua_scripts");
XMLParser* parser = System::getSingleton().getXMLParser();
if (parser->isPropertyPresent("SchemaDefaultResourceGroup"))
parser->setProperty("SchemaDefaultResourceGroup", "schemas");
// load TaharezLook scheme and DejaVuSans-10 font
SchemeManager::getSingleton().createFromFile("TaharezLook.scheme", "schemes");
FontManager::getSingleton().createFromFile("DejaVuSans-10.font");
// set default font and cursor image and tooltip type
System::getSingleton().getDefaultGUIContext().setDefaultFont("DejaVuSans-10");
System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("TaharezLook/MouseArrow");
System::getSingleton().getDefaultGUIContext().setDefaultTooltipType("TaharezLook/Tooltip");
}
void initWindows()
{
using namespace CEGUI;
/////////////////////////////////////////////////////////////
// Add your gui initialisation code in here.
// You should preferably use layout loading because you won't
// have to recompile everytime you change the layout. But you
// can also use static window creation code here, of course.
/////////////////////////////////////////////////////////////
// load layout
Window* root = WindowManager::getSingleton().loadLayoutFromFile("application_templates.layout");
System::getSingleton().getDefaultGUIContext().setRootWindow(root);
}
#ifdef _MSC_VER
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
#else
int main(int argc, char* argv[])
#endif
{
using namespace CEGUI;
// init glfw
initGLFW();
// init cegui
initCEGUI();
// setup glfw callbacks
setupCallbacks();
// notify system of the window size
System::getSingleton().notifyDisplaySizeChanged(Sizef(800.f, 600.f));
glViewport(0, 0, 800, 600);
// initialise windows and setup layout
initWindows();
// set gl clear color
glClearColor(0, 0, 0, 255);
float time = glfwGetTime();
OpenGL3Renderer* renderer = static_cast<OpenGL3Renderer*>(System::getSingleton().getRenderer());
// repeat until a quit is requested
while (glfwWindowShouldClose(window) == GL_FALSE)
{
// clear screen
glClear(GL_COLOR_BUFFER_BIT);
// inject time pulses
const float newtime = glfwGetTime();
const float time_elapsed = newtime - time;
System::getSingleton().injectTimePulse(time_elapsed);
System::getSingleton().getDefaultGUIContext().injectTimePulse(time_elapsed);
time = newtime;
// render gui
renderer->beginRendering();
System::getSingleton().renderAllGUIContexts();
renderer->endRendering();
// swap buffers
glfwSwapBuffers(window);
// poll events
glfwPollEvents();
}
// destroy system and renderer
System::destroy();
OpenGL3Renderer::destroy(*renderer);
renderer = 0;
// destroy glfw window
glfwDestroyWindow(window);
// cleanup glfw
glfwTerminate();
return 0;
}<commit_msg>MOD: docu<commit_after>/***********************************************************************
created: Sep 15 2014
author: Luca Ebach <bitcket@lucebac.net>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2015 Paul D Turner & The CEGUI Development Team
*
* 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 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.
***************************************************************************/
/**************************************************************************
* The following libs (and corresponding headers) are needed to compile and to link:
* CEGUIBase
* CEGUIOpenGLRenderer
* CEGUICoreWindowRendererSet
* default CEGUI xml parser (and dependencies)
* GLFW3
* OpengGL
* glm headers (as part of CEGUIBase)
***************************************************************************/
#include <iostream>
#include <CEGUI/CEGUI.h>
#include <CEGUI/RendererModules/OpenGL/GL3Renderer.h>
#include <GLFW/glfw3.h>
static GLFWwindow* window;
CEGUI::MouseButton toCEGUIButton(int button)
{
switch (button)
{
case GLFW_MOUSE_BUTTON_LEFT:
return CEGUI::LeftButton;
case GLFW_MOUSE_BUTTON_MIDDLE:
return CEGUI::MiddleButton;
case GLFW_MOUSE_BUTTON_RIGHT:
return CEGUI::RightButton;
default:
return CEGUI::MouseButtonCount;
}
}
CEGUI::Key::Scan toCEGUIKey(int glfwKey)
{
switch (glfwKey)
{
case GLFW_KEY_ESCAPE: return CEGUI::Key::Escape;
case GLFW_KEY_F1: return CEGUI::Key::F1;
case GLFW_KEY_F2: return CEGUI::Key::F2;
case GLFW_KEY_F3: return CEGUI::Key::F3;
case GLFW_KEY_F4: return CEGUI::Key::F4;
case GLFW_KEY_F5: return CEGUI::Key::F5;
case GLFW_KEY_F6: return CEGUI::Key::F6;
case GLFW_KEY_F7: return CEGUI::Key::F7;
case GLFW_KEY_F8: return CEGUI::Key::F8;
case GLFW_KEY_F9: return CEGUI::Key::F9;
case GLFW_KEY_F10: return CEGUI::Key::F10;
case GLFW_KEY_F11: return CEGUI::Key::F11;
case GLFW_KEY_F12: return CEGUI::Key::F12;
case GLFW_KEY_F13: return CEGUI::Key::F13;
case GLFW_KEY_F14: return CEGUI::Key::F14;
case GLFW_KEY_F15: return CEGUI::Key::F15;
case GLFW_KEY_UP: return CEGUI::Key::ArrowUp;
case GLFW_KEY_DOWN: return CEGUI::Key::ArrowDown;
case GLFW_KEY_LEFT: return CEGUI::Key::ArrowLeft;
case GLFW_KEY_RIGHT: return CEGUI::Key::ArrowRight;
case GLFW_KEY_LEFT_SHIFT: return CEGUI::Key::LeftShift;
case GLFW_KEY_RIGHT_SHIFT: return CEGUI::Key::RightShift;
case GLFW_KEY_LEFT_CONTROL: return CEGUI::Key::LeftControl;
case GLFW_KEY_RIGHT_CONTROL: return CEGUI::Key::RightControl;
case GLFW_KEY_LEFT_ALT: return CEGUI::Key::LeftAlt;
case GLFW_KEY_RIGHT_ALT: return CEGUI::Key::RightAlt;
case GLFW_KEY_TAB: return CEGUI::Key::Tab;
case GLFW_KEY_ENTER: return CEGUI::Key::Return;
case GLFW_KEY_BACKSPACE: return CEGUI::Key::Backspace;
case GLFW_KEY_INSERT: return CEGUI::Key::Insert;
case GLFW_KEY_DELETE: return CEGUI::Key::Delete;
case GLFW_KEY_PAGE_UP: return CEGUI::Key::PageUp;
case GLFW_KEY_PAGE_DOWN: return CEGUI::Key::PageDown;
case GLFW_KEY_HOME: return CEGUI::Key::Home;
case GLFW_KEY_END: return CEGUI::Key::End;
case GLFW_KEY_KP_ENTER: return CEGUI::Key::NumpadEnter;
case GLFW_KEY_SPACE: return CEGUI::Key::Space;
case 'A': return CEGUI::Key::A;
case 'B': return CEGUI::Key::B;
case 'C': return CEGUI::Key::C;
case 'D': return CEGUI::Key::D;
case 'E': return CEGUI::Key::E;
case 'F': return CEGUI::Key::F;
case 'G': return CEGUI::Key::G;
case 'H': return CEGUI::Key::H;
case 'I': return CEGUI::Key::I;
case 'J': return CEGUI::Key::J;
case 'K': return CEGUI::Key::K;
case 'L': return CEGUI::Key::L;
case 'M': return CEGUI::Key::M;
case 'N': return CEGUI::Key::N;
case 'O': return CEGUI::Key::O;
case 'P': return CEGUI::Key::P;
case 'Q': return CEGUI::Key::Q;
case 'R': return CEGUI::Key::R;
case 'S': return CEGUI::Key::S;
case 'T': return CEGUI::Key::T;
case 'U': return CEGUI::Key::U;
case 'V': return CEGUI::Key::V;
case 'W': return CEGUI::Key::W;
case 'X': return CEGUI::Key::X;
case 'Y': return CEGUI::Key::Y;
case 'Z': return CEGUI::Key::Z;
default: return CEGUI::Key::Unknown;
}
}
void charCallback(GLFWwindow* window, unsigned int char_pressed)
{
CEGUI::System::getSingleton().getDefaultGUIContext().injectChar(char_pressed);
}
void cursorPosCallback(GLFWwindow* window, double x, double y)
{
CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(x, y);
}
void keyCallback(GLFWwindow* window, int key, int scan, int action, int mod)
{
CEGUI::Key::Scan cegui_key = toCEGUIKey(key);
if (action == GLFW_PRESS)
{
CEGUI::System::getSingleton().getDefaultGUIContext().injectKeyDown(cegui_key);
}
else
{
CEGUI::System::getSingleton().getDefaultGUIContext().injectKeyUp(cegui_key);
}
}
void mouseButtonCallback(GLFWwindow* window, int button, int state, int mod)
{
if (state == GLFW_PRESS)
{
CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseButtonDown(toCEGUIButton(button));
}
else
{
CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseButtonUp(toCEGUIButton(button));
}
}
void mouseWheelCallback(GLFWwindow* window, double x, double y)
{
if (y < 0.f)
CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseWheelChange(-1.f);
else
CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseWheelChange(+1.f);
}
void windowResizedCallback(GLFWwindow* window, int width, int height)
{
CEGUI::System::getSingleton().notifyDisplaySizeChanged(
CEGUI::Sizef(static_cast<float>(width), static_cast<float>(height)));
glViewport(0, 0, width, height);
}
void errorCallback(int error, const char* message)
{
CEGUI::Logger::getSingleton().logEvent(message, CEGUI::Errors);
}
void setupCallbacks()
{
// input callbacks
glfwSetCharCallback(window, charCallback);
glfwSetCursorPosCallback(window, cursorPosCallback);
glfwSetKeyCallback(window, keyCallback);
glfwSetMouseButtonCallback(window, mouseButtonCallback);
glfwSetScrollCallback(window, mouseWheelCallback);
// window callback
glfwSetWindowSizeCallback(window, windowResizedCallback);
// error callback
glfwSetErrorCallback(errorCallback);
}
void initGLFW()
{
// init everything from glfw
if (glfwInit() != GL_TRUE)
{
std::cerr << "glfw could not be initialized!" << std::endl;
exit(1);
}
// create glfw window with size of 800x600px
window = glfwCreateWindow(800, 600, "CEGUI + glfw3 window", NULL, NULL);
if (!window)
{
std::cerr << "Could not create glfw window!" << std::endl;
glfwTerminate();
exit(1);
}
// makes this window's gl context the current one
glfwMakeContextCurrent(window);
// hide native mouse cursor when it is over the window
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
// disable VSYNC
glfwSwapInterval(0);
// clear error messages
glGetError();
}
void initCEGUI()
{
using namespace CEGUI;
// create renderer and enable extra states
OpenGL3Renderer& cegui_renderer = OpenGL3Renderer::create(Sizef(800.f, 600.f));
cegui_renderer.enableExtraStateSettings(true);
// create CEGUI system object
CEGUI::System::create(cegui_renderer);
// setup resource directories
DefaultResourceProvider* rp = static_cast<DefaultResourceProvider*>(System::getSingleton().getResourceProvider());
rp->setResourceGroupDirectory("schemes", "datafiles/schemes/");
rp->setResourceGroupDirectory("imagesets", "datafiles/imagesets/");
rp->setResourceGroupDirectory("fonts", "datafiles/fonts/");
rp->setResourceGroupDirectory("layouts", "datafiles/layouts/");
rp->setResourceGroupDirectory("looknfeels", "datafiles/looknfeel/");
rp->setResourceGroupDirectory("lua_scripts", "datafiles/lua_scripts/");
rp->setResourceGroupDirectory("schemas", "datafiles/xml_schemas/");
// set default resource groups
ImageManager::setImagesetDefaultResourceGroup("imagesets");
Font::setDefaultResourceGroup("fonts");
Scheme::setDefaultResourceGroup("schemes");
WidgetLookManager::setDefaultResourceGroup("looknfeels");
WindowManager::setDefaultResourceGroup("layouts");
ScriptModule::setDefaultResourceGroup("lua_scripts");
XMLParser* parser = System::getSingleton().getXMLParser();
if (parser->isPropertyPresent("SchemaDefaultResourceGroup"))
parser->setProperty("SchemaDefaultResourceGroup", "schemas");
// load TaharezLook scheme and DejaVuSans-10 font
SchemeManager::getSingleton().createFromFile("TaharezLook.scheme", "schemes");
FontManager::getSingleton().createFromFile("DejaVuSans-10.font");
// set default font and cursor image and tooltip type
System::getSingleton().getDefaultGUIContext().setDefaultFont("DejaVuSans-10");
System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("TaharezLook/MouseArrow");
System::getSingleton().getDefaultGUIContext().setDefaultTooltipType("TaharezLook/Tooltip");
}
void initWindows()
{
using namespace CEGUI;
/////////////////////////////////////////////////////////////
// Add your gui initialisation code in here.
// You should preferably use layout loading because you won't
// have to recompile everytime you change the layout. But you
// can also use static window creation code here, of course.
/////////////////////////////////////////////////////////////
// load layout
Window* root = WindowManager::getSingleton().loadLayoutFromFile("application_templates.layout");
System::getSingleton().getDefaultGUIContext().setRootWindow(root);
}
#ifdef _MSC_VER
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
#else
int main(int argc, char* argv[])
#endif
{
using namespace CEGUI;
// init glfw
initGLFW();
// init cegui
initCEGUI();
// setup glfw callbacks
setupCallbacks();
// notify system of the window size
System::getSingleton().notifyDisplaySizeChanged(Sizef(800.f, 600.f));
glViewport(0, 0, 800, 600);
// initialise windows and setup layout
initWindows();
// set gl clear color
glClearColor(0, 0, 0, 255);
float time = glfwGetTime();
OpenGL3Renderer* renderer = static_cast<OpenGL3Renderer*>(System::getSingleton().getRenderer());
// repeat until a quit is requested
while (glfwWindowShouldClose(window) == GL_FALSE)
{
// clear screen
glClear(GL_COLOR_BUFFER_BIT);
// inject time pulses
const float newtime = glfwGetTime();
const float time_elapsed = newtime - time;
System::getSingleton().injectTimePulse(time_elapsed);
System::getSingleton().getDefaultGUIContext().injectTimePulse(time_elapsed);
time = newtime;
// render gui
renderer->beginRendering();
System::getSingleton().renderAllGUIContexts();
renderer->endRendering();
// swap buffers
glfwSwapBuffers(window);
// poll events
glfwPollEvents();
}
// destroy system and renderer
System::destroy();
OpenGL3Renderer::destroy(*renderer);
renderer = 0;
// destroy glfw window
glfwDestroyWindow(window);
// cleanup glfw
glfwTerminate();
return 0;
}<|endoftext|> |
<commit_before>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
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 <cassert>
#include <cstring>
#include <iostream>
#include "lm/binary_format.hh"
#include "lm/enumerate_vocab.hh"
#include "lm/model.hh"
#include "LanguageModelKen.h"
#include "FFState.h"
#include "TypeDef.h"
#include "Util.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "InputFileStream.h"
#include "StaticData.h"
using namespace std;
namespace Moses
{
namespace {
class MappingBuilder : public lm::ngram::EnumerateVocab {
public:
MappingBuilder(FactorType factorType, FactorCollection &factorCollection, std::vector<lm::WordIndex> &mapping)
: m_factorType(factorType), m_factorCollection(factorCollection), m_mapping(mapping) {}
void Add(lm::WordIndex index, const StringPiece &str) {
m_word.assign(str.data(), str.size());
std::size_t factorId = m_factorCollection.AddFactor(Output, m_factorType, m_word)->GetId();
if (m_mapping.size() <= factorId) {
// 0 is <unk> :-)
m_mapping.resize(factorId + 1);
}
m_mapping[factorId] = index;
}
private:
std::string m_word;
FactorType m_factorType;
FactorCollection &m_factorCollection;
std::vector<lm::WordIndex> &m_mapping;
};
struct KenLMState : public FFState {
lm::ngram::State state;
int Compare(const FFState &o) const {
const KenLMState &other = static_cast<const KenLMState &>(o);
if (state.valid_length_ < other.state.valid_length_) return -1;
if (state.valid_length_ > other.state.valid_length_) return 1;
return std::memcmp(state.history_, other.state.history_, sizeof(lm::WordIndex) * state.valid_length_);
}
};
/** Implementation of single factor LM using Ken's code.
*/
template <class Model> class LanguageModelKen : public LanguageModelSingleFactor
{
private:
Model *m_ngram;
std::vector<lm::WordIndex> m_lmIdLookup;
bool m_lazy;
FFState *m_nullContextState;
FFState *m_beginSentenceState;
void TranslateIDs(const std::vector<const Word*> &contextFactor, lm::WordIndex *indices) const;
public:
LanguageModelKen(bool lazy);
~LanguageModelKen();
bool Load(const std::string &filePath
, FactorType factorType
, size_t nGramOrder);
float GetValueGivenState(const std::vector<const Word*> &contextFactor, FFState &state, unsigned int* len = 0) const;
float GetValueForgotState(const std::vector<const Word*> &contextFactor, FFState &outState, unsigned int* len=0) const;
void GetState(const std::vector<const Word*> &contextFactor, FFState &outState) const;
FFState *GetNullContextState() const;
FFState *GetBeginSentenceState() const;
FFState *NewState(const FFState *from = NULL) const;
lm::WordIndex GetLmID(const std::string &str) const;
void CleanUpAfterSentenceProcessing() {}
void InitializeBeforeSentenceProcessing() {}
};
template <class Model> void LanguageModelKen<Model>::TranslateIDs(const std::vector<const Word*> &contextFactor, lm::WordIndex *indices) const
{
FactorType factorType = GetFactorType();
// set up context
for (size_t i = 0 ; i < contextFactor.size(); i++)
{
std::size_t factor = contextFactor[i]->GetFactor(factorType)->GetId();
lm::WordIndex new_word = (factor >= m_lmIdLookup.size() ? 0 : m_lmIdLookup[factor]);
indices[contextFactor.size() - 1 - i] = new_word;
}
}
template <class Model> LanguageModelKen<Model>::LanguageModelKen(bool lazy)
:m_ngram(NULL), m_lazy(lazy)
{
}
template <class Model> LanguageModelKen<Model>::~LanguageModelKen()
{
delete m_ngram;
}
template <class Model> bool LanguageModelKen<Model>::Load(const std::string &filePath,
FactorType factorType,
size_t /*nGramOrder*/)
{
m_factorType = factorType;
m_filePath = filePath;
FactorCollection &factorCollection = FactorCollection::Instance();
m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, BOS_);
m_sentenceStartArray[m_factorType] = m_sentenceStart;
m_sentenceEnd = factorCollection.AddFactor(Output, m_factorType, EOS_);
m_sentenceEndArray[m_factorType] = m_sentenceEnd;
MappingBuilder builder(m_factorType, factorCollection, m_lmIdLookup);
lm::ngram::Config config;
config.enumerate_vocab = &builder;
config.load_method = m_lazy ? util::LAZY : util::POPULATE_OR_READ;
m_ngram = new Model(filePath.c_str(), config);
m_nGramOrder = m_ngram->Order();
KenLMState *tmp = new KenLMState();
tmp->state = m_ngram->NullContextState();
m_nullContextState = tmp;
tmp = new KenLMState();
tmp->state = m_ngram->BeginSentenceState();
m_beginSentenceState = tmp;
return true;
}
template <class Model> float LanguageModelKen<Model>::GetValueGivenState(const std::vector<const Word*> &contextFactor, FFState &state, unsigned int* len) const
{
if (contextFactor.empty())
{
return 0;
}
lm::ngram::State &realState = static_cast<KenLMState&>(state).state;
std::size_t factor = contextFactor.back()->GetFactor(GetFactorType())->GetId();
lm::WordIndex new_word = (factor >= m_lmIdLookup.size() ? 0 : m_lmIdLookup[factor]);
lm::ngram::State copied(realState);
lm::FullScoreReturn ret(m_ngram->FullScore(copied, new_word, realState));
if (len)
{
*len = ret.ngram_length;
}
return TransformLMScore(ret.prob);
}
template <class Model> float LanguageModelKen<Model>::GetValueForgotState(const vector<const Word*> &contextFactor, FFState &outState, unsigned int* len) const
{
if (contextFactor.empty())
{
static_cast<KenLMState&>(outState).state = m_ngram->NullContextState();
return 0;
}
lm::WordIndex indices[contextFactor.size()];
TranslateIDs(contextFactor, indices);
lm::FullScoreReturn ret(m_ngram->FullScoreForgotState(indices + 1, indices + contextFactor.size(), indices[0], static_cast<KenLMState&>(outState).state));
if (len)
{
*len = ret.ngram_length;
}
return TransformLMScore(ret.prob);
}
template <class Model> void LanguageModelKen<Model>::GetState(const std::vector<const Word*> &contextFactor, FFState &outState) const {
if (contextFactor.empty()) {
static_cast<KenLMState&>(outState).state = m_ngram->NullContextState();
return;
}
lm::WordIndex indices[contextFactor.size()];
TranslateIDs(contextFactor, indices);
m_ngram->GetState(indices, indices + contextFactor.size(), static_cast<KenLMState&>(outState).state);
}
template <class Model> FFState *LanguageModelKen<Model>::GetNullContextState() const {
return m_nullContextState;
}
template <class Model> FFState *LanguageModelKen<Model>::GetBeginSentenceState() const {
return m_beginSentenceState;
}
template <class Model> FFState *LanguageModelKen<Model>::NewState(const FFState *from) const {
KenLMState *ret = new KenLMState;
if (from) {
ret->state = static_cast<const KenLMState&>(*from).state;
}
return ret;
}
template <class Model> lm::WordIndex LanguageModelKen<Model>::GetLmID(const std::string &str) const {
return m_ngram->GetVocabulary().Index(str);
}
} // namespace
LanguageModelSingleFactor *ConstructKenLM(const std::string &file, bool lazy) {
lm::ngram::ModelType model_type;
if (lm::ngram::RecognizeBinary(file.c_str(), model_type)) {
switch(model_type) {
case lm::ngram::HASH_PROBING:
return new LanguageModelKen<lm::ngram::ProbingModel>(lazy);
case lm::ngram::HASH_SORTED:
return new LanguageModelKen<lm::ngram::SortedModel>(lazy);
case lm::ngram::TRIE_SORTED:
return new LanguageModelKen<lm::ngram::TrieModel>(lazy);
default:
std::cerr << "Unrecognized kenlm model type " << model_type << std::endl;
abort();
}
} else {
return new LanguageModelKen<lm::ngram::ProbingModel>(lazy);
}
}
}
<commit_msg>Respect -v 0<commit_after>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
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 <cassert>
#include <cstring>
#include <iostream>
#include "lm/binary_format.hh"
#include "lm/enumerate_vocab.hh"
#include "lm/model.hh"
#include "LanguageModelKen.h"
#include "FFState.h"
#include "TypeDef.h"
#include "Util.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "InputFileStream.h"
#include "StaticData.h"
using namespace std;
namespace Moses
{
namespace {
class MappingBuilder : public lm::ngram::EnumerateVocab {
public:
MappingBuilder(FactorType factorType, FactorCollection &factorCollection, std::vector<lm::WordIndex> &mapping)
: m_factorType(factorType), m_factorCollection(factorCollection), m_mapping(mapping) {}
void Add(lm::WordIndex index, const StringPiece &str) {
m_word.assign(str.data(), str.size());
std::size_t factorId = m_factorCollection.AddFactor(Output, m_factorType, m_word)->GetId();
if (m_mapping.size() <= factorId) {
// 0 is <unk> :-)
m_mapping.resize(factorId + 1);
}
m_mapping[factorId] = index;
}
private:
std::string m_word;
FactorType m_factorType;
FactorCollection &m_factorCollection;
std::vector<lm::WordIndex> &m_mapping;
};
struct KenLMState : public FFState {
lm::ngram::State state;
int Compare(const FFState &o) const {
const KenLMState &other = static_cast<const KenLMState &>(o);
if (state.valid_length_ < other.state.valid_length_) return -1;
if (state.valid_length_ > other.state.valid_length_) return 1;
return std::memcmp(state.history_, other.state.history_, sizeof(lm::WordIndex) * state.valid_length_);
}
};
/** Implementation of single factor LM using Ken's code.
*/
template <class Model> class LanguageModelKen : public LanguageModelSingleFactor
{
private:
Model *m_ngram;
std::vector<lm::WordIndex> m_lmIdLookup;
bool m_lazy;
FFState *m_nullContextState;
FFState *m_beginSentenceState;
void TranslateIDs(const std::vector<const Word*> &contextFactor, lm::WordIndex *indices) const;
public:
LanguageModelKen(bool lazy);
~LanguageModelKen();
bool Load(const std::string &filePath
, FactorType factorType
, size_t nGramOrder);
float GetValueGivenState(const std::vector<const Word*> &contextFactor, FFState &state, unsigned int* len = 0) const;
float GetValueForgotState(const std::vector<const Word*> &contextFactor, FFState &outState, unsigned int* len=0) const;
void GetState(const std::vector<const Word*> &contextFactor, FFState &outState) const;
FFState *GetNullContextState() const;
FFState *GetBeginSentenceState() const;
FFState *NewState(const FFState *from = NULL) const;
lm::WordIndex GetLmID(const std::string &str) const;
void CleanUpAfterSentenceProcessing() {}
void InitializeBeforeSentenceProcessing() {}
};
template <class Model> void LanguageModelKen<Model>::TranslateIDs(const std::vector<const Word*> &contextFactor, lm::WordIndex *indices) const
{
FactorType factorType = GetFactorType();
// set up context
for (size_t i = 0 ; i < contextFactor.size(); i++)
{
std::size_t factor = contextFactor[i]->GetFactor(factorType)->GetId();
lm::WordIndex new_word = (factor >= m_lmIdLookup.size() ? 0 : m_lmIdLookup[factor]);
indices[contextFactor.size() - 1 - i] = new_word;
}
}
template <class Model> LanguageModelKen<Model>::LanguageModelKen(bool lazy)
:m_ngram(NULL), m_lazy(lazy)
{
}
template <class Model> LanguageModelKen<Model>::~LanguageModelKen()
{
delete m_ngram;
}
template <class Model> bool LanguageModelKen<Model>::Load(const std::string &filePath,
FactorType factorType,
size_t /*nGramOrder*/)
{
m_factorType = factorType;
m_filePath = filePath;
FactorCollection &factorCollection = FactorCollection::Instance();
m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, BOS_);
m_sentenceStartArray[m_factorType] = m_sentenceStart;
m_sentenceEnd = factorCollection.AddFactor(Output, m_factorType, EOS_);
m_sentenceEndArray[m_factorType] = m_sentenceEnd;
MappingBuilder builder(m_factorType, factorCollection, m_lmIdLookup);
lm::ngram::Config config;
IFVERBOSE(1) {
config.messages = &std::cerr;
} else {
config.messages = NULL;
}
config.enumerate_vocab = &builder;
config.load_method = m_lazy ? util::LAZY : util::POPULATE_OR_READ;
m_ngram = new Model(filePath.c_str(), config);
m_nGramOrder = m_ngram->Order();
KenLMState *tmp = new KenLMState();
tmp->state = m_ngram->NullContextState();
m_nullContextState = tmp;
tmp = new KenLMState();
tmp->state = m_ngram->BeginSentenceState();
m_beginSentenceState = tmp;
return true;
}
template <class Model> float LanguageModelKen<Model>::GetValueGivenState(const std::vector<const Word*> &contextFactor, FFState &state, unsigned int* len) const
{
if (contextFactor.empty())
{
return 0;
}
lm::ngram::State &realState = static_cast<KenLMState&>(state).state;
std::size_t factor = contextFactor.back()->GetFactor(GetFactorType())->GetId();
lm::WordIndex new_word = (factor >= m_lmIdLookup.size() ? 0 : m_lmIdLookup[factor]);
lm::ngram::State copied(realState);
lm::FullScoreReturn ret(m_ngram->FullScore(copied, new_word, realState));
if (len)
{
*len = ret.ngram_length;
}
return TransformLMScore(ret.prob);
}
template <class Model> float LanguageModelKen<Model>::GetValueForgotState(const vector<const Word*> &contextFactor, FFState &outState, unsigned int* len) const
{
if (contextFactor.empty())
{
static_cast<KenLMState&>(outState).state = m_ngram->NullContextState();
return 0;
}
lm::WordIndex indices[contextFactor.size()];
TranslateIDs(contextFactor, indices);
lm::FullScoreReturn ret(m_ngram->FullScoreForgotState(indices + 1, indices + contextFactor.size(), indices[0], static_cast<KenLMState&>(outState).state));
if (len)
{
*len = ret.ngram_length;
}
return TransformLMScore(ret.prob);
}
template <class Model> void LanguageModelKen<Model>::GetState(const std::vector<const Word*> &contextFactor, FFState &outState) const {
if (contextFactor.empty()) {
static_cast<KenLMState&>(outState).state = m_ngram->NullContextState();
return;
}
lm::WordIndex indices[contextFactor.size()];
TranslateIDs(contextFactor, indices);
m_ngram->GetState(indices, indices + contextFactor.size(), static_cast<KenLMState&>(outState).state);
}
template <class Model> FFState *LanguageModelKen<Model>::GetNullContextState() const {
return m_nullContextState;
}
template <class Model> FFState *LanguageModelKen<Model>::GetBeginSentenceState() const {
return m_beginSentenceState;
}
template <class Model> FFState *LanguageModelKen<Model>::NewState(const FFState *from) const {
KenLMState *ret = new KenLMState;
if (from) {
ret->state = static_cast<const KenLMState&>(*from).state;
}
return ret;
}
template <class Model> lm::WordIndex LanguageModelKen<Model>::GetLmID(const std::string &str) const {
return m_ngram->GetVocabulary().Index(str);
}
} // namespace
LanguageModelSingleFactor *ConstructKenLM(const std::string &file, bool lazy) {
lm::ngram::ModelType model_type;
if (lm::ngram::RecognizeBinary(file.c_str(), model_type)) {
switch(model_type) {
case lm::ngram::HASH_PROBING:
return new LanguageModelKen<lm::ngram::ProbingModel>(lazy);
case lm::ngram::HASH_SORTED:
return new LanguageModelKen<lm::ngram::SortedModel>(lazy);
case lm::ngram::TRIE_SORTED:
return new LanguageModelKen<lm::ngram::TrieModel>(lazy);
default:
std::cerr << "Unrecognized kenlm model type " << model_type << std::endl;
abort();
}
} else {
return new LanguageModelKen<lm::ngram::ProbingModel>(lazy);
}
}
}
<|endoftext|> |
<commit_before>// testdrive.cpp : An example of how to use rosserial in Windows
//
#include "stdafx.h"
#include <string>
#include <stdio.h>
#include "ros.h"
#include <geometry_msgs/Twist.h>
#include <windows.h>
using std::string;
int main(int argc, char* argv[])
{
ros::NodeHandle nh;
if (argc != 2) {
printf("Usage: testdrive host[:port]\n");
return 0;
}
printf("Connecting to server at %s\n", argv[1]);
nh.initNode(argv[1]);
printf("Advertising cmd_vel message\n");
geometry_msgs::Twist twist_msg;
ros::Publisher cmd_vel_pub("husky/cmd_vel", &twist_msg);
nh.advertise(cmd_vel_pub);
printf("Go husky go!\n");
while (1) {
twist_msg.linear.x = 5.1f;
twist_msg.angular.z = -1.8f;
cmd_vel_pub.publish(&twist_msg);
nh.spinOnce();
Sleep(100);
}
return 0;
}
<commit_msg>Updated sample code to be robot agnostic and fixed unitialized message fields.<commit_after>// testdrive.cpp : An example of how to use rosserial in Windows
//
#include "stdafx.h"
#include <string>
#include <stdio.h>
#include "ros.h"
#include <geometry_msgs/Twist.h>
#include <windows.h>
using std::string;
int main(int argc, char* argv[])
{
ros::NodeHandle nh;
if (argc != 2) {
printf("Usage: testdrive host[:port]\n");
return 0;
}
printf("Connecting to server at %s\n", argv[1]);
nh.initNode(argv[1]);
printf("Advertising cmd_vel message\n");
geometry_msgs::Twist twist_msg;
ros::Publisher cmd_vel_pub("cmd_vel", &twist_msg);
nh.advertise(cmd_vel_pub);
printf("Go robot go!\n");
while (1) {
twist_msg.linear.x = 5.1;
twist_msg.linear.y = 0;
twist_msg.linear.z = 0;
twist_msg.angular.x = 0;
twist_msg.angular.y = 0;
twist_msg.angular.z = -1.8;
cmd_vel_pub.publish(&twist_msg);
nh.spinOnce();
Sleep(100);
}
return 0;
}
<|endoftext|> |
<commit_before>#include "machine/test/test.hpp"
#include "marshal.hpp"
#include <iostream>
#include <sstream>
#include <math.h>
class StringUnMarshaller : public UnMarshaller {
public:
std::istringstream sstream;
StringUnMarshaller(STATE) : UnMarshaller(state, sstream) { }
};
class TestUnMarshal : public CxxTest::TestSuite, public VMTest {
public:
StringUnMarshaller* mar;
void setUp() {
create();
mar = new StringUnMarshaller(state);
}
void tearDown() {
destroy();
delete mar;
}
bool tuple_equals(Tuple* x, Tuple* y) {
if(x->num_fields() != y->num_fields()) return false;
for(native_int i = 0; i < x->num_fields(); i++) {
Object* x1 = x->at(state, i);
Object* y1 = y->at(state, i);
if(kind_of<Tuple>(x1)) {
if(!tuple_equals(as<Tuple>(x1), as<Tuple>(y1))) return false;
} else {
if(x1 != y1) return false;
}
}
return true;
}
void test_nil() {
mar->sstream.str(std::string("n\n"));
Object* obj = mar->unmarshal();
TS_ASSERT_EQUALS(obj, cNil);
}
void test_true() {
mar->sstream.str(std::string("t\n"));
Object* obj = mar->unmarshal();
TS_ASSERT_EQUALS(obj, cTrue);
}
void test_false() {
mar->sstream.str(std::string("f\n"));
Object* obj = mar->unmarshal();
TS_ASSERT_EQUALS(obj, cFalse);
}
void test_int() {
mar->sstream.str(std::string("I\n42\n"));
Object* obj = mar->unmarshal();
TS_ASSERT(obj->fixnum_p());
TS_ASSERT_EQUALS(as<Integer>(obj)->to_native(), 66);
}
void test_large_int() {
mar->sstream.str(std::string("I\n100000000\n"));
Object* obj = mar->unmarshal();
TS_ASSERT(kind_of<Integer>(obj));
TS_ASSERT_EQUALS(as<Integer>(obj)->to_ulong_long(), 4294967296ULL);
}
void test_larger_int() {
mar->sstream.str(std::string("I\n9d89d89d89d89dc\n"));
Object* obj = mar->unmarshal();
TS_ASSERT(kind_of<Integer>(obj));
TS_ASSERT_EQUALS(as<Integer>(obj)->to_ulong_long(), 709490156681136604ULL);
}
void test_string_with_encoding() {
mar->sstream.str(std::string("s\nE\n10\nASCII-8BIT\n4\nblah\n"));
Object* obj = mar->unmarshal();
TS_ASSERT(kind_of<String>(obj));
String *str = as<String>(obj);
TS_ASSERT_EQUALS(std::string(str->c_str(state)), "blah");
TS_ASSERT_EQUALS(std::string(str->encoding()->name()->c_str(state)), "ASCII-8BIT");
}
void test_string_no_encoding() {
mar->sstream.str(std::string("s\nE\n0\n\n4\nblah\n"));
Object* obj = mar->unmarshal();
TS_ASSERT(kind_of<String>(obj));
String *str = as<String>(obj);
TS_ASSERT_EQUALS(std::string(str->c_str(state)), "blah");
TS_ASSERT_EQUALS(str->encoding(), cNil);
}
void test_symbol() {
mar->sstream.str(std::string("x\nE\n8\nUS-ASCII\n4\nblah\n"));
Object* obj = mar->unmarshal();
TS_ASSERT(obj->symbol_p());
TS_ASSERT_EQUALS(obj, state->symbol("blah"));
}
void test_tuple() {
mar->sstream.str(std::string("p\n2\nI\n2\nI\n2f\n"));
Object* obj = mar->unmarshal();
TS_ASSERT(kind_of<Tuple>(obj));
Tuple* tup = as<Tuple>(obj);
TS_ASSERT_EQUALS(tup->at(state, 0), Fixnum::from(2));
TS_ASSERT_EQUALS(tup->at(state, 1), Fixnum::from(47));
}
void test_float() {
mar->sstream.str(
std::string("d\n +0.666666666666666629659232512494781985878944396972656250 -2\n"));
Object* obj = mar->unmarshal();
TS_ASSERT(kind_of<Float>(obj));
Float* flt = as<Float>(obj);
TS_ASSERT_EQUALS(flt->value(), 1.0 / 6.0);
mar->sstream.str(
std::string("d\n +0.999999999999999888977697537484345957636833190917968750 1024\n"));
obj = mar->unmarshal();
TS_ASSERT(kind_of<Float>(obj));
flt = as<Float>(obj);
double diff = flt->value() - DBL_MAX;
TS_ASSERT(diff < 0.00000001 && diff > - 0.00000001);
}
void test_float_infinity() {
mar->sstream.str(std::string("d\nInfinity\n"));
Object* obj = mar->unmarshal();
TS_ASSERT(kind_of<Float>(obj));
Float* flt = as<Float>(obj);
TS_ASSERT(std::isinf(flt->value()));
}
void test_float_neg_infinity() {
mar->sstream.str(std::string("d\n-Infinity\n"));
Object* obj = mar->unmarshal();
TS_ASSERT(kind_of<Float>(obj));
Float* flt = as<Float>(obj);
TS_ASSERT(std::isinf(flt->value()));
TS_ASSERT(flt->value() < 0.0);
}
void test_float_nan() {
mar->sstream.str(std::string("d\nNaN\n"));
Object* obj = mar->unmarshal();
TS_ASSERT(kind_of<Float>(obj));
Float* flt = as<Float>(obj);
TS_ASSERT(std::isnan(flt->value()));
}
void test_iseq() {
mar->sstream.str(std::string("i\n1\n0\n"));
Object* obj = mar->unmarshal();
TS_ASSERT(kind_of<InstructionSequence>(obj));
InstructionSequence* seq = as<InstructionSequence>(obj);
TS_ASSERT(kind_of<Tuple>(seq->opcodes()));
TS_ASSERT_EQUALS(seq->opcodes()->num_fields(), 1);
TS_ASSERT_EQUALS(seq->opcodes()->at(state, 0), Fixnum::from(0));
}
void test_compiled_code() {
std::string str = "M\n1\nn\nx\nE\n8\nUS-ASCII\n12\nobject_equal\nx\nE\n8\nUS-ASCII\n4\ntest\ni\n1\n0\nI\na\nI\n0\nI\n0\nI\n0\nI\n0\nn\np\n2\nx\nE\n8\nUS-ASCII\n1\na\nt\nI\n1\np\n2\nI\n1\nI\n2\np\n1\np\n3\nI\n0\nI\n1\nI\n1\nx\nE\n8\nUS-ASCII\n8\nnot_real\np\n1\nx\nE\n8\nUS-ASCII\n4\nblah\n";
mar->sstream.str(str);
Object* obj = mar->unmarshal();
TS_ASSERT(kind_of<CompiledCode>(obj));
CompiledCode* code = as<CompiledCode>(obj);
TS_ASSERT_EQUALS(code->ivars(), cNil);
TS_ASSERT_EQUALS(code->primitive(), state->symbol("object_equal"));
TS_ASSERT_EQUALS(code->name(), state->symbol("test"));
TS_ASSERT(tuple_equals(code->iseq()->opcodes(), Tuple::from(state, 1, Fixnum::from(0))));
TS_ASSERT_EQUALS(code->stack_size(), Fixnum::from(10));
TS_ASSERT_EQUALS(code->local_count(), Fixnum::from(0));
TS_ASSERT_EQUALS(code->required_args(), Fixnum::from(0));
TS_ASSERT_EQUALS(code->post_args(), Fixnum::from(0));
TS_ASSERT_EQUALS(code->total_args(), Fixnum::from(0));
TS_ASSERT_EQUALS(code->splat(), cNil);
TS_ASSERT(tuple_equals(code->keywords(), Tuple::from(state, 2, state->symbol("a"), cTrue)));
TS_ASSERT_EQUALS(code->arity(), Fixnum::from(1));
TS_ASSERT(tuple_equals(code->literals(), Tuple::from(state, 2, Fixnum::from(1), Fixnum::from(2))));
TS_ASSERT(tuple_equals(code->lines(), Tuple::from(state, 1,
Tuple::from(state, 3, Fixnum::from(0), Fixnum::from(1), Fixnum::from(1)))));
TS_ASSERT_EQUALS(code->file(), state->symbol("not_real"));
TS_ASSERT(tuple_equals(code->local_names(), Tuple::from(state, 1, state->symbol("blah"))));
}
};
<commit_msg>Remove VM unmarshal tests.<commit_after><|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/
#ifndef __OPENCV_VIDEOSTAB_HPP__
#define __OPENCV_VIDEOSTAB_HPP__
/**
@defgroup videostab Video Stabilization
The video stabilization module contains a set of functions and classes that can be used to solve the
problem of video stabilization. There are a few methods implemented, most of them are descibed in
the papers @cite OF06 and @cite G11 . However, there are some extensions and deviations from the orginal
paper methods.
### References
1. "Full-Frame Video Stabilization with Motion Inpainting"
Yasuyuki Matsushita, Eyal Ofek, Weina Ge, Xiaoou Tang, Senior Member, and Heung-Yeung Shum
2. "Auto-Directed Video Stabilization with Robust L1 Optimal Camera Paths"
Matthias Grundmann, Vivek Kwatra, Irfan Essa
@{
@defgroup videostab_motion Global Motion Estimation
The video stabilization module contains a set of functions and classes for global motion estimation
between point clouds or between images. In the last case features are extracted and matched
internally. For the sake of convenience the motion estimation functions are wrapped into classes.
Both the functions and the classes are available.
@defgroup videostab_marching Fast Marching Method
The Fast Marching Method @cite Telea04 is used in of the video stabilization routines to do motion and
color inpainting. The method is implemented is a flexible way and it's made public for other users.
@}
*/
#include "opencv2/videostab/stabilizer.hpp"
#include "opencv2/videostab/ring_buffer.hpp"
#endif
<commit_msg>Fixes minor typos.<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/
#ifndef __OPENCV_VIDEOSTAB_HPP__
#define __OPENCV_VIDEOSTAB_HPP__
/**
@defgroup videostab Video Stabilization
The video stabilization module contains a set of functions and classes that can be used to solve the
problem of video stabilization. There are a few methods implemented, most of them are described in
the papers @cite OF06 and @cite G11 . However, there are some extensions and deviations from the original
paper methods.
### References
1. "Full-Frame Video Stabilization with Motion Inpainting"
Yasuyuki Matsushita, Eyal Ofek, Weina Ge, Xiaoou Tang, Senior Member, and Heung-Yeung Shum
2. "Auto-Directed Video Stabilization with Robust L1 Optimal Camera Paths"
Matthias Grundmann, Vivek Kwatra, Irfan Essa
@{
@defgroup videostab_motion Global Motion Estimation
The video stabilization module contains a set of functions and classes for global motion estimation
between point clouds or between images. In the last case features are extracted and matched
internally. For the sake of convenience the motion estimation functions are wrapped into classes.
Both the functions and the classes are available.
@defgroup videostab_marching Fast Marching Method
The Fast Marching Method @cite Telea04 is used in of the video stabilization routines to do motion and
color inpainting. The method is implemented is a flexible way and it's made public for other users.
@}
*/
#include "opencv2/videostab/stabilizer.hpp"
#include "opencv2/videostab/ring_buffer.hpp"
#endif
<|endoftext|> |
<commit_before>
#include "stdafx.h"
#include "fixes.h"
class SizeColossalFix : public TempleFix {
public:
const char* name() override {
return "fixes size_colossal (was misspelled as size_clossal)";
}
void apply() override {
writeHex(0x10278078, "73 69 7A 65 5F 63 6F 6C 6F 73 73 61 6C");
}
} sizeColossalFix;
<commit_msg>Kukri as Martial Weapon partial fix<commit_after>
#include "stdafx.h"
#include "fixes.h"
class SizeColossalFix : public TempleFix {
public:
const char* name() override {
return "fixes size_colossal (was misspelled as size_clossal)";
}
void apply() override {
writeHex(0x10278078, "73 69 7A 65 5F 63 6F 6C 6F 73 73 61 6C");
}
} sizeColossalFix;
class KukriFix : public TempleFix {
public:
const char* name() override {
return "Makes Kukri Proficiency Martial";
}
void apply() override {
writeHex(0x102BFD78 + 30*4, "00 09"); // marks Kukri as Martial in the sense that picking "Martial Weapons Proficiency" will now list Kukri
// TODO: makes the feat "Martial Weapons Proficiency: All" include Kukri proficiency
}
} kukriFix;
<|endoftext|> |
<commit_before>//
// Copyright (c) 2018 Rokas Kupstys
//
// 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 <Urho3D/Resource/XMLFile.h>
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Core/StringUtils.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/ResourceEvents.h>
#include <Urho3D/SystemUI/SystemUI.h>
#include <Tabs/ConsoleTab.h>
#include <Tabs/ResourceTab.h>
#include <Tabs/HierarchyTab.h>
#include <Tabs/InspectorTab.h>
#include <Toolbox/SystemUI/Widgets.h>
#include <ThirdParty/tracy/server/IconsFontAwesome5.h>
#include "Editor.h"
#include "EditorEvents.h"
#include "Project.h"
#include "Tabs/Scene/SceneTab.h"
#include "Tabs/UI/UITab.h"
namespace Urho3D
{
Project::Project(Context* context)
: Object(context)
, assetConverter_(context)
#if URHO3D_PLUGINS
, plugins_(context)
#endif
{
SubscribeToEvent(E_EDITORRESOURCESAVED, std::bind(&Project::SaveProject, this));
SubscribeToEvent(E_RESOURCERENAMED, [this](StringHash, VariantMap& args) {
using namespace ResourceRenamed;
if (args[P_FROM].GetString() == defaultScene_)
defaultScene_ = args[P_TO].GetString();
});
SubscribeToEvent(E_RESOURCEBROWSERDELETE, [this](StringHash, VariantMap& args) {
using namespace ResourceBrowserDelete;
if (args[P_NAME].GetString() == defaultScene_)
defaultScene_ = String::EMPTY;
});
SubscribeToEvent(E_ENDFRAME, [this](StringHash, VariantMap&) {
// Save project every minute.
// TODO: Make save time configurable.
if (saveProjectTimer_.GetMSec(false) >= 60000)
{
SaveProject();
saveProjectTimer_.Reset();
}
});
}
Project::~Project()
{
if (GetSystemUI())
ui::GetIO().IniFilename = nullptr;
if (auto* cache = GetCache())
{
cache->RemoveResourceDir(GetCachePath());
cache->RemoveResourceDir(GetResourcePath());
for (const auto& path : cachedEngineResourcePaths_)
GetCache()->AddResourceDir(path);
}
}
bool Project::LoadProject(const String& projectPath)
{
if (!projectFileDir_.Empty())
// Project is already loaded.
return false;
if (projectPath.Empty())
return false;
projectFileDir_ = AddTrailingSlash(projectPath);
if (!GetFileSystem()->Exists(GetCachePath()))
GetFileSystem()->CreateDirsRecursive(GetCachePath());
if (!GetFileSystem()->Exists(GetResourcePath()))
{
// Initialize new project
GetFileSystem()->CreateDirsRecursive(GetResourcePath());
for (const auto& path : GetCache()->GetResourceDirs())
{
if (path.EndsWith("/EditorData/") || path.Contains("/Autoload/"))
continue;
StringVector names;
URHO3D_LOGINFOF("Importing resources from '%s'", path.CString());
// Copy default resources to the project.
GetFileSystem()->ScanDir(names, path, "*", SCAN_FILES, false);
for (const auto& name : names)
GetFileSystem()->Copy(path + name, GetResourcePath() + name);
GetFileSystem()->ScanDir(names, path, "*", SCAN_DIRS, false);
for (const auto& name : names)
{
if (name == "." || name == "..")
continue;
GetFileSystem()->CopyDir(path + name, GetResourcePath() + name);
}
}
}
// Register asset dirs
GetCache()->AddResourceDir(GetCachePath(), 0);
GetCache()->AddResourceDir(GetResourcePath(), 1);
if (!GetEngine()->IsHeadless())
{
assetConverter_.SetCachePath(GetCachePath());
assetConverter_.AddAssetDirectory(GetResourcePath());
assetConverter_.VerifyCacheAsync();
}
// Unregister engine dirs
auto enginePrefixPath = GetSubsystem<Editor>()->GetCoreResourcePrefixPath();
auto pathsCopy = GetCache()->GetResourceDirs();
cachedEngineResourcePaths_.Clear();
for (const auto& path : pathsCopy)
{
if (path.StartsWith(enginePrefixPath) && !path.EndsWith("/EditorData/"))
{
cachedEngineResourcePaths_.EmplaceBack(path);
GetCache()->RemoveResourceDir(path);
}
}
if (GetSystemUI())
{
uiConfigPath_ = projectFileDir_ + ".ui.ini";
ui::GetIO().IniFilename = uiConfigPath_.CString();
ImGuiSettingsHandler handler;
handler.TypeName = "Project";
handler.TypeHash = ImHash(handler.TypeName, 0, 0);
handler.ReadOpenFn = [](ImGuiContext* context, ImGuiSettingsHandler* handler, const char* name) -> void*
{
if (strcmp(name, "Window") == 0)
return (void*) 1;
return (void*) name;
};
handler.ReadLineFn = [](ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
{
SystemUI* systemUI = ui::GetSystemUI();
auto* editor = systemUI->GetSubsystem<Editor>();
if (entry == (void*) 1)
{
auto* project = systemUI->GetSubsystem<Project>();
project->isNewProject_ = false;
editor->CreateDefaultTabs();
int x, y, w, h;
if (sscanf(line, "Rect=%d,%d,%d,%d", &x, &y, &w, &h) == 4)
{
w = Max(w, 100); // Foot-shooting prevention
h = Max(h, 100);
systemUI->GetGraphics()->SetWindowPosition(x, y);
systemUI->GetGraphics()->SetMode(w, h);
}
else
return;
}
else
{
const char* name = static_cast<const char*>(entry);
Tab* tab = editor->GetTabByName(name);
if (tab == nullptr)
{
StringVector parts = String(name).Split('#');
tab = editor->CreateTab(parts.Front());
}
tab->OnLoadUISettings(name, line);
}
};
handler.WriteAllFn = [](ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
buf->appendf("[Project][Window]\n");
auto* systemUI = ui::GetSystemUI();
auto* editor = systemUI->GetSubsystem<Editor>();
auto* project = systemUI->GetSubsystem<Project>();
IntVector2
wSize = systemUI->GetGraphics()->GetSize();
IntVector2
wPos = systemUI->GetGraphics()->GetWindowPosition();
buf->appendf("Rect=%d,%d,%d,%d\n", wPos.x_, wPos.y_, wSize.x_, wSize.y_);
// Save tabs
for (auto& tab : editor->GetContentTabs())
tab->OnSaveUISettings(buf);
};
ui::GetCurrentContext()->SettingsHandlers.push_back(handler);
}
#if URHO3D_HASH_DEBUG
// StringHashNames.json
{
String filePath(projectFileDir_ + "StringHashNames.json");
if (GetFileSystem()->Exists(filePath))
{
JSONFile file(context_);
if (!file.LoadFile(filePath))
return false;
for (const auto& value : file.GetRoot().GetArray())
{
// Seed global string hash to name map.
StringHash hash(value.GetString());
(void) (hash);
}
}
}
#endif
// Project.json
{
String filePath(projectFileDir_ + "Project.json");
if (GetFileSystem()->Exists(filePath))
{
JSONFile file(context_);
if (!file.LoadFile(filePath))
return false;
const auto& root = file.GetRoot().GetObject();
#if URHO3D_PLUGINS
if (root.Contains("plugins"))
{
const auto& plugins = root["plugins"]->GetArray();
for (const auto& pluginInfoValue : plugins)
{
const JSONObject& pluginInfo = pluginInfoValue.GetObject();
Plugin* plugin = plugins_.Load(pluginInfo["name"]->GetString());
if (pluginInfo["private"]->GetBool())
plugin->SetFlags(plugin->GetFlags() | PLUGIN_PRIVATE);
}
// Tick plugins once to ensure plugins are loaded before loading any possibly open scenes. This makes
// plugins register themselves with the engine so that loaded scenes can properly load components
// provided by plugins. Not doing this would cause scenes to load these components as UnknownComponent.
plugins_.OnEndFrame();
}
#endif
if (root.Contains("default-scene"))
defaultScene_ = root["default-scene"]->GetString();
using namespace EditorProjectLoading;
SendEvent(E_EDITORPROJECTLOADING, P_ROOT, (void*)&root);
}
}
// Settings.json
{
String filePath(projectFileDir_ + "Settings.json");
if (GetFileSystem()->Exists(filePath))
{
JSONFile file(context_);
if (!file.LoadFile(filePath))
return false;
for (auto& pair : file.GetRoot().GetObject())
engineParameters_[pair.first_] = pair.second_.GetVariant();
}
}
return true;
}
bool Project::SaveProject()
{
if (GetEngine()->IsHeadless())
{
URHO3D_LOGERROR("Headless instance is supposed to use project as read-only.");
return false;
}
// Saving project data of tabs may trigger saving resources, which in turn triggers saving editor project. Avoid
// that loop.
UnsubscribeFromEvent(E_EDITORRESOURCESAVED);
if (projectFileDir_.Empty())
{
URHO3D_LOGERROR("Unable to save project. Project path is empty.");
return false;
}
// Project.json
{
JSONFile file(context_);
JSONValue& root = file.GetRoot();
root["version"] = 0;
// Plugins
#if URHO3D_PLUGINS
{
JSONArray plugins{};
for (const auto& plugin : plugins_.GetPlugins())
{
plugins.Push(JSONObject{{"name", plugin->GetName()},
{"private", plugin->GetFlags() & PLUGIN_PRIVATE ? true : false}});
}
Sort(plugins.Begin(), plugins.End(), [](JSONValue& a, JSONValue& b) {
const String& nameA = a.GetObject()["name"]->GetString();
const String& nameB = b.GetObject()["name"]->GetString();
return nameA.Compare(nameB);
});
root["plugins"] = plugins;
}
#endif
root["default-scene"] = defaultScene_;
String filePath(projectFileDir_ + "Project.json");
if (!file.SaveFile(filePath))
{
projectFileDir_.Clear();
URHO3D_LOGERRORF("Saving project to '%s' failed", filePath.CString());
return false;
}
using namespace EditorProjectSaving;
SendEvent(E_EDITORPROJECTSAVING, P_ROOT, (void*)&root);
}
// Settings.json
{
JSONFile file(context_);
JSONValue& root = file.GetRoot();
for (const auto& pair : engineParameters_)
root[pair.first_].SetVariant(pair.second_, context_);
String filePath(projectFileDir_ + "Settings.json");
if (!file.SaveFile(filePath))
{
projectFileDir_.Clear();
URHO3D_LOGERRORF("Saving project to '%s' failed", filePath.CString());
return false;
}
}
#if URHO3D_HASH_DEBUG
// StringHashNames.json
{
auto hashNames = StringHash::GetGlobalStringHashRegister()->GetInternalMap().Values();
Sort(hashNames.Begin(), hashNames.End());
JSONFile file(context_);
JSONArray names;
for (const auto& string : hashNames)
names.Push(string);
file.GetRoot() = names;
String filePath(projectFileDir_ + "StringHashNames.json");
if (!file.SaveFile(filePath))
{
projectFileDir_.Clear();
URHO3D_LOGERRORF("Saving StringHash names to '%s' failed", filePath.CString());
return false;
}
}
#endif
ui::SaveIniSettingsToDisk(uiConfigPath_.CString());
SubscribeToEvent(E_EDITORRESOURCESAVED, std::bind(&Project::SaveProject, this));
return true;
}
String Project::GetCachePath() const
{
if (projectFileDir_.Empty())
return String::EMPTY;
return projectFileDir_ + "Cache/";
}
String Project::GetResourcePath() const
{
if (projectFileDir_.Empty())
return String::EMPTY;
return projectFileDir_ + "Resources/";
}
}
<commit_msg>Editor: Fix crash during project loading when loading plugin fails. Output error instead.<commit_after>//
// Copyright (c) 2018 Rokas Kupstys
//
// 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 <Urho3D/Resource/XMLFile.h>
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Core/StringUtils.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/ResourceEvents.h>
#include <Urho3D/SystemUI/SystemUI.h>
#include <Tabs/ConsoleTab.h>
#include <Tabs/ResourceTab.h>
#include <Tabs/HierarchyTab.h>
#include <Tabs/InspectorTab.h>
#include <Toolbox/SystemUI/Widgets.h>
#include <ThirdParty/tracy/server/IconsFontAwesome5.h>
#include "Editor.h"
#include "EditorEvents.h"
#include "Project.h"
#include "Tabs/Scene/SceneTab.h"
#include "Tabs/UI/UITab.h"
namespace Urho3D
{
Project::Project(Context* context)
: Object(context)
, assetConverter_(context)
#if URHO3D_PLUGINS
, plugins_(context)
#endif
{
SubscribeToEvent(E_EDITORRESOURCESAVED, std::bind(&Project::SaveProject, this));
SubscribeToEvent(E_RESOURCERENAMED, [this](StringHash, VariantMap& args) {
using namespace ResourceRenamed;
if (args[P_FROM].GetString() == defaultScene_)
defaultScene_ = args[P_TO].GetString();
});
SubscribeToEvent(E_RESOURCEBROWSERDELETE, [this](StringHash, VariantMap& args) {
using namespace ResourceBrowserDelete;
if (args[P_NAME].GetString() == defaultScene_)
defaultScene_ = String::EMPTY;
});
SubscribeToEvent(E_ENDFRAME, [this](StringHash, VariantMap&) {
// Save project every minute.
// TODO: Make save time configurable.
if (saveProjectTimer_.GetMSec(false) >= 60000)
{
SaveProject();
saveProjectTimer_.Reset();
}
});
}
Project::~Project()
{
if (GetSystemUI())
ui::GetIO().IniFilename = nullptr;
if (auto* cache = GetCache())
{
cache->RemoveResourceDir(GetCachePath());
cache->RemoveResourceDir(GetResourcePath());
for (const auto& path : cachedEngineResourcePaths_)
GetCache()->AddResourceDir(path);
}
}
bool Project::LoadProject(const String& projectPath)
{
if (!projectFileDir_.Empty())
// Project is already loaded.
return false;
if (projectPath.Empty())
return false;
projectFileDir_ = AddTrailingSlash(projectPath);
if (!GetFileSystem()->Exists(GetCachePath()))
GetFileSystem()->CreateDirsRecursive(GetCachePath());
if (!GetFileSystem()->Exists(GetResourcePath()))
{
// Initialize new project
GetFileSystem()->CreateDirsRecursive(GetResourcePath());
for (const auto& path : GetCache()->GetResourceDirs())
{
if (path.EndsWith("/EditorData/") || path.Contains("/Autoload/"))
continue;
StringVector names;
URHO3D_LOGINFOF("Importing resources from '%s'", path.CString());
// Copy default resources to the project.
GetFileSystem()->ScanDir(names, path, "*", SCAN_FILES, false);
for (const auto& name : names)
GetFileSystem()->Copy(path + name, GetResourcePath() + name);
GetFileSystem()->ScanDir(names, path, "*", SCAN_DIRS, false);
for (const auto& name : names)
{
if (name == "." || name == "..")
continue;
GetFileSystem()->CopyDir(path + name, GetResourcePath() + name);
}
}
}
// Register asset dirs
GetCache()->AddResourceDir(GetCachePath(), 0);
GetCache()->AddResourceDir(GetResourcePath(), 1);
if (!GetEngine()->IsHeadless())
{
assetConverter_.SetCachePath(GetCachePath());
assetConverter_.AddAssetDirectory(GetResourcePath());
assetConverter_.VerifyCacheAsync();
}
// Unregister engine dirs
auto enginePrefixPath = GetSubsystem<Editor>()->GetCoreResourcePrefixPath();
auto pathsCopy = GetCache()->GetResourceDirs();
cachedEngineResourcePaths_.Clear();
for (const auto& path : pathsCopy)
{
if (path.StartsWith(enginePrefixPath) && !path.EndsWith("/EditorData/"))
{
cachedEngineResourcePaths_.EmplaceBack(path);
GetCache()->RemoveResourceDir(path);
}
}
if (GetSystemUI())
{
uiConfigPath_ = projectFileDir_ + ".ui.ini";
ui::GetIO().IniFilename = uiConfigPath_.CString();
ImGuiSettingsHandler handler;
handler.TypeName = "Project";
handler.TypeHash = ImHash(handler.TypeName, 0, 0);
handler.ReadOpenFn = [](ImGuiContext* context, ImGuiSettingsHandler* handler, const char* name) -> void*
{
if (strcmp(name, "Window") == 0)
return (void*) 1;
return (void*) name;
};
handler.ReadLineFn = [](ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
{
SystemUI* systemUI = ui::GetSystemUI();
auto* editor = systemUI->GetSubsystem<Editor>();
if (entry == (void*) 1)
{
auto* project = systemUI->GetSubsystem<Project>();
project->isNewProject_ = false;
editor->CreateDefaultTabs();
int x, y, w, h;
if (sscanf(line, "Rect=%d,%d,%d,%d", &x, &y, &w, &h) == 4)
{
w = Max(w, 100); // Foot-shooting prevention
h = Max(h, 100);
systemUI->GetGraphics()->SetWindowPosition(x, y);
systemUI->GetGraphics()->SetMode(w, h);
}
else
return;
}
else
{
const char* name = static_cast<const char*>(entry);
Tab* tab = editor->GetTabByName(name);
if (tab == nullptr)
{
StringVector parts = String(name).Split('#');
tab = editor->CreateTab(parts.Front());
}
tab->OnLoadUISettings(name, line);
}
};
handler.WriteAllFn = [](ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
buf->appendf("[Project][Window]\n");
auto* systemUI = ui::GetSystemUI();
auto* editor = systemUI->GetSubsystem<Editor>();
auto* project = systemUI->GetSubsystem<Project>();
IntVector2
wSize = systemUI->GetGraphics()->GetSize();
IntVector2
wPos = systemUI->GetGraphics()->GetWindowPosition();
buf->appendf("Rect=%d,%d,%d,%d\n", wPos.x_, wPos.y_, wSize.x_, wSize.y_);
// Save tabs
for (auto& tab : editor->GetContentTabs())
tab->OnSaveUISettings(buf);
};
ui::GetCurrentContext()->SettingsHandlers.push_back(handler);
}
#if URHO3D_HASH_DEBUG
// StringHashNames.json
{
String filePath(projectFileDir_ + "StringHashNames.json");
if (GetFileSystem()->Exists(filePath))
{
JSONFile file(context_);
if (!file.LoadFile(filePath))
return false;
for (const auto& value : file.GetRoot().GetArray())
{
// Seed global string hash to name map.
StringHash hash(value.GetString());
(void) (hash);
}
}
}
#endif
// Project.json
{
String filePath(projectFileDir_ + "Project.json");
if (GetFileSystem()->Exists(filePath))
{
JSONFile file(context_);
if (!file.LoadFile(filePath))
return false;
const auto& root = file.GetRoot().GetObject();
#if URHO3D_PLUGINS
if (root.Contains("plugins"))
{
const auto& plugins = root["plugins"]->GetArray();
for (const auto& pluginInfoValue : plugins)
{
const JSONObject& pluginInfo = pluginInfoValue.GetObject();
const String& pluginName = pluginInfo["name"]->GetString();
if (Plugin* plugin = plugins_.Load(pluginName))
{
if (pluginInfo["private"]->GetBool())
plugin->SetFlags(plugin->GetFlags() | PLUGIN_PRIVATE);
}
else
URHO3D_LOGERRORF("Loading plugin '%s' failed.", pluginName.CString());
}
// Tick plugins once to ensure plugins are loaded before loading any possibly open scenes. This makes
// plugins register themselves with the engine so that loaded scenes can properly load components
// provided by plugins. Not doing this would cause scenes to load these components as UnknownComponent.
plugins_.OnEndFrame();
}
#endif
if (root.Contains("default-scene"))
defaultScene_ = root["default-scene"]->GetString();
using namespace EditorProjectLoading;
SendEvent(E_EDITORPROJECTLOADING, P_ROOT, (void*)&root);
}
}
// Settings.json
{
String filePath(projectFileDir_ + "Settings.json");
if (GetFileSystem()->Exists(filePath))
{
JSONFile file(context_);
if (!file.LoadFile(filePath))
return false;
for (auto& pair : file.GetRoot().GetObject())
engineParameters_[pair.first_] = pair.second_.GetVariant();
}
}
return true;
}
bool Project::SaveProject()
{
if (GetEngine()->IsHeadless())
{
URHO3D_LOGERROR("Headless instance is supposed to use project as read-only.");
return false;
}
// Saving project data of tabs may trigger saving resources, which in turn triggers saving editor project. Avoid
// that loop.
UnsubscribeFromEvent(E_EDITORRESOURCESAVED);
if (projectFileDir_.Empty())
{
URHO3D_LOGERROR("Unable to save project. Project path is empty.");
return false;
}
// Project.json
{
JSONFile file(context_);
JSONValue& root = file.GetRoot();
root["version"] = 0;
// Plugins
#if URHO3D_PLUGINS
{
JSONArray plugins{};
for (const auto& plugin : plugins_.GetPlugins())
{
plugins.Push(JSONObject{{"name", plugin->GetName()},
{"private", plugin->GetFlags() & PLUGIN_PRIVATE ? true : false}});
}
Sort(plugins.Begin(), plugins.End(), [](JSONValue& a, JSONValue& b) {
const String& nameA = a.GetObject()["name"]->GetString();
const String& nameB = b.GetObject()["name"]->GetString();
return nameA.Compare(nameB);
});
root["plugins"] = plugins;
}
#endif
root["default-scene"] = defaultScene_;
String filePath(projectFileDir_ + "Project.json");
if (!file.SaveFile(filePath))
{
projectFileDir_.Clear();
URHO3D_LOGERRORF("Saving project to '%s' failed", filePath.CString());
return false;
}
using namespace EditorProjectSaving;
SendEvent(E_EDITORPROJECTSAVING, P_ROOT, (void*)&root);
}
// Settings.json
{
JSONFile file(context_);
JSONValue& root = file.GetRoot();
for (const auto& pair : engineParameters_)
root[pair.first_].SetVariant(pair.second_, context_);
String filePath(projectFileDir_ + "Settings.json");
if (!file.SaveFile(filePath))
{
projectFileDir_.Clear();
URHO3D_LOGERRORF("Saving project to '%s' failed", filePath.CString());
return false;
}
}
#if URHO3D_HASH_DEBUG
// StringHashNames.json
{
auto hashNames = StringHash::GetGlobalStringHashRegister()->GetInternalMap().Values();
Sort(hashNames.Begin(), hashNames.End());
JSONFile file(context_);
JSONArray names;
for (const auto& string : hashNames)
names.Push(string);
file.GetRoot() = names;
String filePath(projectFileDir_ + "StringHashNames.json");
if (!file.SaveFile(filePath))
{
projectFileDir_.Clear();
URHO3D_LOGERRORF("Saving StringHash names to '%s' failed", filePath.CString());
return false;
}
}
#endif
ui::SaveIniSettingsToDisk(uiConfigPath_.CString());
SubscribeToEvent(E_EDITORRESOURCESAVED, std::bind(&Project::SaveProject, this));
return true;
}
String Project::GetCachePath() const
{
if (projectFileDir_.Empty())
return String::EMPTY;
return projectFileDir_ + "Cache/";
}
String Project::GetResourcePath() const
{
if (projectFileDir_.Empty())
return String::EMPTY;
return projectFileDir_ + "Resources/";
}
}
<|endoftext|> |
<commit_before><commit_msg>testing<commit_after><|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief simple arango importer
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "BasicsC/common.h"
#include <stdio.h>
#include <fstream>
#include "ArangoShell/ArangoClient.h"
#include "Basics/FileUtils.h"
#include "Basics/ProgramOptions.h"
#include "Basics/ProgramOptionsDescription.h"
#include "Basics/StringUtils.h"
#include "BasicsC/files.h"
#include "BasicsC/init.h"
#include "BasicsC/logging.h"
#include "BasicsC/tri-strings.h"
#include "BasicsC/terminal-utils.h"
#include "ImportHelper.h"
#include "Rest/Endpoint.h"
#include "Rest/InitialiseRest.h"
#include "Rest/HttpResponse.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
#include "V8Client/V8ClientConnection.h"
using namespace std;
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace triagens::rest;
using namespace triagens::v8client;
using namespace triagens::arango;
// -----------------------------------------------------------------------------
// --SECTION-- private variables
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Shell
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief base class for clients
////////////////////////////////////////////////////////////////////////////////
ArangoClient BaseClient;
////////////////////////////////////////////////////////////////////////////////
/// @brief the initial default connection
////////////////////////////////////////////////////////////////////////////////
V8ClientConnection* ClientConnection = 0;
////////////////////////////////////////////////////////////////////////////////
/// @brief max size body size (used for imports)
////////////////////////////////////////////////////////////////////////////////
static uint64_t ChunkSize = 1024 * 1024 * 4;
////////////////////////////////////////////////////////////////////////////////
/// @brief quote character(s)
////////////////////////////////////////////////////////////////////////////////
static string Quote = "\"";
////////////////////////////////////////////////////////////////////////////////
/// @brief separator
////////////////////////////////////////////////////////////////////////////////
static string Separator = ",";
////////////////////////////////////////////////////////////////////////////////
/// @brief file-name
////////////////////////////////////////////////////////////////////////////////
static string FileName = "";
////////////////////////////////////////////////////////////////////////////////
/// @brief collection-name
////////////////////////////////////////////////////////////////////////////////
static string CollectionName = "";
////////////////////////////////////////////////////////////////////////////////
/// @brief import type
////////////////////////////////////////////////////////////////////////////////
static string TypeImport = "json";
////////////////////////////////////////////////////////////////////////////////
/// @brief create collection if necessary
////////////////////////////////////////////////////////////////////////////////
static bool CreateCollection = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief progress
////////////////////////////////////////////////////////////////////////////////
static bool Progress = true;
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Shell
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief parses the program options
////////////////////////////////////////////////////////////////////////////////
static void ParseProgramOptions (int argc, char* argv[]) {
ProgramOptionsDescription deprecatedOptions("DEPRECATED options");
deprecatedOptions
("max-upload-size", &ChunkSize, "size for individual data batches (in bytes)")
;
ProgramOptionsDescription description("STANDARD options");
description
("file", &FileName, "file name (\"-\" for STDIN)")
("batch-size", &ChunkSize, "size for individual data batches (in bytes)")
("collection", &CollectionName, "collection name")
("create-collection", &CreateCollection, "create collection if it does not yet exist")
("type", &TypeImport, "type of file (\"csv\", \"tsv\", or \"json\")")
("quote", &Quote, "quote character(s)")
("separator", &Separator, "separator")
("progress", &Progress, "show progress")
(deprecatedOptions, true)
;
BaseClient.setupGeneral(description);
BaseClient.setupServer(description);
vector<string> arguments;
description.arguments(&arguments);
ProgramOptions options;
BaseClient.parse(options, description, argc, argv, "arangoimp.conf");
if (FileName == "" && arguments.size() > 0) {
FileName = arguments[0];
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Shell
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief startup and exit functions
////////////////////////////////////////////////////////////////////////////////
static void arangoimpEntryFunction ();
static void arangoimpExitFunction (int, void*);
#ifdef _WIN32
// .............................................................................
// Call this function to do various initialistions for windows only
// .............................................................................
void arangoimpEntryFunction() {
int maxOpenFiles = 1024;
int res = 0;
// ...........................................................................
// Uncomment this to call this for extended debug information.
// If you familiar with valgrind ... then this is not like that, however
// you do get some similar functionality.
// ...........................................................................
//res = initialiseWindows(TRI_WIN_INITIAL_SET_DEBUG_FLAG, 0);
res = initialiseWindows(TRI_WIN_INITIAL_SET_INVALID_HANLE_HANDLER, 0);
if (res != 0) {
_exit(1);
}
res = initialiseWindows(TRI_WIN_INITIAL_SET_MAX_STD_IO,(const char*)(&maxOpenFiles));
if (res != 0) {
_exit(1);
}
res = initialiseWindows(TRI_WIN_INITIAL_WSASTARTUP_FUNCTION_CALL, 0);
if (res != 0) {
_exit(1);
}
TRI_Application_Exit_SetExit(arangoimpExitFunction);
}
static void arangoimpExitFunction(int exitCode, void* data) {
int res = 0;
// ...........................................................................
// TODO: need a terminate function for windows to be called and cleanup
// any windows specific stuff.
// ...........................................................................
res = finaliseWindows(TRI_WIN_FINAL_WSASTARTUP_FUNCTION_CALL, 0);
if (res != 0) {
exit(1);
}
exit(exitCode);
}
#else
static void arangoimpEntryFunction() {
}
static void arangoimpExitFunction(int exitCode, void* data) {
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief main
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char* argv[]) {
int ret = EXIT_SUCCESS;
arangoimpEntryFunction();
TRIAGENS_C_INITIALISE(argc, argv);
TRIAGENS_REST_INITIALISE(argc, argv);
TRI_InitialiseLogging(false);
BaseClient.setEndpointString(Endpoint::getDefaultEndpoint());
// .............................................................................
// parse the program options
// .............................................................................
ParseProgramOptions(argc, argv);
// .............................................................................
// set-up client connection
// .............................................................................
BaseClient.createEndpoint();
if (BaseClient.endpointServer() == 0) {
cerr << "invalid value for --server.endpoint ('" << BaseClient.endpointString() << "')" << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
ClientConnection = new V8ClientConnection(BaseClient.endpointServer(),
BaseClient.databaseName(),
BaseClient.username(),
BaseClient.password(),
BaseClient.requestTimeout(),
BaseClient.connectTimeout(),
ArangoClient::DEFAULT_RETRIES,
BaseClient.sslProtocol(),
false);
if (! ClientConnection->isConnected() || ClientConnection->getLastHttpReturnCode() != HttpResponse::OK) {
cerr << "Could not connect to endpoint '" << BaseClient.endpointServer()->getSpecification()
<< "', database: '" << BaseClient.databaseName() << "'" << endl;
cerr << "Error message: '" << ClientConnection->getErrorMessage() << "'" << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
// successfully connected
cout << "Connected to ArangoDB '" << BaseClient.endpointServer()->getSpecification()
<< "', version " << ClientConnection->getVersion() << ", database: '"
<< BaseClient.databaseName() << "', username: '" << BaseClient.username() << "'" << endl;
cout << "----------------------------------------" << endl;
cout << "database: " << BaseClient.databaseName() << endl;
cout << "collection: " << CollectionName << endl;
cout << "create: " << (CreateCollection ? "yes" : "no") << endl;
cout << "file: " << FileName << endl;
cout << "type: " << TypeImport << endl;
if (TypeImport == "csv") {
cout << "quote: " << Quote << endl;
cout << "separator: " << Separator << endl;
}
cout << "connect timeout: " << BaseClient.connectTimeout() << endl;
cout << "request timeout: " << BaseClient.requestTimeout() << endl;
cout << "----------------------------------------" << endl;
ImportHelper ih(ClientConnection->getHttpClient(), ChunkSize);
// create colletion
if (CreateCollection) {
ih.setCreateCollection(true);
}
// quote
if (Quote.length() <= 1) {
ih.setQuote(Quote);
}
else {
cerr << "Wrong length of quote character." << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
// separator
if (Separator.length() == 1) {
ih.setSeparator(Separator);
}
else {
cerr << "Separator must be exactly one character." << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
// collection name
if (CollectionName == "") {
cerr << "collection name is missing." << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
// filename
if (FileName == "") {
cerr << "file name is missing." << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
if (FileName != "-" && ! FileUtils::isRegularFile(FileName)) {
cerr << "file '" << FileName << "' is not a regular file." << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
// progress
if (Progress) {
ih.setProgress(true);
}
// import type
bool ok = false;
if (TypeImport == "csv") {
cout << "Starting CSV import..." << endl;
ok = ih.importDelimited(CollectionName, FileName, ImportHelper::CSV);
}
else if (TypeImport == "tsv") {
cout << "Starting TSV import..." << endl;
ih.setQuote("");
ih.setSeparator("\\t");
ok = ih.importDelimited(CollectionName, FileName, ImportHelper::TSV);
}
else if (TypeImport == "json") {
cout << "Starting JSON import..." << endl;
ok = ih.importJson(CollectionName, FileName);
}
else {
cerr << "Wrong type '" << TypeImport << "'." << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
cout << endl;
// give information about import
if (ok) {
cout << "created: " << ih.getImportedLines() << endl;
cout << "errors: " << ih.getErrorLines() << endl;
cout << "total: " << ih.getReadLines() << endl;
}
else {
cerr << "error message: " << ih.getErrorMessage() << endl;
}
// calling dispose in V8 3.10.x causes a segfault. the v8 docs says its not necessary to call it upon program termination
// v8::V8::Dispose();
TRIAGENS_REST_SHUTDOWN;
arangoimpExitFunction(ret, NULL);
return ret;
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>slightly updated error messages<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief simple arango importer
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "BasicsC/common.h"
#include <stdio.h>
#include <fstream>
#include "ArangoShell/ArangoClient.h"
#include "Basics/FileUtils.h"
#include "Basics/ProgramOptions.h"
#include "Basics/ProgramOptionsDescription.h"
#include "Basics/StringUtils.h"
#include "BasicsC/files.h"
#include "BasicsC/init.h"
#include "BasicsC/logging.h"
#include "BasicsC/tri-strings.h"
#include "BasicsC/terminal-utils.h"
#include "ImportHelper.h"
#include "Rest/Endpoint.h"
#include "Rest/InitialiseRest.h"
#include "Rest/HttpResponse.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
#include "V8Client/V8ClientConnection.h"
using namespace std;
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace triagens::rest;
using namespace triagens::v8client;
using namespace triagens::arango;
// -----------------------------------------------------------------------------
// --SECTION-- private variables
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Shell
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief base class for clients
////////////////////////////////////////////////////////////////////////////////
ArangoClient BaseClient;
////////////////////////////////////////////////////////////////////////////////
/// @brief the initial default connection
////////////////////////////////////////////////////////////////////////////////
V8ClientConnection* ClientConnection = 0;
////////////////////////////////////////////////////////////////////////////////
/// @brief max size body size (used for imports)
////////////////////////////////////////////////////////////////////////////////
static uint64_t ChunkSize = 1024 * 1024 * 4;
////////////////////////////////////////////////////////////////////////////////
/// @brief quote character(s)
////////////////////////////////////////////////////////////////////////////////
static string Quote = "\"";
////////////////////////////////////////////////////////////////////////////////
/// @brief separator
////////////////////////////////////////////////////////////////////////////////
static string Separator = ",";
////////////////////////////////////////////////////////////////////////////////
/// @brief file-name
////////////////////////////////////////////////////////////////////////////////
static string FileName = "";
////////////////////////////////////////////////////////////////////////////////
/// @brief collection-name
////////////////////////////////////////////////////////////////////////////////
static string CollectionName = "";
////////////////////////////////////////////////////////////////////////////////
/// @brief import type
////////////////////////////////////////////////////////////////////////////////
static string TypeImport = "json";
////////////////////////////////////////////////////////////////////////////////
/// @brief create collection if necessary
////////////////////////////////////////////////////////////////////////////////
static bool CreateCollection = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief progress
////////////////////////////////////////////////////////////////////////////////
static bool Progress = true;
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Shell
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief parses the program options
////////////////////////////////////////////////////////////////////////////////
static void ParseProgramOptions (int argc, char* argv[]) {
ProgramOptionsDescription deprecatedOptions("DEPRECATED options");
deprecatedOptions
("max-upload-size", &ChunkSize, "size for individual data batches (in bytes)")
;
ProgramOptionsDescription description("STANDARD options");
description
("file", &FileName, "file name (\"-\" for STDIN)")
("batch-size", &ChunkSize, "size for individual data batches (in bytes)")
("collection", &CollectionName, "collection name")
("create-collection", &CreateCollection, "create collection if it does not yet exist")
("type", &TypeImport, "type of file (\"csv\", \"tsv\", or \"json\")")
("quote", &Quote, "quote character(s)")
("separator", &Separator, "separator")
("progress", &Progress, "show progress")
(deprecatedOptions, true)
;
BaseClient.setupGeneral(description);
BaseClient.setupServer(description);
vector<string> arguments;
description.arguments(&arguments);
ProgramOptions options;
BaseClient.parse(options, description, argc, argv, "arangoimp.conf");
if (FileName == "" && arguments.size() > 0) {
FileName = arguments[0];
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Shell
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief startup and exit functions
////////////////////////////////////////////////////////////////////////////////
static void arangoimpEntryFunction ();
static void arangoimpExitFunction (int, void*);
#ifdef _WIN32
// .............................................................................
// Call this function to do various initialistions for windows only
// .............................................................................
void arangoimpEntryFunction() {
int maxOpenFiles = 1024;
int res = 0;
// ...........................................................................
// Uncomment this to call this for extended debug information.
// If you familiar with valgrind ... then this is not like that, however
// you do get some similar functionality.
// ...........................................................................
//res = initialiseWindows(TRI_WIN_INITIAL_SET_DEBUG_FLAG, 0);
res = initialiseWindows(TRI_WIN_INITIAL_SET_INVALID_HANLE_HANDLER, 0);
if (res != 0) {
_exit(1);
}
res = initialiseWindows(TRI_WIN_INITIAL_SET_MAX_STD_IO,(const char*)(&maxOpenFiles));
if (res != 0) {
_exit(1);
}
res = initialiseWindows(TRI_WIN_INITIAL_WSASTARTUP_FUNCTION_CALL, 0);
if (res != 0) {
_exit(1);
}
TRI_Application_Exit_SetExit(arangoimpExitFunction);
}
static void arangoimpExitFunction(int exitCode, void* data) {
int res = 0;
// ...........................................................................
// TODO: need a terminate function for windows to be called and cleanup
// any windows specific stuff.
// ...........................................................................
res = finaliseWindows(TRI_WIN_FINAL_WSASTARTUP_FUNCTION_CALL, 0);
if (res != 0) {
exit(1);
}
exit(exitCode);
}
#else
static void arangoimpEntryFunction() {
}
static void arangoimpExitFunction(int exitCode, void* data) {
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief main
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char* argv[]) {
int ret = EXIT_SUCCESS;
arangoimpEntryFunction();
TRIAGENS_C_INITIALISE(argc, argv);
TRIAGENS_REST_INITIALISE(argc, argv);
TRI_InitialiseLogging(false);
BaseClient.setEndpointString(Endpoint::getDefaultEndpoint());
// .............................................................................
// parse the program options
// .............................................................................
ParseProgramOptions(argc, argv);
// .............................................................................
// set-up client connection
// .............................................................................
BaseClient.createEndpoint();
if (BaseClient.endpointServer() == 0) {
cerr << "invalid value for --server.endpoint ('" << BaseClient.endpointString() << "')" << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
ClientConnection = new V8ClientConnection(BaseClient.endpointServer(),
BaseClient.databaseName(),
BaseClient.username(),
BaseClient.password(),
BaseClient.requestTimeout(),
BaseClient.connectTimeout(),
ArangoClient::DEFAULT_RETRIES,
BaseClient.sslProtocol(),
false);
if (! ClientConnection->isConnected() ||
ClientConnection->getLastHttpReturnCode() != HttpResponse::OK) {
cerr << "Could not connect to endpoint '" << BaseClient.endpointServer()->getSpecification()
<< "', database: '" << BaseClient.databaseName() << "'" << endl;
cerr << "Error message: '" << ClientConnection->getErrorMessage() << "'" << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
// successfully connected
cout << "Connected to ArangoDB '" << BaseClient.endpointServer()->getSpecification()
<< "', version " << ClientConnection->getVersion() << ", database: '"
<< BaseClient.databaseName() << "', username: '" << BaseClient.username() << "'" << endl;
cout << "----------------------------------------" << endl;
cout << "database: " << BaseClient.databaseName() << endl;
cout << "collection: " << CollectionName << endl;
cout << "create: " << (CreateCollection ? "yes" : "no") << endl;
cout << "file: " << FileName << endl;
cout << "type: " << TypeImport << endl;
if (TypeImport == "csv") {
cout << "quote: " << Quote << endl;
cout << "separator: " << Separator << endl;
}
cout << "connect timeout: " << BaseClient.connectTimeout() << endl;
cout << "request timeout: " << BaseClient.requestTimeout() << endl;
cout << "----------------------------------------" << endl;
ImportHelper ih(ClientConnection->getHttpClient(), ChunkSize);
// create colletion
if (CreateCollection) {
ih.setCreateCollection(true);
}
// quote
if (Quote.length() <= 1) {
ih.setQuote(Quote);
}
else {
cerr << "Wrong length of quote character." << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
// separator
if (Separator.length() == 1) {
ih.setSeparator(Separator);
}
else {
cerr << "Separator must be exactly one character." << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
// collection name
if (CollectionName == "") {
cerr << "Collection name is missing." << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
// filename
if (FileName == "") {
cerr << "File name is missing." << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
if (FileName != "-" && ! FileUtils::isRegularFile(FileName)) {
cerr << "Cannot open file '" << FileName << "'" << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
// progress
if (Progress) {
ih.setProgress(true);
}
// import type
bool ok = false;
if (TypeImport == "csv") {
cout << "Starting CSV import..." << endl;
ok = ih.importDelimited(CollectionName, FileName, ImportHelper::CSV);
}
else if (TypeImport == "tsv") {
cout << "Starting TSV import..." << endl;
ih.setQuote("");
ih.setSeparator("\\t");
ok = ih.importDelimited(CollectionName, FileName, ImportHelper::TSV);
}
else if (TypeImport == "json") {
cout << "Starting JSON import..." << endl;
ok = ih.importJson(CollectionName, FileName);
}
else {
cerr << "Wrong type '" << TypeImport << "'." << endl;
TRI_EXIT_FUNCTION(EXIT_FAILURE, NULL);
}
cout << endl;
// give information about import
if (ok) {
cout << "created: " << ih.getImportedLines() << endl;
cout << "errors: " << ih.getErrorLines() << endl;
cout << "total: " << ih.getReadLines() << endl;
}
else {
cerr << "error message: " << ih.getErrorMessage() << endl;
}
TRIAGENS_REST_SHUTDOWN;
arangoimpExitFunction(ret, NULL);
return ret;
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This is a port of ManifestParser.cc from WebKit/WebCore/loader/appcache.
/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 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 APPLE INC. ``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 APPLE INC. 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 "webkit/appcache/manifest_parser.h"
#include "base/i18n/icu_string_conversions.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"
namespace appcache {
enum Mode {
EXPLICIT,
FALLBACK,
ONLINE_WHITELIST,
UNKNOWN,
};
Manifest::Manifest() : online_whitelist_all(false) {}
Manifest::~Manifest() {}
bool ParseManifest(const GURL& manifest_url, const char* data, int length,
Manifest& manifest) {
static const std::wstring kSignature(L"CACHE MANIFEST");
DCHECK(manifest.explicit_urls.empty());
DCHECK(manifest.fallback_namespaces.empty());
DCHECK(manifest.online_whitelist_namespaces.empty());
DCHECK(!manifest.online_whitelist_all);
Mode mode = EXPLICIT;
std::wstring data_string;
// TODO(jennb): cannot do UTF8ToWide(data, length, &data_string);
// until UTF8ToWide uses 0xFFFD Unicode replacement character.
base::CodepageToWide(std::string(data, length), base::kCodepageUTF8,
base::OnStringConversionError::SUBSTITUTE, &data_string);
const wchar_t* p = data_string.c_str();
const wchar_t* end = p + data_string.length();
// Look for the magic signature: "^\xFEFF?CACHE MANIFEST[ \t]?"
// Example: "CACHE MANIFEST #comment" is a valid signature.
// Example: "CACHE MANIFEST;V2" is not.
// When the input data starts with a UTF-8 Byte-Order-Mark
// (0xEF, 0xBB, 0xBF), the UTF8ToWide() function converts it to a
// Unicode BOM (U+FEFF). Skip a converted Unicode BOM if it exists.
int bom_offset = 0;
if (!data_string.empty() && data_string[0] == 0xFEFF) {
bom_offset = 1;
++p;
}
if (p >= end ||
data_string.compare(bom_offset, kSignature.length(), kSignature)) {
return false;
}
p += kSignature.length(); // Skip past "CACHE MANIFEST"
// Character after "CACHE MANIFEST" must be whitespace.
if (p < end && *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r')
return false;
// Skip to the end of the line.
while (p < end && *p != '\r' && *p != '\n')
++p;
while (1) {
// Skip whitespace
while (p < end && (*p == '\n' || *p == '\r' || *p == ' ' || *p == '\t'))
++p;
if (p == end)
break;
const wchar_t* line_start = p;
// Find the end of the line
while (p < end && *p != '\r' && *p != '\n')
++p;
// Check if we have a comment
if (*line_start == '#')
continue;
// Get rid of trailing whitespace
const wchar_t* tmp = p - 1;
while (tmp > line_start && (*tmp == ' ' || *tmp == '\t'))
--tmp;
std::wstring line(line_start, tmp - line_start + 1);
if (line == L"CACHE:") {
mode = EXPLICIT;
} else if (line == L"FALLBACK:") {
mode = FALLBACK;
} else if (line == L"NETWORK:") {
mode = ONLINE_WHITELIST;
} else if (*(line.end() - 1) == ':') {
mode = UNKNOWN;
} else if (mode == UNKNOWN) {
continue;
} else if (line == L"*" && mode == ONLINE_WHITELIST) {
manifest.online_whitelist_all = true;
continue;
} else if (mode == EXPLICIT || mode == ONLINE_WHITELIST) {
const wchar_t *line_p = line.c_str();
const wchar_t *line_end = line_p + line.length();
// Look for whitespace separating the URL from subsequent ignored tokens.
while (line_p < line_end && *line_p != '\t' && *line_p != ' ')
++line_p;
string16 url16;
WideToUTF16(line.c_str(), line_p - line.c_str(), &url16);
GURL url = manifest_url.Resolve(url16);
if (!url.is_valid())
continue;
if (url.has_ref()) {
GURL::Replacements replacements;
replacements.ClearRef();
url = url.ReplaceComponents(replacements);
}
// Scheme component must be the same as the manifest URL's.
if (url.scheme() != manifest_url.scheme()) {
continue;
}
// If the manifest's scheme is https:, then manifest URL must have same
// origin as resulting absolute URL.
if (mode == EXPLICIT && manifest_url.SchemeIsSecure() &&
manifest_url.GetOrigin() != url.GetOrigin()) {
continue;
}
if (mode == EXPLICIT) {
manifest.explicit_urls.insert(url.spec());
} else {
manifest.online_whitelist_namespaces.push_back(url);
}
} else if (mode == FALLBACK) {
const wchar_t* line_p = line.c_str();
const wchar_t* line_end = line_p + line.length();
// Look for whitespace separating the two URLs
while (line_p < line_end && *line_p != '\t' && *line_p != ' ')
++line_p;
if (line_p == line_end) {
// There was no whitespace separating the URLs.
continue;
}
string16 namespace_url16;
WideToUTF16(line.c_str(), line_p - line.c_str(), &namespace_url16);
GURL namespace_url = manifest_url.Resolve(namespace_url16);
if (!namespace_url.is_valid())
continue;
if (namespace_url.has_ref()) {
GURL::Replacements replacements;
replacements.ClearRef();
namespace_url = namespace_url.ReplaceComponents(replacements);
}
// Fallback namespace URL must have the same scheme, host and port
// as the manifest's URL.
if (manifest_url.GetOrigin() != namespace_url.GetOrigin()) {
continue;
}
// Skip whitespace separating fallback namespace from URL.
while (line_p < line_end && (*line_p == '\t' || *line_p == ' '))
++line_p;
// Look for whitespace separating the URL from subsequent ignored tokens.
const wchar_t* fallback_start = line_p;
while (line_p < line_end && *line_p != '\t' && *line_p != ' ')
++line_p;
string16 fallback_url16;
WideToUTF16(fallback_start, line_p - fallback_start, &fallback_url16);
GURL fallback_url = manifest_url.Resolve(fallback_url16);
if (!fallback_url.is_valid())
continue;
if (fallback_url.has_ref()) {
GURL::Replacements replacements;
replacements.ClearRef();
fallback_url = fallback_url.ReplaceComponents(replacements);
}
// Fallback entry URL must have the same scheme, host and port
// as the manifest's URL.
if (manifest_url.GetOrigin() != fallback_url.GetOrigin()) {
continue;
}
// Store regardless of duplicate namespace URL. Only first match
// will ever be used.
manifest.fallback_namespaces.push_back(
FallbackNamespace(namespace_url, fallback_url));
} else {
NOTREACHED();
}
}
return true;
}
} // namespace appcache
<commit_msg>appcache: document that the manifest parsing algorithm is fixed<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This is a port of ManifestParser.cc from WebKit/WebCore/loader/appcache.
/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 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 APPLE INC. ``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 APPLE INC. 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 "webkit/appcache/manifest_parser.h"
#include "base/i18n/icu_string_conversions.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"
namespace appcache {
enum Mode {
EXPLICIT,
FALLBACK,
ONLINE_WHITELIST,
UNKNOWN,
};
Manifest::Manifest() : online_whitelist_all(false) {}
Manifest::~Manifest() {}
bool ParseManifest(const GURL& manifest_url, const char* data, int length,
Manifest& manifest) {
// This is an implementation of the parsing algorithm specified in
// the HTML5 offline web application docs:
// http://www.w3.org/TR/html5/offline.html
// Do not modify it without consulting those docs.
// Though you might be tempted to convert these wstrings to UTF-8 or
// string16, this implementation seems simpler given the constraints.
static const std::wstring kSignature(L"CACHE MANIFEST");
DCHECK(manifest.explicit_urls.empty());
DCHECK(manifest.fallback_namespaces.empty());
DCHECK(manifest.online_whitelist_namespaces.empty());
DCHECK(!manifest.online_whitelist_all);
Mode mode = EXPLICIT;
std::wstring data_string;
// TODO(jennb): cannot do UTF8ToWide(data, length, &data_string);
// until UTF8ToWide uses 0xFFFD Unicode replacement character.
base::CodepageToWide(std::string(data, length), base::kCodepageUTF8,
base::OnStringConversionError::SUBSTITUTE, &data_string);
const wchar_t* p = data_string.c_str();
const wchar_t* end = p + data_string.length();
// Look for the magic signature: "^\xFEFF?CACHE MANIFEST[ \t]?"
// Example: "CACHE MANIFEST #comment" is a valid signature.
// Example: "CACHE MANIFEST;V2" is not.
// When the input data starts with a UTF-8 Byte-Order-Mark
// (0xEF, 0xBB, 0xBF), the UTF8ToWide() function converts it to a
// Unicode BOM (U+FEFF). Skip a converted Unicode BOM if it exists.
int bom_offset = 0;
if (!data_string.empty() && data_string[0] == 0xFEFF) {
bom_offset = 1;
++p;
}
if (p >= end ||
data_string.compare(bom_offset, kSignature.length(), kSignature)) {
return false;
}
p += kSignature.length(); // Skip past "CACHE MANIFEST"
// Character after "CACHE MANIFEST" must be whitespace.
if (p < end && *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r')
return false;
// Skip to the end of the line.
while (p < end && *p != '\r' && *p != '\n')
++p;
while (1) {
// Skip whitespace
while (p < end && (*p == '\n' || *p == '\r' || *p == ' ' || *p == '\t'))
++p;
if (p == end)
break;
const wchar_t* line_start = p;
// Find the end of the line
while (p < end && *p != '\r' && *p != '\n')
++p;
// Check if we have a comment
if (*line_start == '#')
continue;
// Get rid of trailing whitespace
const wchar_t* tmp = p - 1;
while (tmp > line_start && (*tmp == ' ' || *tmp == '\t'))
--tmp;
std::wstring line(line_start, tmp - line_start + 1);
if (line == L"CACHE:") {
mode = EXPLICIT;
} else if (line == L"FALLBACK:") {
mode = FALLBACK;
} else if (line == L"NETWORK:") {
mode = ONLINE_WHITELIST;
} else if (*(line.end() - 1) == ':') {
mode = UNKNOWN;
} else if (mode == UNKNOWN) {
continue;
} else if (line == L"*" && mode == ONLINE_WHITELIST) {
manifest.online_whitelist_all = true;
continue;
} else if (mode == EXPLICIT || mode == ONLINE_WHITELIST) {
const wchar_t *line_p = line.c_str();
const wchar_t *line_end = line_p + line.length();
// Look for whitespace separating the URL from subsequent ignored tokens.
while (line_p < line_end && *line_p != '\t' && *line_p != ' ')
++line_p;
string16 url16;
WideToUTF16(line.c_str(), line_p - line.c_str(), &url16);
GURL url = manifest_url.Resolve(url16);
if (!url.is_valid())
continue;
if (url.has_ref()) {
GURL::Replacements replacements;
replacements.ClearRef();
url = url.ReplaceComponents(replacements);
}
// Scheme component must be the same as the manifest URL's.
if (url.scheme() != manifest_url.scheme()) {
continue;
}
// If the manifest's scheme is https:, then manifest URL must have same
// origin as resulting absolute URL.
if (mode == EXPLICIT && manifest_url.SchemeIsSecure() &&
manifest_url.GetOrigin() != url.GetOrigin()) {
continue;
}
if (mode == EXPLICIT) {
manifest.explicit_urls.insert(url.spec());
} else {
manifest.online_whitelist_namespaces.push_back(url);
}
} else if (mode == FALLBACK) {
const wchar_t* line_p = line.c_str();
const wchar_t* line_end = line_p + line.length();
// Look for whitespace separating the two URLs
while (line_p < line_end && *line_p != '\t' && *line_p != ' ')
++line_p;
if (line_p == line_end) {
// There was no whitespace separating the URLs.
continue;
}
string16 namespace_url16;
WideToUTF16(line.c_str(), line_p - line.c_str(), &namespace_url16);
GURL namespace_url = manifest_url.Resolve(namespace_url16);
if (!namespace_url.is_valid())
continue;
if (namespace_url.has_ref()) {
GURL::Replacements replacements;
replacements.ClearRef();
namespace_url = namespace_url.ReplaceComponents(replacements);
}
// Fallback namespace URL must have the same scheme, host and port
// as the manifest's URL.
if (manifest_url.GetOrigin() != namespace_url.GetOrigin()) {
continue;
}
// Skip whitespace separating fallback namespace from URL.
while (line_p < line_end && (*line_p == '\t' || *line_p == ' '))
++line_p;
// Look for whitespace separating the URL from subsequent ignored tokens.
const wchar_t* fallback_start = line_p;
while (line_p < line_end && *line_p != '\t' && *line_p != ' ')
++line_p;
string16 fallback_url16;
WideToUTF16(fallback_start, line_p - fallback_start, &fallback_url16);
GURL fallback_url = manifest_url.Resolve(fallback_url16);
if (!fallback_url.is_valid())
continue;
if (fallback_url.has_ref()) {
GURL::Replacements replacements;
replacements.ClearRef();
fallback_url = fallback_url.ReplaceComponents(replacements);
}
// Fallback entry URL must have the same scheme, host and port
// as the manifest's URL.
if (manifest_url.GetOrigin() != fallback_url.GetOrigin()) {
continue;
}
// Store regardless of duplicate namespace URL. Only first match
// will ever be used.
manifest.fallback_namespaces.push_back(
FallbackNamespace(namespace_url, fallback_url));
} else {
NOTREACHED();
}
}
return true;
}
} // namespace appcache
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Sachin Chitta */
// Original code from pr2_moveit_tutorials::motion_planning_api_tutorial.cpp
#include <pluginlib/class_loader.h>
#include <ros/ros.h>
// MoveIt!
#include <moveit/robot_model_loader/robot_model_loader.h>
#include <moveit/planning_interface/planning_interface.h>
#include <moveit/planning_scene/planning_scene.h>
#include <moveit/kinematic_constraints/utils.h>
#include <moveit_msgs/DisplayTrajectory.h>
#include <moveit_msgs/PlanningScene.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "move_itomp");
ros::AsyncSpinner spinner(1);
spinner.start();
ros::NodeHandle node_handle("~");
// Setting up to start using a planner is pretty easy. Planners are
// setup as plugins in MoveIt! and you can use the ROS pluginlib
// interface to load any planner that you want to use. Before we
// can load the planner, we need two objects, a RobotModel
// and a PlanningScene.
// We will start by instantiating a
// `RobotModelLoader`_
// object, which will look up
// the robot description on the ROS parameter server and construct a
// :moveit_core:`RobotModel` for us to use.
//
// .. _RobotModelLoader: http://docs.ros.org/api/moveit_ros_planning/html/classrobot__model__loader_1_1RobotModelLoader.html
robot_model_loader::RobotModelLoader robot_model_loader("robot_description");
robot_model::RobotModelPtr robot_model = robot_model_loader.getModel();
// Using the :moveit_core:`RobotModel`, we can construct a
// :planning_scene:`PlanningScene` that maintains the state of
// the world (including the robot).
planning_scene::PlanningScenePtr planning_scene(new planning_scene::PlanningScene(robot_model));
// We will now construct a loader to load a planner, by name.
// Note that we are using the ROS pluginlib library here.
boost::scoped_ptr<pluginlib::ClassLoader<planning_interface::PlannerManager> > planner_plugin_loader;
planning_interface::PlannerManagerPtr planner_instance;
std::string planner_plugin_name;
// We will get the name of planning plugin we want to load
// from the ROS param server, and then load the planner
// making sure to catch all exceptions.
if (!node_handle.getParam("planning_plugin", planner_plugin_name))
ROS_FATAL_STREAM("Could not find planner plugin name");
try
{
planner_plugin_loader.reset(
new pluginlib::ClassLoader<planning_interface::PlannerManager>("moveit_core",
"planning_interface::PlannerManager"));
}
catch (pluginlib::PluginlibException& ex)
{
ROS_FATAL_STREAM("Exception while creating planning plugin loader " << ex.what());
}
try
{
planner_instance.reset(planner_plugin_loader->createUnmanagedInstance(planner_plugin_name));
if (!planner_instance->initialize(robot_model, node_handle.getNamespace()))
ROS_FATAL_STREAM("Could not initialize planner instance");
ROS_INFO_STREAM("Using planning interface '" << planner_instance->getDescription() << "'");
}
catch (pluginlib::PluginlibException& ex)
{
const std::vector<std::string> &classes = planner_plugin_loader->getDeclaredClasses();
std::stringstream ss;
for (std::size_t i = 0; i < classes.size(); ++i)
ss << classes[i] << " ";
ROS_ERROR_STREAM(
"Exception while loading planner '" << planner_plugin_name << "': " << ex.what() << std::endl << "Available plugins: " << ss.str());
}
/* Sleep a little to allow time to startup rviz, etc. */
ros::WallDuration sleep_time(1.0);
sleep_time.sleep();
// We will now create a motion plan request
// specifying the desired pose of the end-effector as input.
planning_interface::MotionPlanRequest req;
planning_interface::MotionPlanResponse res;
robot_state::RobotState& start_state = planning_scene->getCurrentStateNonConst();
// Set start_state
const robot_state::JointModelGroup* joint_model_group = start_state.getJointModelGroup("whole_body");
std::map<std::string, double> values;
joint_model_group->getVariableDefaultPositions("pressup", values);
//joint_model_group->getVariableDefaultPositions("standup", values);
start_state.setVariablePositions(values);
// Copy from start_state to req.start_state
unsigned int num_joints = start_state.getVariableCount();
req.start_state.joint_state.name = start_state.getVariableNames();
req.start_state.joint_state.position.resize(num_joints);
req.start_state.joint_state.velocity.resize(num_joints);
req.start_state.joint_state.effort.resize(num_joints);
memcpy(&req.start_state.joint_state.position[0], start_state.getVariablePositions(), sizeof(double) * num_joints);
if (start_state.hasVelocities())
memcpy(&req.start_state.joint_state.velocity[0], start_state.getVariableVelocities(), sizeof(double) * num_joints);
else
memset(&req.start_state.joint_state.velocity[0], 0, sizeof(double) * num_joints);
if (start_state.hasAccelerations())
memcpy(&req.start_state.joint_state.effort[0], start_state.getVariableAccelerations(), sizeof(double) * num_joints);
else
memset(&req.start_state.joint_state.effort[0], 0, sizeof(double) * num_joints);
// Now, setup a goal state
robot_state::RobotState goal_state(start_state);
joint_model_group->getVariableDefaultPositions("pressup2", values);
//joint_model_group->getVariableDefaultPositions("standup", values);
goal_state.setVariablePositions(values);
double jointValue = 1.0;
//goal_state.setJointPositions("base_prismatic_joint_y", &jointValue);
req.group_name = "whole_body";
moveit_msgs::Constraints joint_goal = kinematic_constraints::constructGoalConstraints(goal_state, joint_model_group);
req.goal_constraints.push_back(joint_goal);
// We now construct a planning context that encapsulate the scene,
// the request and the response. We call the planner using this
// planning context
planning_interface::PlanningContextPtr context = planner_instance->getPlanningContext(planning_scene, req,
res.error_code_);
context->solve(res);
if (res.error_code_.val != res.error_code_.SUCCESS)
{
ROS_ERROR("Could not compute plan successfully");
return 0;
}
// Visualize the result
// ^^^^^^^^^^^^^^^^^^^^
ros::Publisher display_publisher = node_handle.advertise<moveit_msgs::DisplayTrajectory>(
"/move_group/display_planned_path", 1, true);
moveit_msgs::DisplayTrajectory display_trajectory;
/* Visualize the trajectory */
ROS_INFO("Visualizing the trajectory");
moveit_msgs::MotionPlanResponse response;
res.getMessage(response);
display_trajectory.trajectory_start = response.trajectory_start;
display_trajectory.trajectory.push_back(response.trajectory);
display_publisher.publish(display_trajectory);
sleep_time.sleep();
ROS_INFO("Done");
planner_instance.reset();
return 0;
}
<commit_msg>render start/goal states<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Sachin Chitta */
// Original code from pr2_moveit_tutorials::motion_planning_api_tutorial.cpp
#include <pluginlib/class_loader.h>
#include <ros/ros.h>
// MoveIt!
#include <moveit/robot_model_loader/robot_model_loader.h>
#include <moveit/planning_interface/planning_interface.h>
#include <moveit/planning_scene/planning_scene.h>
#include <moveit/kinematic_constraints/utils.h>
#include <moveit_msgs/DisplayTrajectory.h>
#include <moveit_msgs/DisplayRobotState.h>
#include <moveit_msgs/PlanningScene.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "move_itomp");
ros::AsyncSpinner spinner(1);
spinner.start();
ros::NodeHandle node_handle("~");
// Setting up to start using a planner is pretty easy. Planners are
// setup as plugins in MoveIt! and you can use the ROS pluginlib
// interface to load any planner that you want to use. Before we
// can load the planner, we need two objects, a RobotModel
// and a PlanningScene.
// We will start by instantiating a
// `RobotModelLoader`_
// object, which will look up
// the robot description on the ROS parameter server and construct a
// :moveit_core:`RobotModel` for us to use.
//
// .. _RobotModelLoader: http://docs.ros.org/api/moveit_ros_planning/html/classrobot__model__loader_1_1RobotModelLoader.html
robot_model_loader::RobotModelLoader robot_model_loader("robot_description");
robot_model::RobotModelPtr robot_model = robot_model_loader.getModel();
// Using the :moveit_core:`RobotModel`, we can construct a
// :planning_scene:`PlanningScene` that maintains the state of
// the world (including the robot).
planning_scene::PlanningScenePtr planning_scene(new planning_scene::PlanningScene(robot_model));
// We will now construct a loader to load a planner, by name.
// Note that we are using the ROS pluginlib library here.
boost::scoped_ptr<pluginlib::ClassLoader<planning_interface::PlannerManager> > planner_plugin_loader;
planning_interface::PlannerManagerPtr planner_instance;
std::string planner_plugin_name;
// We will get the name of planning plugin we want to load
// from the ROS param server, and then load the planner
// making sure to catch all exceptions.
if (!node_handle.getParam("planning_plugin", planner_plugin_name))
ROS_FATAL_STREAM("Could not find planner plugin name");
try
{
planner_plugin_loader.reset(
new pluginlib::ClassLoader<planning_interface::PlannerManager>("moveit_core",
"planning_interface::PlannerManager"));
} catch (pluginlib::PluginlibException& ex)
{
ROS_FATAL_STREAM("Exception while creating planning plugin loader " << ex.what());
}
try
{
planner_instance.reset(planner_plugin_loader->createUnmanagedInstance(planner_plugin_name));
if (!planner_instance->initialize(robot_model, node_handle.getNamespace()))
ROS_FATAL_STREAM("Could not initialize planner instance");
ROS_INFO_STREAM("Using planning interface '" << planner_instance->getDescription() << "'");
} catch (pluginlib::PluginlibException& ex)
{
const std::vector<std::string> &classes = planner_plugin_loader->getDeclaredClasses();
std::stringstream ss;
for (std::size_t i = 0; i < classes.size(); ++i)
ss << classes[i] << " ";
ROS_ERROR_STREAM(
"Exception while loading planner '" << planner_plugin_name << "': " << ex.what() << std::endl << "Available plugins: " << ss.str());
}
/* Sleep a little to allow time to startup rviz, etc. */
ros::WallDuration sleep_time(1.0);
sleep_time.sleep();
// We will now create a motion plan request
// specifying the desired pose of the end-effector as input.
planning_interface::MotionPlanRequest req;
planning_interface::MotionPlanResponse res;
robot_state::RobotState& start_state = planning_scene->getCurrentStateNonConst();
// Set start_state
const robot_state::JointModelGroup* joint_model_group = start_state.getJointModelGroup("whole_body");
std::map<std::string, double> values;
joint_model_group->getVariableDefaultPositions("pressup", values);
//joint_model_group->getVariableDefaultPositions("standup", values);
start_state.setVariablePositions(values);
// Copy from start_state to req.start_state
unsigned int num_joints = start_state.getVariableCount();
req.start_state.joint_state.name = start_state.getVariableNames();
req.start_state.joint_state.position.resize(num_joints);
req.start_state.joint_state.velocity.resize(num_joints);
req.start_state.joint_state.effort.resize(num_joints);
memcpy(&req.start_state.joint_state.position[0], start_state.getVariablePositions(), sizeof(double) * num_joints);
if (start_state.hasVelocities())
memcpy(&req.start_state.joint_state.velocity[0], start_state.getVariableVelocities(), sizeof(double) * num_joints);
else
memset(&req.start_state.joint_state.velocity[0], 0, sizeof(double) * num_joints);
if (start_state.hasAccelerations())
memcpy(&req.start_state.joint_state.effort[0], start_state.getVariableAccelerations(), sizeof(double) * num_joints);
else
memset(&req.start_state.joint_state.effort[0], 0, sizeof(double) * num_joints);
// Now, setup a goal state
robot_state::RobotState goal_state(start_state);
joint_model_group->getVariableDefaultPositions("pressup2", values);
//joint_model_group->getVariableDefaultPositions("standup", values);
goal_state.setVariablePositions(values);
double jointValue = 1.0;
//goal_state.setJointPositions("base_prismatic_joint_y", &jointValue);
req.group_name = "whole_body";
moveit_msgs::Constraints joint_goal = kinematic_constraints::constructGoalConstraints(goal_state, joint_model_group);
req.goal_constraints.push_back(joint_goal);
int num_variables = start_state.getVariableNames().size();
ros::Publisher start_state_display_publisher = node_handle.advertise<moveit_msgs::DisplayRobotState>(
"/move_itomp/display_start_state", 1, true);
moveit_msgs::DisplayRobotState disp_start_state;
disp_start_state.state.joint_state.header.frame_id = robot_model->getModelFrame();
disp_start_state.state.joint_state.name = start_state.getVariableNames();
disp_start_state.state.joint_state.position.resize(num_variables);
memcpy(&disp_start_state.state.joint_state.position[0], start_state.getVariablePositions(),
sizeof(double) * num_variables);
disp_start_state.highlight_links.clear();
const std::vector<std::string>& link_model_names = robot_model->getLinkModelNames();
for (int i = 0; i < link_model_names.size(); ++i)
{
std_msgs::ColorRGBA color;
color.a = 0.5;
color.r = 0.0;
color.g = 1.0;
color.b = 0.5;
moveit_msgs::ObjectColor obj_color;
obj_color.id = link_model_names[i];
obj_color.color = color;
disp_start_state.highlight_links.push_back(obj_color);
}
start_state_display_publisher.publish(disp_start_state);
ros::Publisher goal_state_display_publisher = node_handle.advertise<moveit_msgs::DisplayRobotState>(
"/move_itomp/display_goal_state", 1, true);
moveit_msgs::DisplayRobotState disp_goal_state;
disp_goal_state.state.joint_state.header.frame_id = robot_model->getModelFrame();
disp_goal_state.state.joint_state.name = goal_state.getVariableNames();
disp_goal_state.state.joint_state.position.resize(num_variables);
memcpy(&disp_goal_state.state.joint_state.position[0], goal_state.getVariablePositions(),
sizeof(double) * num_variables);
disp_goal_state.highlight_links.clear();
for (int i = 0; i < link_model_names.size(); ++i)
{
std_msgs::ColorRGBA color;
color.a = 0.5;
color.r = 0.0;
color.g = 0.5;
color.b = 1.0;
moveit_msgs::ObjectColor obj_color;
obj_color.id = link_model_names[i];
obj_color.color = color;
disp_goal_state.highlight_links.push_back(obj_color);
}
goal_state_display_publisher.publish(disp_goal_state);
// We now construct a planning context that encapsulate the scene,
// the request and the response. We call the planner using this
// planning context
planning_interface::PlanningContextPtr context = planner_instance->getPlanningContext(planning_scene, req,
res.error_code_);
context->solve(res);
if (res.error_code_.val != res.error_code_.SUCCESS)
{
ROS_ERROR("Could not compute plan successfully");
return 0;
}
// Visualize the result
// ^^^^^^^^^^^^^^^^^^^^
ros::Publisher display_publisher = node_handle.advertise<moveit_msgs::DisplayTrajectory>(
"/move_group/display_planned_path", 1, true);
moveit_msgs::DisplayTrajectory display_trajectory;
/* Visualize the trajectory */
ROS_INFO("Visualizing the trajectory");
moveit_msgs::MotionPlanResponse response;
res.getMessage(response);
display_trajectory.trajectory_start = response.trajectory_start;
display_trajectory.trajectory.push_back(response.trajectory);
display_publisher.publish(display_trajectory);
sleep_time.sleep();
ROS_INFO("Done");
planner_instance.reset();
return 0;
}
<|endoftext|> |
<commit_before>//
// Game.cpp
// Phantasma
//
// Created by Thomas Harte on 17/12/2013.
// Copyright (c) 2013 Thomas Harte. All rights reserved.
//
#include "Game.h"
#include "GeometricObject.h"
#include "Matrix.h"
#include "VertexBuffer.h"
static float angle = 180.0f;
Game::Game(AreaMap *_areasByAreaID)
{
hasReceivedTime = false;
areasByAreaID = _areasByAreaID;
}
Game::~Game()
{
delete areasByAreaID;
}
void Game::setAspectRatio(float aspectRatio)
{
// create a projection matrix
Matrix projectionMatrix = Matrix::projectionMatrix(60.0f, aspectRatio, 1.0f, 1000.0f);
GeometricObject::setProjectionMatrix(projectionMatrix.contents);
}
void Game::draw()
{
// just clear the display to a salmon colour
glClearColor(1.0f, 0.5f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
Matrix rotationMatrix = Matrix::rotationMatrix(angle, 1.0f, 1.0f, 0.0f);
Matrix translationMatrix = Matrix::translationMatrix(0.0f, 0.0f, -5.0f);
GeometricObject::setViewMatrix((translationMatrix * rotationMatrix).contents);
GeometricObject::drawTestObject(vertexBuffer);
}
void Game::setupOpenGL()
{
GeometricObject::setupOpenGL();
if(!vertexBuffer)
vertexBuffer = GeometricObject::newVertexBuffer();
}
void Game::advanceToTime(uint32_t millisecondsSinceArbitraryMoment)
{
if(!hasReceivedTime)
{
timeOfLastTick = millisecondsSinceArbitraryMoment;
hasReceivedTime = true;
return;
}
// so how many milliseconds is that since we last paid attention?
uint32_t timeDifference = millisecondsSinceArbitraryMoment - timeOfLastTick;
// TODO: player movement updates out here
angle += (float)timeDifference / 10.0f;
// we'll advance at 50hz, which makes for some easy integer arithmetic here
while(timeDifference > 20)
{
timeOfLastTick += 20;
timeDifference -= 20;
// TODO: in-game timed events here
}
}
<commit_msg>Made sure vertexBuffer is initially NULL.<commit_after>//
// Game.cpp
// Phantasma
//
// Created by Thomas Harte on 17/12/2013.
// Copyright (c) 2013 Thomas Harte. All rights reserved.
//
#include "Game.h"
#include "GeometricObject.h"
#include "Matrix.h"
#include "VertexBuffer.h"
static float angle = 180.0f;
Game::Game(AreaMap *_areasByAreaID)
{
hasReceivedTime = false;
areasByAreaID = _areasByAreaID;
vertexBuffer = nullptr;
}
Game::~Game()
{
delete areasByAreaID;
}
void Game::setAspectRatio(float aspectRatio)
{
// create a projection matrix
Matrix projectionMatrix = Matrix::projectionMatrix(60.0f, aspectRatio, 1.0f, 1000.0f);
GeometricObject::setProjectionMatrix(projectionMatrix.contents);
}
void Game::draw()
{
// just clear the display to a salmon colour
glClearColor(1.0f, 0.5f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
Matrix rotationMatrix = Matrix::rotationMatrix(angle, 1.0f, 1.0f, 0.0f);
Matrix translationMatrix = Matrix::translationMatrix(0.0f, 0.0f, -5.0f);
GeometricObject::setViewMatrix((translationMatrix * rotationMatrix).contents);
GeometricObject::drawTestObject(vertexBuffer);
}
void Game::setupOpenGL()
{
GeometricObject::setupOpenGL();
if(!vertexBuffer)
vertexBuffer = GeometricObject::newVertexBuffer();
}
void Game::advanceToTime(uint32_t millisecondsSinceArbitraryMoment)
{
if(!hasReceivedTime)
{
timeOfLastTick = millisecondsSinceArbitraryMoment;
hasReceivedTime = true;
return;
}
// so how many milliseconds is that since we last paid attention?
uint32_t timeDifference = millisecondsSinceArbitraryMoment - timeOfLastTick;
// TODO: player movement updates out here
angle += (float)timeDifference / 10.0f;
// we'll advance at 50hz, which makes for some easy integer arithmetic here
while(timeDifference > 20)
{
timeOfLastTick += 20;
timeDifference -= 20;
// TODO: in-game timed events here
}
}
<|endoftext|> |
<commit_before>/*
* MIPS.hpp
*
* Created on: Jun 14, 2014
* Author: Pimenta
*/
#ifndef MIPS_HPP_
#define MIPS_HPP_
// lib
#include <systemc.h>
// local
#include "Context.hpp"
#include "Thread.hpp"
#include "readwrite_if.hpp"
struct Bitmap {
short magic_number;
int file_size;
int reserved;
int header_size;
int data_distance;
int width;
int height;
short planes;
short bpp;
int compression;
int data_size;
int horizontal_resolution;
int vertical_resolution;
int palette_size;
int important_colors;
uint32_t* buf;
};
SC_MODULE(MIPS) {
sc_in<bool> clk;
sc_port<readwrite_if> ioController;
uint32_t breg[32];
Bitmap bg;
SC_CTOR(MIPS) {
SC_METHOD(exec);
sensitive << clk.pos();
const char fn[] = "teste.bmp";
const char mode[] = "rb";
breg[4] = (uint32_t)fn; breg[5] = (uint32_t)mode;
fileOpen();
breg[4] = breg[2];
breg[5] = (uint32_t)&bg.magic_number; breg[6] = 2;
fileRead();
breg[5] = (uint32_t)&bg.file_size; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.reserved; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.header_size; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.data_distance; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.width; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.height; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.planes; breg[6] = 2;
fileRead();
breg[5] = (uint32_t)&bg.bpp; breg[6] = 2;
fileRead();
breg[5] = (uint32_t)&bg.compression; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.data_size; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.horizontal_resolution; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.vertical_resolution; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.palette_size; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.important_colors; breg[6] = 4;
fileRead();
bg.buf = new uint32_t[bg.width*bg.height];
breg[5] = (uint32_t)bg.buf; breg[6] = bg.width*bg.height*bg.bpp/8;
fileRead();
fileClose();
}
~MIPS() {
delete[] bg.buf;
}
void exec() {
static bool inited = false;
if (!inited) {
inited = true;
int wSize = ioController->read(0x10), w = wSize >> 16, h = wSize & 0xFFFF;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
ioController->write(0x0, bg.buf[(bg.height - 1 - y)*bg.width + x]);
ioController->write(0x4, 0x10010000 + (y*w + x)*4);
}
}
}
if (ioController->read(0x30))
exit();
Thread::sleep(33);
}
// ===========================================================================
// syscalls (code in v0)
// ===========================================================================
// v0: 2
// a0: 4
// a1: 5
// a2: 6
void exit() { // v0 = 10
sc_stop();
}
void fileOpen() { // v0 = 13
breg[2] = (uint32_t)fopen((const char*)breg[4], (const char*)breg[5]);
}
void fileRead() { // v0 = 14
breg[2] = (uint32_t)fread((void*)breg[5], breg[6], 1, (FILE*)breg[4]);
}
void fileWrite() { // v0 = 15
breg[2] = (uint32_t)fwrite((const void*)breg[5], breg[6], 1, (FILE*)breg[4]);
}
void fileClose() { // v0 = 16
fclose((FILE*)breg[4]);
}
};
#endif /* MIPS_HPP_ */
<commit_msg>Adicionando syscall de sleep<commit_after>/*
* MIPS.hpp
*
* Created on: Jun 14, 2014
* Author: Pimenta
*/
#ifndef MIPS_HPP_
#define MIPS_HPP_
// lib
#include <systemc.h>
// local
#include "Context.hpp"
#include "Thread.hpp"
#include "readwrite_if.hpp"
struct Bitmap {
short magic_number;
int file_size;
int reserved;
int header_size;
int data_distance;
int width;
int height;
short planes;
short bpp;
int compression;
int data_size;
int horizontal_resolution;
int vertical_resolution;
int palette_size;
int important_colors;
uint32_t* buf;
};
SC_MODULE(MIPS) {
sc_in<bool> clk;
sc_port<readwrite_if> ioController;
uint32_t breg[32];
Bitmap bg;
SC_CTOR(MIPS) {
SC_METHOD(exec);
sensitive << clk.pos();
const char fn[] = "teste.bmp";
const char mode[] = "rb";
breg[4] = (uint32_t)fn; breg[5] = (uint32_t)mode;
fileOpen();
breg[4] = breg[2];
breg[5] = (uint32_t)&bg.magic_number; breg[6] = 2;
fileRead();
breg[5] = (uint32_t)&bg.file_size; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.reserved; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.header_size; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.data_distance; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.width; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.height; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.planes; breg[6] = 2;
fileRead();
breg[5] = (uint32_t)&bg.bpp; breg[6] = 2;
fileRead();
breg[5] = (uint32_t)&bg.compression; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.data_size; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.horizontal_resolution; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.vertical_resolution; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.palette_size; breg[6] = 4;
fileRead();
breg[5] = (uint32_t)&bg.important_colors; breg[6] = 4;
fileRead();
bg.buf = new uint32_t[bg.width*bg.height];
breg[5] = (uint32_t)bg.buf; breg[6] = bg.width*bg.height*bg.bpp/8;
fileRead();
fileClose();
}
~MIPS() {
delete[] bg.buf;
}
void exec() {
static bool inited = false;
if (!inited) {
inited = true;
int wSize = ioController->read(0x10), w = wSize >> 16, h = wSize & 0xFFFF;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
ioController->write(0x0, bg.buf[(bg.height - 1 - y)*bg.width + x]);
ioController->write(0x4, 0x10010000 + (y*w + x)*4);
}
}
}
if (ioController->read(0x30))
exit();
breg[4] = 33;
sleep();
}
// ===========================================================================
// syscalls (code in v0)
// ===========================================================================
// v0: 2
// a0: 4
// a1: 5
// a2: 6
void exit() { // v0 = 10
sc_stop();
}
void fileOpen() { // v0 = 13
breg[2] = (uint32_t)fopen((const char*)breg[4], (const char*)breg[5]);
}
void fileRead() { // v0 = 14
breg[2] = (uint32_t)fread((void*)breg[5], breg[6], 1, (FILE*)breg[4]);
}
void fileWrite() { // v0 = 15
breg[2] = (uint32_t)fwrite((const void*)breg[5], breg[6], 1, (FILE*)breg[4]);
}
void fileClose() { // v0 = 16
fclose((FILE*)breg[4]);
}
void sleep() { // v0 = 32
Thread::sleep(breg[4]);
}
};
#endif /* MIPS_HPP_ */
<|endoftext|> |
<commit_before>// Util.cpp
// Util class member-functions definition.
//
// Author: yat0 - https://github.com/yat0
#include "Util.h"
#include "App.h"
#include <cmath>
// render cross on board field (row, col)
void Util::drawCross(int row, int col)
{
int fieldW = App::SCREEN_WIDTH/3;
int fieldH = App::SCREEN_HEIGHT/3;
// top left to bottom right
SDL_SetRenderDrawColor(App::getRenderer(),//SDL_Render_DrawLine
col*fieldW, row*fieldH,
col*fieldW+fieldW, row*fieldH+fieldH);
// top right to bottom left
SDL_RenderDrawLine(App::getRenderer(),
col*fieldW, row*fieldH+fieldH,
col*fieldW+fieldW, row*fieldH);
}
// render circle on board field (boardX, boardY)
void Util::drawCircle(int row, int col)
{
int fieldW = App::SCREEN_WIDTH/3;
int fieldH = App::SCREEN_HEIGHT/3;
// calculate circle center
int centerX = col*fieldW+(fieldW/2);
int centerY = row*fieldH+(fieldH/2);
int r = fieldW/2;
double step = 2*M_PI/30;
int endX = centerX + r;
int endY = centerY;
// draw circle.. Multiple straight lines between consecutive
// points of the desired circle
for(double angle=0; angle<2*M_PI; angle+=step)
{
int startX = endX;
int startY = endY;
endX = r * cos(angle) + centerX;
endY = r * sin(angle) + centerY;
SDL_RenderDrawLine(App::getRenderer(), startX, startY, endX, endY);
}
}
<commit_msg>Displays a nuclear letter X now<commit_after>// Util.cpp
// Util class member-functions definition.
//
// Author: yat0 - https://github.com/yat0
#include "Util.h"
#include "App.h"
#include <cmath>
// render cross on board field (row, col)
void Util::drawCross(int row, int col)
{
int fieldW = App::SCREEN_WIDTH/3;
int fieldH = App::SCREEN_HEIGHT/3;
// top left to bottom right
SDL_SetRenderDrawColor(App::getRenderer(),//SDL_Render_DrawLine
col*fieldW, row*fieldH,
col*fieldW+fieldW, row*fieldH+fieldH);
// top right to bottom left
SDL_RenderDrawLine(App::getRenderer(),
col*fieldW, row*fieldH+fieldH,
col*fieldW+fieldW, row*fieldH);
SDL_RenderDrawLine(App::getRenderer(),
col*fieldW, row*fieldH,
col*fieldW+fieldW, row*fieldH+fieldH);
}
// render circle on board field (boardX, boardY)
void Util::drawCircle(int row, int col)
{
int fieldW = App::SCREEN_WIDTH/3;
int fieldH = App::SCREEN_HEIGHT/3;
// calculate circle center
int centerX = col*fieldW+(fieldW/2);
int centerY = row*fieldH+(fieldH/2);
int r = fieldW/2;
double step = 2*M_PI/30;
int endX = centerX + r;
int endY = centerY;
// draw circle.. Multiple straight lines between consecutive
// points of the desired circle
for(double angle=0; angle<2*M_PI; angle+=step)
{
int startX = endX;
int startY = endY;
endX = r * cos(angle) + centerX;
endY = r * sin(angle) + centerY;
SDL_RenderDrawLine(App::getRenderer(), startX, startY, endX, endY);
}
}
<|endoftext|> |
<commit_before>/**
* @file Wave.cpp
* @author Sebastian Ritterbusch <ospac@ritterbusch.de>
* @version 1.0
* @date 5.2.2016
* @copyright MIT License (see LICENSE file)
* @brief Wave file management via libsndfile
*/
#include <iostream>
#include <fstream>
extern "C" {
#include <sndfile.h>
}
#include "Wave.h"
#include "Log.h"
Channels & Wave::load(const std::string &name, Channels & channels,float skip,float length)
{
LOG(logINFO) << "Loading "<< name << std::endl;
SNDFILE *sf;
SF_INFO info;
info.format = 0;
sf = sf_open(name.c_str(),SFM_READ,&info);
if(sf==NULL)
{
LOG(logERROR) << "Could not read " << name << std::endl;
return channels;
}
//if(info.frames>44100*60*10)
// info.frames=44100*60*10;
short * buf=new short[info.channels*65536];
LOG(logINFO) << "Reading "<<info.frames<<" frames with "<<info.channels<<" channels with rate "<< info.samplerate << std::endl;
//std::cerr << info.format << std::endl;
unsigned o=channels.size();
unsigned skiplen=skip*(int)info.samplerate;
unsigned fulllen=length*(int)info.samplerate;
if(skiplen>info.frames)
skiplen=info.frames;
if(fulllen>info.frames-skiplen || length>1e+90)
fulllen=info.frames-skiplen;
for(int i=0;i<info.channels;i++)
channels.push_back(Channel((int)info.samplerate,std::vector<float>(fulllen)));
for(unsigned i=0;i<info.frames && i<skiplen+fulllen;)
{
int items=65536;
if(i+items>=info.frames)
items=info.frames-i;
//LOG(logDEBUG) << i << ": Reading "<< items << " ";
int hasread=sf_read_short(sf,buf,items*info.channels);
hasread=hasread+0;
LOG(logDEBUG2) << i << ": Read "<< hasread << std::endl;
for(int j=0,t=0;j<items;i++,j++)
for(int c=0;c<info.channels;c++)
if(i>=skiplen && i<=skiplen+fulllen)
channels[o+c][i-skiplen]=buf[t++];
}
delete [] buf;
sf_close(sf);
LOG(logDEBUG) << "Loading done" << std::endl;
return channels;
}
Channels & Wave::loadAscii(const std::string &name,int samplerate,Channels & channels,float skip,float maxlength)
{
unsigned length=0;
double min=1e99;
double max=-1e99;
double sum=0;
unsigned count=0;
unsigned skiplen=skip*samplerate;
unsigned fulllen=maxlength*samplerate;
{
std::ifstream in(name.c_str());
if(in.fail())
return channels;
double dummy;
for(;!in.eof();length++)
{
while(!in.eof() && (in.peek()=='#' || in.peek()==' '
|| in.peek()=='\n' || in.peek()=='\r'
|| in.peek()=='\t'))
{
char c;
c=in.get();
if(c=='#')
{
while(!in.eof() && in.peek()!='\n' && in.peek()!='\r')
in.get();
}
}
in >> dummy;
if(length>=skiplen && (length<fulllen || maxlength>1e+90))
{
sum+=dummy;
count++;
if(dummy>max)
{
max=dummy;
}
if(dummy<min)
{
min=dummy;
}
}
}
}
if(skip>length)
skip=length;
if(fulllen>length-skip || maxlength>1e+90)
fulllen=length-skip;
if(count==0)
count=1;
double null=sum/count;
if(min>null)
min=null-1;
if(max<null)
max=null+1;
// Kill DC signal...
if(2*null-min>max)
max=2*null-min;
if(2*null-max<min)
min=2*null-max;
unsigned o=channels.size();
channels.push_back(Channel(samplerate,fulllen));
std::ifstream in(name.c_str());
unsigned i=0;
for(;!in.eof() && i<length && i<skiplen+fulllen;i++)
{
while(!in.eof() && (in.peek()=='#' || in.peek()==' '
|| in.peek()=='\n' || in.peek()=='\r'
|| in.peek()=='\t'))
{
char c;
c=in.get();
if(c=='#')
{
while(!in.eof() && in.peek()!='\n' && in.peek()!='\r')
in.get();
}
}
double d;
in >> d;
if(i>=skiplen && i<skiplen+fulllen)
channels[o][i-skiplen]=(d-min)/(max-min)*64000-32000;
}
return channels;
}
Channels Wave::load(const std::string &name,float skip,float length)
{
std::vector<Channel> channels;
LOG(logINFO) << "Loading "<< name << std::endl;
return load(name,channels,skip,length);
}
int Wave::save(const std::string &name,Channel & channel)
{
Channels channels=Channels(1);
channels[0]=channel;
return save(name,channels);
}
int Wave::save(const std::string &name,Channels & channels)
{
SF_INFO info;
if(channels.size()==0)
return 1;
int no_channels=info.channels=channels.size();
info.samplerate=channels[0].samplerate();
int frames=info.frames=channels[0].size();
LOG(logINFO) << "Writing " << name << " with "<< info.channels << " channels in " << info.samplerate << "Hz and " << info.frames << "frames " << std::endl;
for(unsigned i=0;i<channels.size();i++)
{
if(channels[i].samplerate()!=(unsigned)info.samplerate)
channels[i]=channels[i].resampleTo(info.samplerate);
if(channels[i].size()!=info.frames)
channels[i]=channels[i].resizeTo(info.frames);
}
SNDFILE *sf;
info.format=SF_FORMAT_WAV | SF_FORMAT_PCM_16;
info.sections=1;
info.seekable=1;
//std::cerr << info.format << std::endl;
sf=sf_open(name.c_str(),SFM_WRITE,&info);
if(sf==NULL)
{
LOG(logERROR) << "Could not write " << name << std::endl;
return 1;
}
short * buf=new short[info.channels*65536];
//std::cerr << "Starting" << std::endl;
for(int i=0;i<frames;)
{
int items=65536;
if(i+items>=frames)
items=frames-i;
//std::cerr << items << std::endl;
for(int j=0,t=0;j<items;i++,j++)
for(int c=0;c<no_channels;c++)
{
if(((int)channels[c][i])<-32767)
buf[t++]=-32767;
else if(((int)channels[c][i])>32767)
buf[t++]=32767;
else
buf[t++]=channels[c][i];
}
int haswritten=sf_write_short(sf,buf,items*no_channels);
//std::cerr << "wrote " << haswritten << std::endl;
haswritten=haswritten+0;
}
delete [] buf;
sf_close(sf);
return 0;
}
<commit_msg>Added logging of length of target file.<commit_after>/**
* @file Wave.cpp
* @author Sebastian Ritterbusch <ospac@ritterbusch.de>
* @version 1.0
* @date 5.2.2016
* @copyright MIT License (see LICENSE file)
* @brief Wave file management via libsndfile
*/
#include <iostream>
#include <fstream>
extern "C" {
#include <sndfile.h>
}
#include "Wave.h"
#include "Log.h"
Channels & Wave::load(const std::string &name, Channels & channels,float skip,float length)
{
LOG(logINFO) << "Loading "<< name << std::endl;
SNDFILE *sf;
SF_INFO info;
info.format = 0;
sf = sf_open(name.c_str(),SFM_READ,&info);
if(sf==NULL)
{
LOG(logERROR) << "Could not read " << name << std::endl;
return channels;
}
//if(info.frames>44100*60*10)
// info.frames=44100*60*10;
short * buf=new short[info.channels*65536];
LOG(logINFO) << "Reading "<<info.frames<<" frames with "<<info.channels<<" channels with rate "<< info.samplerate << std::endl;
//std::cerr << info.format << std::endl;
unsigned o=channels.size();
unsigned skiplen=skip*(int)info.samplerate;
unsigned fulllen=length*(int)info.samplerate;
if(skiplen>info.frames)
skiplen=info.frames;
if(fulllen>info.frames-skiplen || length>1e+90)
fulllen=info.frames-skiplen;
for(int i=0;i<info.channels;i++)
channels.push_back(Channel((int)info.samplerate,std::vector<float>(fulllen)));
for(unsigned i=0;i<info.frames && i<skiplen+fulllen;)
{
int items=65536;
if(i+items>=info.frames)
items=info.frames-i;
//LOG(logDEBUG) << i << ": Reading "<< items << " ";
int hasread=sf_read_short(sf,buf,items*info.channels);
hasread=hasread+0;
LOG(logDEBUG2) << i << ": Read "<< hasread << std::endl;
for(int j=0,t=0;j<items;i++,j++)
for(int c=0;c<info.channels;c++)
if(i>=skiplen && i<=skiplen+fulllen)
channels[o+c][i-skiplen]=buf[t++];
}
delete [] buf;
sf_close(sf);
LOG(logDEBUG) << "Loading done" << std::endl;
return channels;
}
Channels & Wave::loadAscii(const std::string &name,int samplerate,Channels & channels,float skip,float maxlength)
{
unsigned length=0;
double min=1e99;
double max=-1e99;
double sum=0;
unsigned count=0;
unsigned skiplen=skip*samplerate;
unsigned fulllen=maxlength*samplerate;
{
std::ifstream in(name.c_str());
if(in.fail())
return channels;
double dummy;
for(;!in.eof();length++)
{
while(!in.eof() && (in.peek()=='#' || in.peek()==' '
|| in.peek()=='\n' || in.peek()=='\r'
|| in.peek()=='\t'))
{
char c;
c=in.get();
if(c=='#')
{
while(!in.eof() && in.peek()!='\n' && in.peek()!='\r')
in.get();
}
}
in >> dummy;
if(length>=skiplen && (length<fulllen || maxlength>1e+90))
{
sum+=dummy;
count++;
if(dummy>max)
{
max=dummy;
}
if(dummy<min)
{
min=dummy;
}
}
}
}
if(skip>length)
skip=length;
if(fulllen>length-skip || maxlength>1e+90)
fulllen=length-skip;
if(count==0)
count=1;
double null=sum/count;
if(min>null)
min=null-1;
if(max<null)
max=null+1;
// Kill DC signal...
if(2*null-min>max)
max=2*null-min;
if(2*null-max<min)
min=2*null-max;
unsigned o=channels.size();
channels.push_back(Channel(samplerate,fulllen));
std::ifstream in(name.c_str());
unsigned i=0;
for(;!in.eof() && i<length && i<skiplen+fulllen;i++)
{
while(!in.eof() && (in.peek()=='#' || in.peek()==' '
|| in.peek()=='\n' || in.peek()=='\r'
|| in.peek()=='\t'))
{
char c;
c=in.get();
if(c=='#')
{
while(!in.eof() && in.peek()!='\n' && in.peek()!='\r')
in.get();
}
}
double d;
in >> d;
if(i>=skiplen && i<skiplen+fulllen)
channels[o][i-skiplen]=(d-min)/(max-min)*64000-32000;
}
return channels;
}
Channels Wave::load(const std::string &name,float skip,float length)
{
std::vector<Channel> channels;
LOG(logINFO) << "Loading "<< name << std::endl;
return load(name,channels,skip,length);
}
int Wave::save(const std::string &name,Channel & channel)
{
Channels channels=Channels(1);
channels[0]=channel;
return save(name,channels);
}
int Wave::save(const std::string &name,Channels & channels)
{
SF_INFO info;
if(channels.size()==0)
return 1;
int no_channels=info.channels=channels.size();
info.samplerate=channels[0].samplerate();
int frames=info.frames=channels[0].size();
char lengthString[40];
float secs=frames/float(info.samplerate);
int mins=secs/60;
secs-=mins*60;
int hours=mins/60;
mins-=hours*60;
if(hours>0)
sprintf(lengthString,"%d:%02d:%05.2f",hours,mins,secs);
else
sprintf(lengthString,"%d:%05.2f",mins,secs);
LOG(logINFO) << "Writing " << name << " with "<< info.channels << " channels in " << info.samplerate << "Hz and " << info.frames << "frames" << std::endl;
LOG(logINFO) << "Final length: " <<lengthString << std::endl;
for(unsigned i=0;i<channels.size();i++)
{
if(channels[i].samplerate()!=(unsigned)info.samplerate)
channels[i]=channels[i].resampleTo(info.samplerate);
if(channels[i].size()!=info.frames)
channels[i]=channels[i].resizeTo(info.frames);
}
SNDFILE *sf;
info.format=SF_FORMAT_WAV | SF_FORMAT_PCM_16;
info.sections=1;
info.seekable=1;
//std::cerr << info.format << std::endl;
sf=sf_open(name.c_str(),SFM_WRITE,&info);
if(sf==NULL)
{
LOG(logERROR) << "Could not write " << name << std::endl;
return 1;
}
short * buf=new short[info.channels*65536];
//std::cerr << "Starting" << std::endl;
for(int i=0;i<frames;)
{
int items=65536;
if(i+items>=frames)
items=frames-i;
//std::cerr << items << std::endl;
for(int j=0,t=0;j<items;i++,j++)
for(int c=0;c<no_channels;c++)
{
if(((int)channels[c][i])<-32767)
buf[t++]=-32767;
else if(((int)channels[c][i])>32767)
buf[t++]=32767;
else
buf[t++]=channels[c][i];
}
int haswritten=sf_write_short(sf,buf,items*no_channels);
//std::cerr << "wrote " << haswritten << std::endl;
haswritten=haswritten+0;
}
delete [] buf;
sf_close(sf);
return 0;
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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 "itkRLEImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkTestingMacros.h"
#include <cstdlib>
#include <string>
template <typename ImageType1, typename ImageType2>
void compare(itk::SmartPointer<ImageType1> im1, itk::SmartPointer<ImageType2> im2)
{
itk::ImageRegionConstIterator<ImageType1> it1(im1, im1->GetLargestPossibleRegion());
itk::ImageRegionConstIterator<ImageType2> it2(im2, im2->GetLargestPossibleRegion());
while (!it1.IsAtEnd())
{
if (it1.Get() != it2.Get())
{
itkGenericExceptionMacro(<< "Images differ. Val1: " << it1.Get() << " Val2: " << it2.Get()
<< "\nInd1: " << it1.GetIndex() << " Ind2: " << it2.GetIndex());
}
++it1;
++it2;
}
}
template <typename ImageType>
void roiTest(itk::SmartPointer<itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension> > orig)
{
using myRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension>;
using charRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension, char>;
using charConverterType = itk::RegionOfInterestImageFilter<myRLEImage, charRLEImage>;
typename charConverterType::Pointer cConv = charConverterType::New();
cConv->SetInput(orig);
cConv->SetRegionOfInterest(orig->GetLargestPossibleRegion());
cConv->Update();
typename charRLEImage::Pointer cIn = cConv->GetOutput();
cIn->DisconnectPipeline();
using ucharRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension, unsigned char>;
using ucharConverterType = itk::RegionOfInterestImageFilter<myRLEImage, ucharRLEImage>;
typename ucharConverterType::Pointer ucConv = ucharConverterType::New();
ucConv->SetInput(orig);
ucConv->SetRegionOfInterest(orig->GetLargestPossibleRegion());
ucConv->Update();
typename ucharRLEImage::Pointer ucIn = ucConv->GetOutput();
ucIn->DisconnectPipeline();
std::cout << "Comparing direct conversions...";
compare(cIn, ucIn);
std::cout << "OK" << std::endl;
typename myRLEImage::RegionType reg = orig->GetLargestPossibleRegion();
typename myRLEImage::RegionType rNeg = reg;
for (unsigned i = 0; i < ImageType::ImageDimension; i++)
{
rNeg.SetIndex(i, -typename myRLEImage::IndexValueType(reg.GetSize(i)) * 3 / 4);
}
cIn->SetRegions(rNeg);
ucIn->SetRegions(rNeg);
std::cout << "Comparing LPR with negative indices...";
compare(cIn, ucIn);
std::cout << "OK" << std::endl;
//region for partial coverage, skip X due to RLE representation constraints
for (unsigned i = 1; i < ImageType::ImageDimension; i++)
{
reg.GetModifiableIndex()[i] += (reg.GetSize(i) - 1) / 4;
rNeg.GetModifiableIndex()[i] += typename myRLEImage::IndexValueType(rNeg.GetSize(i) - 1) / 4;
reg.SetSize(i, (reg.GetSize(i) + 1) / 2);
rNeg.SetSize(i, (rNeg.GetSize(i) + 1) / 2);
}
using myConverterType = itk::RegionOfInterestImageFilter<myRLEImage, myRLEImage>;
typename myConverterType::Pointer myConv = myConverterType::New();
myConv->SetInput(orig);
myConv->SetRegionOfInterest(reg);
myConv->Update();
typename myRLEImage::Pointer myIn = myConv->GetOutput();
using cRoIType = itk::RegionOfInterestImageFilter<charRLEImage, charRLEImage>;
typename cRoIType::Pointer cRoI = cRoIType::New();
cRoI->SetInput(cIn);
cRoI->SetRegionOfInterest(rNeg);
cRoI->Update();
cIn = cRoI->GetOutput();
cIn->DisconnectPipeline();
using ucRoIType = itk::RegionOfInterestImageFilter<ucharRLEImage, ucharRLEImage>;
typename ucRoIType::Pointer ucRoI = ucRoIType::New();
ucRoI->SetInput(ucIn);
ucRoI->SetRegionOfInterest(rNeg);
ucRoI->Update();
ucIn = ucRoI->GetOutput();
ucIn->DisconnectPipeline();
std::cout << "Comparing RoIs with negative indices...";
compare(cIn, ucIn);
std::cout << "OK" << std::endl;
std::cout << "Comparing RoIs with negative and positive indices...";
compare(cIn, myIn);
compare(ucIn, myIn);
std::cout << "OK" << std::endl;
}
template <typename ImageType>
int doTest(std::string inFilename, std::string outFilename)
{
using ReaderType = itk::ImageFileReader < ImageType >;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(inFilename);
std::cout << "Reading " << inFilename << std::endl;
reader->Update();
using myRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension>;
using inConverterType = itk::RegionOfInterestImageFilter<ImageType, myRLEImage>;
typename inConverterType::Pointer inConv = inConverterType::New();
inConv->SetInput(reader->GetOutput());
inConv->SetRegionOfInterest(reader->GetOutput()->GetLargestPossibleRegion());
std::cout << "Converting regular image to RLEImage" << std::endl;
inConv->Update();
typename myRLEImage::Pointer test = inConv->GetOutput();
itk::SizeValueType xSize = test->GetLargestPossibleRegion().GetSize(0);
std::cout << "Running region of interest tests" << std::endl;
if (xSize > 127)
{
std::cout << "\n xSize>127 (CHAR_MAX)" << std::endl;
ITK_TRY_EXPECT_EXCEPTION(roiTest<myRLEImage>(test));
}
else
{
ITK_TRY_EXPECT_NO_EXCEPTION(roiTest<myRLEImage>(test));
}
using outConverterType = itk::RegionOfInterestImageFilter<myRLEImage, ImageType>;
typename outConverterType::Pointer outConv = outConverterType::New();
outConv->SetInput(test);
outConv->SetRegionOfInterest(test->GetLargestPossibleRegion());
std::cout << "Converting RLEImage to regular image" << std::endl;
outConv->Update();
using WriterType = itk::ImageFileWriter< ImageType >;
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName(outFilename);
writer->SetInput(outConv->GetOutput());
writer->SetUseCompression(true);
std::cout << "Writing " << outFilename << std::endl;
writer->Update();
std::cout << "Test finished" << std::endl;
return EXIT_SUCCESS;
}
void dimTest()
{
using S2Type = itk::RLEImage<short, 2>; //2D
using S3Type = itk::RLEImage<short, 3>; //3D
S2Type::Pointer s2=S2Type::New();
S3Type::Pointer s3=S3Type::New();
//instantiation of "RoIType" is dissalowed due to different dimension
//uncommenting the lines below should give a meaningful error message
//using RoIType = itk::RegionOfInterestImageFilter<S3Type, S2Type>;
//typename RoIType::Pointer roi = RoIType::New();
}
int itkRLEImageTest( int argc, char* argv[] )
{
if( argc < 3 )
{
std::cerr << "Usage: " << argv[0] << " inputImage outputImage" << std::endl;
return EXIT_FAILURE;
}
const char * inputImageFileName = argv[1];
const char * outputImageFileName = argv[2];
using ScalarPixelType = itk::ImageIOBase::IOComponentType;
itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(
inputImageFileName, itk::ImageIOFactory::FileModeType::ReadMode);
if (!imageIO)
{
std::cerr << "Could not CreateImageIO for: " << inputImageFileName << std::endl;
return EXIT_FAILURE;
}
imageIO->SetFileName(inputImageFileName);
imageIO->ReadImageInformation();
const ScalarPixelType pixelType = imageIO->GetComponentType();
const size_t numDimensions = imageIO->GetNumberOfDimensions();
try
{
//unused cases are not instantiated because they greatly increase compile time
if (numDimensions==2 && pixelType == itk::ImageIOBase::UCHAR)
{
return doTest<itk::Image<unsigned char, 2> >(inputImageFileName, outputImageFileName);
}
if (numDimensions==3 && (pixelType == itk::ImageIOBase::SHORT
|| pixelType == itk::ImageIOBase::USHORT))
{
return doTest<itk::Image<short, 3> >(inputImageFileName, outputImageFileName);
}
if (numDimensions==3) //if not (u)short, then interpret as uint
{
return doTest<itk::Image<unsigned int, 3> >(inputImageFileName, outputImageFileName);
}
if (numDimensions==4 && pixelType == itk::ImageIOBase::UCHAR)
{
return doTest<itk::Image<unsigned char, 4> >(inputImageFileName, outputImageFileName);
}
std::cerr << "Unsupported image type:\n Dimensions: " << numDimensions;
std::cerr<< "\n Pixel type:" << imageIO->GetComponentTypeAsString(pixelType) << std::endl;
return EXIT_FAILURE;
}
catch( itk::ExceptionObject & error )
{
std::cerr << "Error: " << error << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>COMP: follow rename of ImageIOFactory FileModeType into FileModeEnum<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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 "itkRLEImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkTestingMacros.h"
#include <cstdlib>
#include <string>
template <typename ImageType1, typename ImageType2>
void compare(itk::SmartPointer<ImageType1> im1, itk::SmartPointer<ImageType2> im2)
{
itk::ImageRegionConstIterator<ImageType1> it1(im1, im1->GetLargestPossibleRegion());
itk::ImageRegionConstIterator<ImageType2> it2(im2, im2->GetLargestPossibleRegion());
while (!it1.IsAtEnd())
{
if (it1.Get() != it2.Get())
{
itkGenericExceptionMacro(<< "Images differ. Val1: " << it1.Get() << " Val2: " << it2.Get()
<< "\nInd1: " << it1.GetIndex() << " Ind2: " << it2.GetIndex());
}
++it1;
++it2;
}
}
template <typename ImageType>
void roiTest(itk::SmartPointer<itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension> > orig)
{
using myRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension>;
using charRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension, char>;
using charConverterType = itk::RegionOfInterestImageFilter<myRLEImage, charRLEImage>;
typename charConverterType::Pointer cConv = charConverterType::New();
cConv->SetInput(orig);
cConv->SetRegionOfInterest(orig->GetLargestPossibleRegion());
cConv->Update();
typename charRLEImage::Pointer cIn = cConv->GetOutput();
cIn->DisconnectPipeline();
using ucharRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension, unsigned char>;
using ucharConverterType = itk::RegionOfInterestImageFilter<myRLEImage, ucharRLEImage>;
typename ucharConverterType::Pointer ucConv = ucharConverterType::New();
ucConv->SetInput(orig);
ucConv->SetRegionOfInterest(orig->GetLargestPossibleRegion());
ucConv->Update();
typename ucharRLEImage::Pointer ucIn = ucConv->GetOutput();
ucIn->DisconnectPipeline();
std::cout << "Comparing direct conversions...";
compare(cIn, ucIn);
std::cout << "OK" << std::endl;
typename myRLEImage::RegionType reg = orig->GetLargestPossibleRegion();
typename myRLEImage::RegionType rNeg = reg;
for (unsigned i = 0; i < ImageType::ImageDimension; i++)
{
rNeg.SetIndex(i, -typename myRLEImage::IndexValueType(reg.GetSize(i)) * 3 / 4);
}
cIn->SetRegions(rNeg);
ucIn->SetRegions(rNeg);
std::cout << "Comparing LPR with negative indices...";
compare(cIn, ucIn);
std::cout << "OK" << std::endl;
//region for partial coverage, skip X due to RLE representation constraints
for (unsigned i = 1; i < ImageType::ImageDimension; i++)
{
reg.GetModifiableIndex()[i] += (reg.GetSize(i) - 1) / 4;
rNeg.GetModifiableIndex()[i] += typename myRLEImage::IndexValueType(rNeg.GetSize(i) - 1) / 4;
reg.SetSize(i, (reg.GetSize(i) + 1) / 2);
rNeg.SetSize(i, (rNeg.GetSize(i) + 1) / 2);
}
using myConverterType = itk::RegionOfInterestImageFilter<myRLEImage, myRLEImage>;
typename myConverterType::Pointer myConv = myConverterType::New();
myConv->SetInput(orig);
myConv->SetRegionOfInterest(reg);
myConv->Update();
typename myRLEImage::Pointer myIn = myConv->GetOutput();
using cRoIType = itk::RegionOfInterestImageFilter<charRLEImage, charRLEImage>;
typename cRoIType::Pointer cRoI = cRoIType::New();
cRoI->SetInput(cIn);
cRoI->SetRegionOfInterest(rNeg);
cRoI->Update();
cIn = cRoI->GetOutput();
cIn->DisconnectPipeline();
using ucRoIType = itk::RegionOfInterestImageFilter<ucharRLEImage, ucharRLEImage>;
typename ucRoIType::Pointer ucRoI = ucRoIType::New();
ucRoI->SetInput(ucIn);
ucRoI->SetRegionOfInterest(rNeg);
ucRoI->Update();
ucIn = ucRoI->GetOutput();
ucIn->DisconnectPipeline();
std::cout << "Comparing RoIs with negative indices...";
compare(cIn, ucIn);
std::cout << "OK" << std::endl;
std::cout << "Comparing RoIs with negative and positive indices...";
compare(cIn, myIn);
compare(ucIn, myIn);
std::cout << "OK" << std::endl;
}
template <typename ImageType>
int doTest(std::string inFilename, std::string outFilename)
{
using ReaderType = itk::ImageFileReader < ImageType >;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(inFilename);
std::cout << "Reading " << inFilename << std::endl;
reader->Update();
using myRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension>;
using inConverterType = itk::RegionOfInterestImageFilter<ImageType, myRLEImage>;
typename inConverterType::Pointer inConv = inConverterType::New();
inConv->SetInput(reader->GetOutput());
inConv->SetRegionOfInterest(reader->GetOutput()->GetLargestPossibleRegion());
std::cout << "Converting regular image to RLEImage" << std::endl;
inConv->Update();
typename myRLEImage::Pointer test = inConv->GetOutput();
itk::SizeValueType xSize = test->GetLargestPossibleRegion().GetSize(0);
std::cout << "Running region of interest tests" << std::endl;
if (xSize > 127)
{
std::cout << "\n xSize>127 (CHAR_MAX)" << std::endl;
ITK_TRY_EXPECT_EXCEPTION(roiTest<myRLEImage>(test));
}
else
{
ITK_TRY_EXPECT_NO_EXCEPTION(roiTest<myRLEImage>(test));
}
using outConverterType = itk::RegionOfInterestImageFilter<myRLEImage, ImageType>;
typename outConverterType::Pointer outConv = outConverterType::New();
outConv->SetInput(test);
outConv->SetRegionOfInterest(test->GetLargestPossibleRegion());
std::cout << "Converting RLEImage to regular image" << std::endl;
outConv->Update();
using WriterType = itk::ImageFileWriter< ImageType >;
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName(outFilename);
writer->SetInput(outConv->GetOutput());
writer->SetUseCompression(true);
std::cout << "Writing " << outFilename << std::endl;
writer->Update();
std::cout << "Test finished" << std::endl;
return EXIT_SUCCESS;
}
void dimTest()
{
using S2Type = itk::RLEImage<short, 2>; //2D
using S3Type = itk::RLEImage<short, 3>; //3D
S2Type::Pointer s2=S2Type::New();
S3Type::Pointer s3=S3Type::New();
//instantiation of "RoIType" is dissalowed due to different dimension
//uncommenting the lines below should give a meaningful error message
//using RoIType = itk::RegionOfInterestImageFilter<S3Type, S2Type>;
//typename RoIType::Pointer roi = RoIType::New();
}
int itkRLEImageTest( int argc, char* argv[] )
{
if( argc < 3 )
{
std::cerr << "Usage: " << argv[0] << " inputImage outputImage" << std::endl;
return EXIT_FAILURE;
}
const char * inputImageFileName = argv[1];
const char * outputImageFileName = argv[2];
using ScalarPixelType = itk::ImageIOBase::IOComponentType;
itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(
inputImageFileName, itk::ImageIOFactory::FileModeEnum::ReadMode);
if (!imageIO)
{
std::cerr << "Could not CreateImageIO for: " << inputImageFileName << std::endl;
return EXIT_FAILURE;
}
imageIO->SetFileName(inputImageFileName);
imageIO->ReadImageInformation();
const ScalarPixelType pixelType = imageIO->GetComponentType();
const size_t numDimensions = imageIO->GetNumberOfDimensions();
try
{
//unused cases are not instantiated because they greatly increase compile time
if (numDimensions==2 && pixelType == itk::ImageIOBase::UCHAR)
{
return doTest<itk::Image<unsigned char, 2> >(inputImageFileName, outputImageFileName);
}
if (numDimensions==3 && (pixelType == itk::ImageIOBase::SHORT
|| pixelType == itk::ImageIOBase::USHORT))
{
return doTest<itk::Image<short, 3> >(inputImageFileName, outputImageFileName);
}
if (numDimensions==3) //if not (u)short, then interpret as uint
{
return doTest<itk::Image<unsigned int, 3> >(inputImageFileName, outputImageFileName);
}
if (numDimensions==4 && pixelType == itk::ImageIOBase::UCHAR)
{
return doTest<itk::Image<unsigned char, 4> >(inputImageFileName, outputImageFileName);
}
std::cerr << "Unsupported image type:\n Dimensions: " << numDimensions;
std::cerr<< "\n Pixel type:" << imageIO->GetComponentTypeAsString(pixelType) << std::endl;
return EXIT_FAILURE;
}
catch( itk::ExceptionObject & error )
{
std::cerr << "Error: " << error << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before><commit_msg>[DF][NFC] Add npartitions kwarg to RDF docs<commit_after><|endoftext|> |
<commit_before><commit_msg>[tree] Fix memory leak in TTreeCacheUnzip #7429<commit_after><|endoftext|> |
<commit_before>/*
This file is part of the KDE alarm daemon.
Copyright (c) 1997-1999 Preston Brown
Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org>
Copyright (c) 2001 David Jarvie <software@astrojar.org.uk>
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., 675 Mass Ave, Cambridge, MA 02139, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
// $Id$
//
// KOrganizer/KAlarm alarm daemon main program
//
#include <stdlib.h>
#include <kdebug.h>
#include <klocale.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include "alarmapp.h"
static const char* kalarmdVersion = "3.1";
static const KCmdLineOptions options[] =
{
{ "login", I18N_NOOP("Application is being auto-started at KDE session start"), 0L },
{ 0L, 0L, 0L }
};
int main(int argc, char **argv)
{
KAboutData aboutData("kalarmd", I18N_NOOP("Alarm Daemon"),
kalarmdVersion, I18N_NOOP("KOrganizer/KAlarm Alarm Daemon"), KAboutData::License_GPL,
"(c) 1997-1999 Preston Brown\n(c) 2000-2001 Cornelius Schumacher\n(c) 2001 David Jarvie", 0L,
"http://korganizer.kde.org");
aboutData.addAuthor("Cornelius Schumacher",I18N_NOOP("Maintainer"),
"schumacher@kde.org");
aboutData.addAuthor("David Jarvie",I18N_NOOP("KAlarm Author"),
"software@astrojar.org.uk");
aboutData.addAuthor("Preston Brown",I18N_NOOP("Original Author"),
"pbrown@kde.org");
KCmdLineArgs::init(argc,argv,&aboutData);
KCmdLineArgs::addCmdLineOptions(options);
KUniqueApplication::addCmdLineOptions();
if (!AlarmApp::start())
exit(0);
AlarmApp app;
return app.exec();
}
<commit_msg>Update version number to 3.2<commit_after>/*
This file is part of the KDE alarm daemon.
Copyright (c) 1997-1999 Preston Brown
Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org>
Copyright (c) 2001 David Jarvie <software@astrojar.org.uk>
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., 675 Mass Ave, Cambridge, MA 02139, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
// $Id$
//
// KOrganizer/KAlarm alarm daemon main program
//
#include <stdlib.h>
#include <kdebug.h>
#include <klocale.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include "alarmapp.h"
static const char* kalarmdVersion = "3.2";
static const KCmdLineOptions options[] =
{
{ "login", I18N_NOOP("Application is being auto-started at KDE session start"), 0L },
{ 0L, 0L, 0L }
};
int main(int argc, char **argv)
{
KAboutData aboutData("kalarmd", I18N_NOOP("Alarm Daemon"),
kalarmdVersion, I18N_NOOP("KOrganizer/KAlarm Alarm Daemon"), KAboutData::License_GPL,
"(c) 1997-1999 Preston Brown\n(c) 2000-2001 Cornelius Schumacher\n(c) 2001 David Jarvie", 0L,
"http://korganizer.kde.org");
aboutData.addAuthor("Cornelius Schumacher",I18N_NOOP("Maintainer"),
"schumacher@kde.org");
aboutData.addAuthor("David Jarvie",I18N_NOOP("KAlarm Author"),
"software@astrojar.org.uk");
aboutData.addAuthor("Preston Brown",I18N_NOOP("Original Author"),
"pbrown@kde.org");
KCmdLineArgs::init(argc,argv,&aboutData);
KCmdLineArgs::addCmdLineOptions(options);
KUniqueApplication::addCmdLineOptions();
if (!AlarmApp::start())
exit(0);
AlarmApp app;
return app.exec();
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include "Lex.h"
#include "JZFileUtil.h"
#include <string.h>
TEST(LexUtil, eraseLineSeperator){
//these cases are a little complex in input because they are full of special charactor.
//don't remove \n if it doesn't have "\"
const char* input0 = "this is a test!\n this is a test";
uint64 bufSize0 = strlen(input0);
const char* eraseRet0 = LexUtil::eraseLineSeperator((const char*)input0, &bufSize0);
ASSERT_STREQ("this is a test!\n this is a test", eraseRet0);
//remove \ \n if it has a \ at the end of line
const char* input1 = "this is a test!\\ \n this is a test";
uint64 bufSize1 = strlen(input1);
const char* eraseRet1 = LexUtil::eraseLineSeperator((const char*)input1, &bufSize1);
ASSERT_STREQ("this is a test! this is a test", eraseRet1);
//remove \ \n if it has a \ at the end of line event if it's inside the ""
const char* input2 = "\"this is a test!\\ \n this is a test\"";
uint64 bufSize2 = strlen(input2);
const char* eraseRet2 = LexUtil::eraseLineSeperator((const char*)input2, &bufSize2);
ASSERT_STREQ("\"this is a test! this is a test\"", eraseRet2);
//don't remove \ \n if it is escaped by a \ before the last one
const char* input3 = "\"this is a test!\\\\ \n this is a test\"";
uint64 bufSize3 = strlen(input3);
const char* eraseRet3 = LexUtil::eraseLineSeperator((const char*)input3, &bufSize3);
ASSERT_STREQ("\"this is a test!\\\\ \n this is a test\"", eraseRet3);
//remove \ \n even if it is inside a comment
const char* input4 = "//this is a test!\\ \n this is a test";
uint64 bufSize4 = strlen(input4);
const char* eraseRet4 = LexUtil::eraseLineSeperator((const char*)input4, &bufSize4);
ASSERT_STREQ("//this is a test! this is a test", eraseRet4);
}
TEST(LexUtil, eraseComment){
//erase the comment until the end of line
const char* input0 = "this is a test!\n this is a test// this is a comment";
uint64 bufSize0 = strlen(input0);
const char* eraseRet0 = LexUtil::eraseComment((const char*)input0, &bufSize0);
ASSERT_STREQ("this is a test!\n this is a test", eraseRet0);
const char* input1 = "this is a test!\n this is a test/* this is a comment*/";
uint64 bufSize1 = strlen(input1);
const char* eraseRet1 = LexUtil::eraseComment((const char*)input1, &bufSize1);
ASSERT_STREQ("this is a test!\n this is a test", eraseRet1);
const char* input2 = "this is a test!\n this is a test// this is a comment\nthis is a new line";
uint64 bufSize2 = strlen(input2);
const char* eraseRet2 = LexUtil::eraseComment((const char*)input2, &bufSize2);
ASSERT_STREQ("this is a test!\n this is a test\nthis is a new line", eraseRet2);
const char* input3 = "this is a test!\n this /*this is a comment*/is a test";
uint64 bufSize3 = strlen(input3);
const char* eraseRet3 = LexUtil::eraseComment((const char*)input3, &bufSize3);
ASSERT_STREQ("this is a test!\n this is a test", eraseRet3);
const char* input4 = "this is a test!\n this is a test\n\"//don't erase this comment\"";
uint64 bufSize4 = strlen(input4);
const char* eraseRet4 = LexUtil::eraseComment((const char*)input4, &bufSize4);
ASSERT_STREQ("this is a test!\n this is a test\n\"//don't erase this comment\"", eraseRet4);
}
TEST(LexUtil, smallTestCase){
EXPECT_EQ(true, LexUtil::isLineEnder('\n'));
EXPECT_EQ(false, LexUtil::isLineEnder('\t'));
EXPECT_EQ(true, LexUtil::isEmptyInput('\t'));
EXPECT_EQ(true, LexUtil::isEmptyInput('\n'));
EXPECT_EQ(true, LexUtil::isEmptyInput(' '));
EXPECT_EQ(false, LexUtil::isEmptyInput('.'));
EXPECT_EQ(true, LexUtil::isBackSlant('\\'));
EXPECT_EQ(false, LexUtil::isBackSlant('/'));
EXPECT_EQ(true, LexUtil::isEmptyInput("\t \n "));
EXPECT_EQ(false, LexUtil::isEmptyInput(" a \n \t"));
EXPECT_EQ(true, LexUtil::isEndWithBackSlant("\\ \n"));
EXPECT_EQ(true, LexUtil::isEndWithBackSlant("\\\t\n"));
EXPECT_EQ(true, LexUtil::isEndWithBackSlant("\\\t \n"));
EXPECT_EQ(false, LexUtil::isEndWithBackSlant("\\n \n"));
EXPECT_EQ('\'', LexUtil::seperatorMatcher('\''));
EXPECT_EQ('\"', LexUtil::seperatorMatcher('\"'));
EXPECT_EQ('}', LexUtil::seperatorMatcher('{'));
EXPECT_EQ(']', LexUtil::seperatorMatcher('['));
EXPECT_EQ(')', LexUtil::seperatorMatcher('('));
EXPECT_EQ(true, LexUtil::isConstNumberChar('0'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('1'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('2'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('3'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('4'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('5'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('6'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('7'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('8'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('9'));
EXPECT_EQ(false, LexUtil::isConstNumberChar('.'));
EXPECT_EQ(false, LexUtil::isConstNumberChar('-'));
EXPECT_EQ(false, LexUtil::isConstNumberChar('+'));
EXPECT_EQ(false, LexUtil::isConstNumberChar('='));
ASSERT_STREQ("abce", LexUtil::eatLREmptyInput(" abce ").c_str());
ASSERT_STREQ("", LexUtil::eatLREmptyInput(" \t\n ").c_str());
ASSERT_STREQ("abce", LexUtil::eatLREmptyInput("abce ").c_str());
ASSERT_STREQ("abce", LexUtil::eatLREmptyInput(" abce").c_str());
EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("if"));
EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("ifdef"));
EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("ifndef"));
EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("endif"));
EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("else"));
EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("define"));
EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("param"));
EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("include"));
EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("once"));
EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("warning"));
EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("error"));
}
<commit_msg>add more test case on comment<commit_after>#include <gtest/gtest.h>
#include "Lex.h"
#include "JZFileUtil.h"
#include <string.h>
#include "JZMacroFunc.h"
TEST(LexUtil, eraseLineSeperator){
//these cases are a little complex in input because they are full of special charactor.
//don't remove \n if it doesn't have "\"
const char* input0 = "this is a test!\n this is a test";
uint64 bufSize0 = strlen(input0);
const char* eraseRet0 = LexUtil::eraseLineSeperator((const char*)input0, &bufSize0);
ASSERT_STREQ("this is a test!\n this is a test", eraseRet0);
//remove \ \n if it has a \ at the end of line
const char* input1 = "this is a test!\\ \n this is a test";
uint64 bufSize1 = strlen(input1);
const char* eraseRet1 = LexUtil::eraseLineSeperator((const char*)input1, &bufSize1);
ASSERT_STREQ("this is a test! this is a test", eraseRet1);
//remove \ \n if it has a \ at the end of line event if it's inside the ""
const char* input2 = "\"this is a test!\\ \n this is a test\"";
uint64 bufSize2 = strlen(input2);
const char* eraseRet2 = LexUtil::eraseLineSeperator((const char*)input2, &bufSize2);
ASSERT_STREQ("\"this is a test! this is a test\"", eraseRet2);
//don't remove \ \n if it is escaped by a \ before the last one
const char* input3 = "\"this is a test!\\\\ \n this is a test\"";
uint64 bufSize3 = strlen(input3);
const char* eraseRet3 = LexUtil::eraseLineSeperator((const char*)input3, &bufSize3);
ASSERT_STREQ("\"this is a test!\\\\ \n this is a test\"", eraseRet3);
//remove \ \n even if it is inside a comment
const char* input4 = "//this is a test!\\ \n this is a test";
uint64 bufSize4 = strlen(input4);
const char* eraseRet4 = LexUtil::eraseLineSeperator((const char*)input4, &bufSize4);
ASSERT_STREQ("//this is a test! this is a test", eraseRet4);
JZSAFE_DELETE(eraseRet0);
JZSAFE_DELETE(eraseRet1);
JZSAFE_DELETE(eraseRet2);
JZSAFE_DELETE(eraseRet3);
JZSAFE_DELETE(eraseRet4);
}
TEST(LexUtil, eraseComment){
//erase the comment until the end of line
const char* input0 = "this is a test!\n this is a test// this is a comment";
uint64 bufSize0 = strlen(input0);
const char* eraseRet0 = LexUtil::eraseComment((const char*)input0, &bufSize0);
ASSERT_STREQ("this is a test!\n this is a test", eraseRet0);
//erase the /*abc*/ comment
const char* input1 = "this is a test!\n this is a test/* this is a comment*/";
uint64 bufSize1 = strlen(input1);
const char* eraseRet1 = LexUtil::eraseComment((const char*)input1, &bufSize1);
ASSERT_STREQ("this is a test!\n this is a test", eraseRet1);
//do not erase the \n and next line
const char* input2 = "this is a test!\n this is a test// this is a comment\nthis is a new line";
uint64 bufSize2 = strlen(input2);
const char* eraseRet2 = LexUtil::eraseComment((const char*)input2, &bufSize2);
ASSERT_STREQ("this is a test!\n this is a test\nthis is a new line", eraseRet2);
// the /**/ comment should not effect the input
const char* input3 = "this is a test!\n this /*this is a comment*/is a test";
uint64 bufSize3 = strlen(input3);
const char* eraseRet3 = LexUtil::eraseComment((const char*)input3, &bufSize3);
ASSERT_STREQ("this is a test!\n this is a test", eraseRet3);
//comment is disabled in string
const char* input4 = "this is a test!\n this is a test\n\"//don't erase this comment\"";
uint64 bufSize4 = strlen(input4);
const char* eraseRet4 = LexUtil::eraseComment((const char*)input4, &bufSize4);
ASSERT_STREQ("this is a test!\n this is a test\n\"//don't erase this comment\"", eraseRet4);
//comment is disabled in string
const char* input5 = "this is a test!\n this is a test\n\"/*don't erase this comment*/\"";
uint64 bufSize5 = strlen(input5);
const char* eraseRet5 = LexUtil::eraseComment((const char*)input5, &bufSize5);
ASSERT_STREQ("this is a test!\n this is a test\n\"/*don't erase this comment*/\"", eraseRet5);
//erase the comment with "
const char* input6 = "this is a test!\n this is a test// this is a comment//\"this is a comment with \"\"";
uint64 bufSize6 = strlen(input6);
const char* eraseRet6 = LexUtil::eraseComment((const char*)input6, &bufSize6);
ASSERT_STREQ("this is a test!\n this is a test", eraseRet6);
//erasee the comment with "
const char* input7 = "this is a test!\n /*\"this is a comment inside\"*/this is a test// this is a comment";
uint64 bufSize7 = strlen(input7);
const char* eraseRet7 = LexUtil::eraseComment((const char*)input7, &bufSize7);
ASSERT_STREQ("this is a test!\n this is a test", eraseRet7);
JZSAFE_DELETE(eraseRet0);
JZSAFE_DELETE(eraseRet1);
JZSAFE_DELETE(eraseRet2);
JZSAFE_DELETE(eraseRet3);
JZSAFE_DELETE(eraseRet4);
JZSAFE_DELETE(eraseRet5);
JZSAFE_DELETE(eraseRet6);
JZSAFE_DELETE(eraseRet7);
// JZSAFE_DELETE(eraseRet8);
// JZSAFE_DELETE(eraseRet9);
}
TEST(LexUtil, smallTestCase){
EXPECT_EQ(true, LexUtil::isLineEnder('\n'));
EXPECT_EQ(false, LexUtil::isLineEnder('\t'));
EXPECT_EQ(true, LexUtil::isEmptyInput('\t'));
EXPECT_EQ(true, LexUtil::isEmptyInput('\n'));
EXPECT_EQ(true, LexUtil::isEmptyInput(' '));
EXPECT_EQ(false, LexUtil::isEmptyInput('.'));
EXPECT_EQ(true, LexUtil::isBackSlant('\\'));
EXPECT_EQ(false, LexUtil::isBackSlant('/'));
EXPECT_EQ(true, LexUtil::isEmptyInput("\t \n "));
EXPECT_EQ(false, LexUtil::isEmptyInput(" a \n \t"));
EXPECT_EQ(true, LexUtil::isEndWithBackSlant("\\ \n"));
EXPECT_EQ(true, LexUtil::isEndWithBackSlant("\\\t\n"));
EXPECT_EQ(true, LexUtil::isEndWithBackSlant("\\\t \n"));
EXPECT_EQ(false, LexUtil::isEndWithBackSlant("\\n \n"));
EXPECT_EQ('\'', LexUtil::seperatorMatcher('\''));
EXPECT_EQ('\"', LexUtil::seperatorMatcher('\"'));
EXPECT_EQ('}', LexUtil::seperatorMatcher('{'));
EXPECT_EQ(']', LexUtil::seperatorMatcher('['));
EXPECT_EQ(')', LexUtil::seperatorMatcher('('));
EXPECT_EQ(true, LexUtil::isConstNumberChar('0'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('1'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('2'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('3'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('4'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('5'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('6'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('7'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('8'));
EXPECT_EQ(true, LexUtil::isConstNumberChar('9'));
EXPECT_EQ(false, LexUtil::isConstNumberChar('.'));
EXPECT_EQ(false, LexUtil::isConstNumberChar('-'));
EXPECT_EQ(false, LexUtil::isConstNumberChar('+'));
EXPECT_EQ(false, LexUtil::isConstNumberChar('='));
ASSERT_STREQ("abce", LexUtil::eatLREmptyInput(" abce ").c_str());
ASSERT_STREQ("", LexUtil::eatLREmptyInput(" \t\n ").c_str());
ASSERT_STREQ("abce", LexUtil::eatLREmptyInput("abce ").c_str());
ASSERT_STREQ("abce", LexUtil::eatLREmptyInput(" abce").c_str());
EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("if"));
EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("ifdef"));
EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("ifndef"));
EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("endif"));
EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("else"));
EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("define"));
EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("param"));
EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("include"));
EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("once"));
EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("warning"));
EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("error"));
}
<|endoftext|> |
<commit_before>/*
@ 0xCCCCCCCC
*/
#include "kbase/pickle.h"
#include <algorithm>
#include "kbase/string_util.h"
namespace {
// Rounds up `num` to the nearest multiple of `factor`.
constexpr size_t RoundToMultiple(size_t num, size_t factor)
{
return factor == 0 ? 0 : (num - 1 - (num - 1) % factor + factor);
}
// Zeros padding memory; otherwise some memory detectors may complain about
// uninitialized memory.
void SanitizePadding(byte* padding_begin, size_t padding_size)
{
if (padding_size != 0) {
memset(padding_begin, 0, padding_size);
}
}
} // namespace
namespace kbase {
PickleReader::PickleReader(const void* pickled_data, size_t size_in_bytes)
: read_ptr_(static_cast<const byte*>(pickled_data) + sizeof(Pickle::Header)),
data_end_(read_ptr_ + size_in_bytes - sizeof(Pickle::Header))
{}
PickleReader::PickleReader(const Pickle& pickle)
: read_ptr_(pickle.payload()),
data_end_(pickle.end_of_payload())
{}
PickleReader& PickleReader::operator>>(std::string& value)
{
PickleReader& reader = *this;
size_t length;
reader >> length;
auto* dest = WriteInto(value, length + 1);
Read(dest, sizeof(std::string::value_type) * length);
return reader;
}
PickleReader& PickleReader::operator>>(std::wstring& value)
{
PickleReader& reader = *this;
size_t length;
reader >> length;
auto* dest = WriteInto(value, length + 1);
Read(dest, sizeof(std::wstring::value_type) * length);
return reader;
}
void PickleReader::Read(void* dest, size_t size_in_bytes)
{
ENSURE(CHECK, !!*this).Require();
memcpy_s(dest, size_in_bytes, read_ptr_, size_in_bytes);
SeekReadPosition(size_in_bytes);
}
void PickleReader::SeekReadPosition(size_t data_size) noexcept
{
size_t rounded_size = RoundToMultiple(data_size, sizeof(uint32_t));
if (read_ptr_ + rounded_size > data_end_) {
read_ptr_ += data_size;
} else {
read_ptr_ += rounded_size;
}
}
void PickleReader::SkipData(size_t data_size) noexcept
{
SeekReadPosition(data_size);
}
// -*- Pickle -*-
Pickle::Pickle()
: header_(nullptr), capacity_(0)
{
ResizeCapacity(kCapacityUnit);
header_->payload_size = 0;
}
Pickle::Pickle(const void* data, size_t size_in_bytes)
: header_(nullptr), capacity_(0)
{
ENSURE(CHECK, data != nullptr && size_in_bytes > 0).Require();
ResizeCapacity(size_in_bytes);
memcpy_s(header_, capacity_, data, size_in_bytes);
}
Pickle::Pickle(const Pickle& other)
: header_(nullptr), capacity_(0)
{
ResizeCapacity(other.size());
memcpy_s(header_, capacity_, other.header_, other.size());
}
Pickle::Pickle(Pickle&& other) noexcept
: header_(other.header_), capacity_(other.capacity_)
{
other.header_ = nullptr;
other.capacity_ = 0;
}
Pickle::~Pickle()
{
// Technically, only pickles having been moved have null header.
if (header_ != nullptr) {
free(header_);
}
}
Pickle& Pickle::operator=(const Pickle& rhs)
{
if (this != &rhs) {
if (capacity_ < rhs.size()) {
ResizeCapacity(rhs.size());
}
memcpy_s(header_, capacity_, rhs.header_, rhs.size());
}
return *this;
}
Pickle& Pickle::operator=(Pickle&& rhs) noexcept
{
if (this != &rhs) {
Header* old_header = header_;
header_ = rhs.header_;
capacity_ = rhs.capacity_;
rhs.header_ = nullptr;
rhs.capacity_ = 0;
free(old_header);
}
return *this;
}
void Pickle::ResizeCapacity(size_t new_capacity)
{
ENSURE(CHECK, new_capacity > capacity_).Require();
new_capacity = RoundToMultiple(new_capacity, kCapacityUnit);
void* ptr = realloc(header_, new_capacity);
ENSURE(RAISE, ptr != nullptr).Require("Failed to realloc a new memory block!");
header_ = static_cast<Header*>(ptr);
capacity_ = new_capacity;
}
Pickle& Pickle::operator<<(const std::string& value)
{
Pickle& pickle = *this;
auto length = value.length();
pickle << length;
Write(value.data(), length * sizeof(char));
return pickle;
}
Pickle& Pickle::operator<<(const std::wstring& value)
{
Pickle& pickle = *this;
auto length = value.length();
pickle << length;
Write(value.data(), length * sizeof(wchar_t));
return pickle;
}
void Pickle::Write(const void* data, size_t size_in_bytes)
{
size_t last_payload_size = payload_size();
byte* dest = SeekWritePosition(size_in_bytes);
size_t free_buf_size = capacity_ - (dest - reinterpret_cast<byte*>(header_));
memcpy_s(dest, free_buf_size, data, size_in_bytes);
size_t padding_size = payload_size() - last_payload_size - size_in_bytes;
SanitizePadding(dest - padding_size, padding_size);
}
byte* Pickle::SeekWritePosition(size_t length)
{
// Writing starts at a uint32-aligned offset.
size_t offset = RoundToMultiple(header_->payload_size, sizeof(uint32_t));
size_t required_size = offset + length;
size_t required_total_size = required_size + sizeof(Header);
if (required_total_size > capacity_) {
ResizeCapacity(std::max(capacity_ << 1, required_total_size));
}
ENSURE(CHECK, required_size <= std::numeric_limits<uint32_t>::max())(required_size).Require();
header_->payload_size = static_cast<uint32_t>(required_size);
return mutable_payload() + offset;
}
} // namespace kbase<commit_msg>Pickle: Fix the bug that couldn't de-serialize an empty std::string correctly.<commit_after>/*
@ 0xCCCCCCCC
*/
#include "kbase/pickle.h"
#include <algorithm>
#include "kbase/string_util.h"
namespace {
// Rounds up `num` to the nearest multiple of `factor`.
constexpr size_t RoundToMultiple(size_t num, size_t factor)
{
return factor == 0 ? 0 : (num - 1 - (num - 1) % factor + factor);
}
// Zeros padding memory; otherwise some memory detectors may complain about
// uninitialized memory.
void SanitizePadding(byte* padding_begin, size_t padding_size)
{
if (padding_size != 0) {
memset(padding_begin, 0, padding_size);
}
}
} // namespace
namespace kbase {
PickleReader::PickleReader(const void* pickled_data, size_t size_in_bytes)
: read_ptr_(static_cast<const byte*>(pickled_data) + sizeof(Pickle::Header)),
data_end_(read_ptr_ + size_in_bytes - sizeof(Pickle::Header))
{}
PickleReader::PickleReader(const Pickle& pickle)
: read_ptr_(pickle.payload()),
data_end_(pickle.end_of_payload())
{}
PickleReader& PickleReader::operator>>(std::string& value)
{
PickleReader& reader = *this;
size_t length;
reader >> length;
if (length != 0) {
auto* dest = WriteInto(value, length + 1);
Read(dest, sizeof(std::string::value_type) * length);
}
return reader;
}
PickleReader& PickleReader::operator>>(std::wstring& value)
{
PickleReader& reader = *this;
size_t length;
reader >> length;
if (length != 0) {
auto* dest = WriteInto(value, length + 1);
Read(dest, sizeof(std::wstring::value_type) * length);
}
return reader;
}
void PickleReader::Read(void* dest, size_t size_in_bytes)
{
ENSURE(CHECK, !!*this).Require();
memcpy_s(dest, size_in_bytes, read_ptr_, size_in_bytes);
SeekReadPosition(size_in_bytes);
}
void PickleReader::SeekReadPosition(size_t data_size) noexcept
{
size_t rounded_size = RoundToMultiple(data_size, sizeof(uint32_t));
if (read_ptr_ + rounded_size > data_end_) {
read_ptr_ += data_size;
} else {
read_ptr_ += rounded_size;
}
}
void PickleReader::SkipData(size_t data_size) noexcept
{
SeekReadPosition(data_size);
}
// -*- Pickle -*-
Pickle::Pickle()
: header_(nullptr), capacity_(0)
{
ResizeCapacity(kCapacityUnit);
header_->payload_size = 0;
}
Pickle::Pickle(const void* data, size_t size_in_bytes)
: header_(nullptr), capacity_(0)
{
ENSURE(CHECK, data != nullptr && size_in_bytes > 0).Require();
ResizeCapacity(size_in_bytes);
memcpy_s(header_, capacity_, data, size_in_bytes);
}
Pickle::Pickle(const Pickle& other)
: header_(nullptr), capacity_(0)
{
ResizeCapacity(other.size());
memcpy_s(header_, capacity_, other.header_, other.size());
}
Pickle::Pickle(Pickle&& other) noexcept
: header_(other.header_), capacity_(other.capacity_)
{
other.header_ = nullptr;
other.capacity_ = 0;
}
Pickle::~Pickle()
{
// Technically, only pickles having been moved have null header.
if (header_ != nullptr) {
free(header_);
}
}
Pickle& Pickle::operator=(const Pickle& rhs)
{
if (this != &rhs) {
if (capacity_ < rhs.size()) {
ResizeCapacity(rhs.size());
}
memcpy_s(header_, capacity_, rhs.header_, rhs.size());
}
return *this;
}
Pickle& Pickle::operator=(Pickle&& rhs) noexcept
{
if (this != &rhs) {
Header* old_header = header_;
header_ = rhs.header_;
capacity_ = rhs.capacity_;
rhs.header_ = nullptr;
rhs.capacity_ = 0;
free(old_header);
}
return *this;
}
void Pickle::ResizeCapacity(size_t new_capacity)
{
ENSURE(CHECK, new_capacity > capacity_).Require();
new_capacity = RoundToMultiple(new_capacity, kCapacityUnit);
void* ptr = realloc(header_, new_capacity);
ENSURE(RAISE, ptr != nullptr).Require("Failed to realloc a new memory block!");
header_ = static_cast<Header*>(ptr);
capacity_ = new_capacity;
}
Pickle& Pickle::operator<<(const std::string& value)
{
Pickle& pickle = *this;
auto length = value.length();
pickle << length;
Write(value.data(), length * sizeof(char));
return pickle;
}
Pickle& Pickle::operator<<(const std::wstring& value)
{
Pickle& pickle = *this;
auto length = value.length();
pickle << length;
Write(value.data(), length * sizeof(wchar_t));
return pickle;
}
void Pickle::Write(const void* data, size_t size_in_bytes)
{
size_t last_payload_size = payload_size();
byte* dest = SeekWritePosition(size_in_bytes);
size_t free_buf_size = capacity_ - (dest - reinterpret_cast<byte*>(header_));
memcpy_s(dest, free_buf_size, data, size_in_bytes);
size_t padding_size = payload_size() - last_payload_size - size_in_bytes;
SanitizePadding(dest - padding_size, padding_size);
}
byte* Pickle::SeekWritePosition(size_t length)
{
// Writing starts at a uint32-aligned offset.
size_t offset = RoundToMultiple(header_->payload_size, sizeof(uint32_t));
size_t required_size = offset + length;
size_t required_total_size = required_size + sizeof(Header);
if (required_total_size > capacity_) {
ResizeCapacity(std::max(capacity_ << 1, required_total_size));
}
ENSURE(CHECK, required_size <= std::numeric_limits<uint32_t>::max())(required_size).Require();
header_->payload_size = static_cast<uint32_t>(required_size);
return mutable_payload() + offset;
}
} // namespace kbase<|endoftext|> |
<commit_before>/**
* @file FDTD_1D.cpp
* @brief Implementation of the FDTD_1D class
* @author Ben Frazier
* @date 08/12/2017 */
#include "FDTD_1D.h"
#include <math.h>
namespace CEM
{
/** \brief FDTD_1D Overloaded Constructor
*
* Standard Constructor
*/
FDTD_1D::FDTD_1D(InputDataInterface * input):
initialized(false),
ABC(SimpleABC),
imp_(377.0),
dataSize_(0)
{
InitializeEngine(input);
}
/**
* \brief Initialize the FDTD_1D engine
*
* This function sets the size of the E and H vectors
* @param input The input structure read in from the input file*/
void FDTD_1D::InitializeEngine(InputDataInterface * input)
{
dataSize_ = input->getVectorLength();
ABC = SimpleABC;
H.resize(dataSize_);
E.resize(dataSize_);
sourceAmplitude_ = input->getSourceAmplitude();
sourceType_ = input->getSourceType();
pulseWidth_ = input->getPulseWidth();
sourceDelay_ = input->getSourceDelay();
sourceIndex_ = input->getSpatialIndex();
pulseWidth2_ = pulseWidth_*pulseWidth_;
initialized = true;
}
/**
* \brief Update the E and H fields
*
* This function updates the E and H fields by stepping to the specified time index
* @param time The next time step to update*/
void FDTD_1D::UpdateFields(double time)
{
applyBC_H();
//update the H Field
for (int mm = 0; mm < dataSize_ - 1; mm++)
H[mm] = H[mm] + (E[mm + 1] - E[mm]) / imp_;
//correct H field --> TFSF
H[sourceIndex_ -1] -= computeSourceAmplitude(time,0)/imp_;
applyBC_E();
//Now update the E Field
for (int mm = 1; mm < dataSize_; mm++)
E[mm] = E[mm] + (H[mm] - H[mm - 1]) * imp_;
//update the source
E[sourceIndex_] += computeSourceAmplitude(time,1.0);
}
/**
* \brief Compute the amplitude of the source
*
* @param time The time to compute the source
* @param shift The value to shift the time (TFSF)*/
double FDTD_1D::computeSourceAmplitude(double time, double shift)
{
double val = sourceAmplitude_ *exp(-(time - sourceDelay_ + shift) * (time - sourceDelay_ + shift) / pulseWidth2_);
return val;
}
/**
* \brief Return the E field at a specified index
*
* This function gets the E field at a given index and returns 0 if the requested
* index exceeds the size of the array
* @param index The index of the E field to retrieve*/
double FDTD_1D::getEField(int index)
{
if (index < dataSize_)
return E[index];
else
return 0;
}
/**
* \brief Return the H field at a specified index
*
* This function gets the H field at a given index and returns 0 if the requested
* index exceeds the size of the array
* @param index The index of the H field to retrieve*/
double FDTD_1D::getHField(int index)
{
if (index < dataSize_)
return H[index];
else
return 0;
}
void FDTD_1D::simpleABC_E()
{
E[0] = E[1];
}
void FDTD_1D::simpleABC_H()
{
H[dataSize_-1] = H[dataSize_-2];
}
void FDTD_1D::applyBC_E()
{
switch (ABC)
{
case NoABC:
break;
case SimpleABC:
simpleABC_E();
break;
case TFSF_ABC:
break;
default:
break;
}
}
void FDTD_1D::applyBC_H()
{
switch (ABC)
{
case NoABC:
break;
case SimpleABC:
simpleABC_H();
break;
case TFSF_ABC:
break;
default:
break;
}
}
}//end of namespace
<commit_msg>FDTD now initializes the impedance from the namespace constant<commit_after>/**
* @file FDTD_1D.cpp
* @brief Implementation of the FDTD_1D class
* @author Ben Frazier
* @date 08/12/2017 */
#include "FDTD_1D.h"
#include <math.h>
#include "CEMdefs.h"
namespace CEM
{
/** \brief FDTD_1D Overloaded Constructor
*
* Standard Constructor
*/
FDTD_1D::FDTD_1D(InputDataInterface * input):
initialized(false),
ABC(SimpleABC),
imp_(CEM::imp0),
dataSize_(0)
{
InitializeEngine(input);
}
/**
* \brief Initialize the FDTD_1D engine
*
* This function sets the size of the E and H vectors
* @param input The input structure read in from the input file*/
void FDTD_1D::InitializeEngine(InputDataInterface * input)
{
dataSize_ = input->getVectorLength();
ABC = SimpleABC;
H.resize(dataSize_);
E.resize(dataSize_);
sourceAmplitude_ = input->getSourceAmplitude();
sourceType_ = input->getSourceType();
pulseWidth_ = input->getPulseWidth();
sourceDelay_ = input->getSourceDelay();
sourceIndex_ = input->getSpatialIndex();
pulseWidth2_ = pulseWidth_*pulseWidth_;
initialized = true;
}
/**
* \brief Update the E and H fields
*
* This function updates the E and H fields by stepping to the specified time index
* @param time The next time step to update*/
void FDTD_1D::UpdateFields(double time)
{
applyBC_H();
//update the H Field
for (int mm = 0; mm < dataSize_ - 1; mm++)
H[mm] = H[mm] + (E[mm + 1] - E[mm]) / imp_;
//correct H field --> TFSF
H[sourceIndex_ -1] -= computeSourceAmplitude(time,0)/imp_;
applyBC_E();
//Now update the E Field
for (int mm = 1; mm < dataSize_; mm++)
E[mm] = E[mm] + (H[mm] - H[mm - 1]) * imp_;
//update the source
E[sourceIndex_] += computeSourceAmplitude(time,1.0);
}
/**
* \brief Compute the amplitude of the source
*
* @param time The time to compute the source
* @param shift The value to shift the time (TFSF)*/
double FDTD_1D::computeSourceAmplitude(double time, double shift)
{
double val = sourceAmplitude_ *exp(-(time - sourceDelay_ + shift) * (time - sourceDelay_ + shift) / pulseWidth2_);
return val;
}
/**
* \brief Return the E field at a specified index
*
* This function gets the E field at a given index and returns 0 if the requested
* index exceeds the size of the array
* @param index The index of the E field to retrieve*/
double FDTD_1D::getEField(int index)
{
if (index < dataSize_)
return E[index];
else
return 0;
}
/**
* \brief Return the H field at a specified index
*
* This function gets the H field at a given index and returns 0 if the requested
* index exceeds the size of the array
* @param index The index of the H field to retrieve*/
double FDTD_1D::getHField(int index)
{
if (index < dataSize_)
return H[index];
else
return 0;
}
void FDTD_1D::simpleABC_E()
{
E[0] = E[1];
}
void FDTD_1D::simpleABC_H()
{
H[dataSize_-1] = H[dataSize_-2];
}
void FDTD_1D::applyBC_E()
{
switch (ABC)
{
case NoABC:
break;
case SimpleABC:
simpleABC_E();
break;
case TFSF_ABC:
break;
default:
break;
}
}
void FDTD_1D::applyBC_H()
{
switch (ABC)
{
case NoABC:
break;
case SimpleABC:
simpleABC_H();
break;
case TFSF_ABC:
break;
default:
break;
}
}
}//end of namespace
<|endoftext|> |
<commit_before>/* Optional packages. You might want to integrate this with your build system e.g. config.h from ./configure. */
#ifndef UTIL_HAVE__
#define UTIL_HAVE__
#ifndef HAVE_ICU
//#define HAVE_ICU
#endif
#ifndef HAVE_BOOST
//#define HAVE_BOOST
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#endif // UTIL_HAVE__
<commit_msg>Patch up build for now, still no compressed support<commit_after>/* Optional packages. You might want to integrate this with your build system e.g. config.h from ./configure. */
#ifndef UTIL_HAVE__
#define UTIL_HAVE__
#ifndef HAVE_ICU
//#define HAVE_ICU
#endif
#ifndef HAVE_BOOST
//#define HAVE_BOOST
#endif
#ifdef HAVE_CONFIG_H
// Chris; uncomment this line.
//#include "config.h"
#endif
#endif // UTIL_HAVE__
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <eigen3/Eigen/Dense>
#include "common.h"
#include "mem_dense_matrix.h"
using namespace fm;
class set_col_operate: public type_set_operate<double>
{
size_t num_cols;
public:
set_col_operate(size_t num_cols) {
this->num_cols = num_cols;
}
void set(double *arr, size_t num_eles, off_t row_idx, off_t col_idx) const {
for (size_t i = 0; i < num_eles; i++) {
arr[i] = (row_idx + i) * num_cols + col_idx;
}
}
};
class set_row_operate: public type_set_operate<double>
{
size_t num_cols;
public:
set_row_operate(size_t num_cols) {
this->num_cols = num_cols;
}
void set(double *arr, size_t num_eles, off_t row_idx, off_t col_idx) const {
for (size_t i = 0; i < num_eles; i++) {
arr[i] = row_idx * num_cols + col_idx + i;
}
}
};
/*
* This function is to compare the performance of inner product between
* in-memory column-wise dense matrix and Eigen matrix.
* I assume Eigen matrix should give us the best performance.
*/
template<class Type>
typename type_mem_dense_matrix<Type>::ptr test1(size_t nrow, size_t ncol,
size_t right_ncol)
{
struct timeval start, end;
gettimeofday(&start, NULL);
typename type_mem_dense_matrix<Type>::ptr m1
= type_mem_dense_matrix<Type>::create(nrow, ncol,
matrix_layout_t::L_COL, set_col_operate(ncol));
gettimeofday(&end, NULL);
printf("It takes %.3f seconds to construct input column matrix\n",
time_diff(start, end));
typename type_mem_dense_matrix<Type>::ptr m2
= type_mem_dense_matrix<Type>::create(ncol, right_ncol,
matrix_layout_t::L_COL, set_col_operate(ncol));
gettimeofday(&start, NULL);
Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> eigen_m1(nrow, ncol);
#pragma omp parallel for
for (size_t i = 0; i < nrow; i++) {
for (size_t j = 0; j < ncol; j++)
eigen_m1(i, j) = i * ncol + j;
}
gettimeofday(&end, NULL);
printf("It takes %.3f seconds to construct input Eigen matrix\n",
time_diff(start, end));
Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> eigen_m2(ncol, right_ncol);
for (size_t i = 0; i < ncol; i++) {
for (size_t j = 0; j < right_ncol; j++)
eigen_m2(i, j) = i * right_ncol + j;
}
start = end;
typename type_mem_dense_matrix<Type>::ptr res1
= multiply<Type, Type, Type>(*m1, *m2);
gettimeofday(&end, NULL);
printf("It takes %.3f seconds to multiply column matrix\n",
time_diff(start, end));
assert(res1->get_num_rows() == m1->get_num_rows());
assert(res1->get_num_cols() == m2->get_num_cols());
printf("The result matrix has %ld rows and %ld columns\n",
res1->get_num_rows(), res1->get_num_cols());
start = end;
Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> eigen_res = eigen_m1 * eigen_m2;
gettimeofday(&end, NULL);
assert((size_t) eigen_res.rows() == res1->get_num_rows());
assert((size_t) eigen_res.cols() == res1->get_num_cols());
printf("It takes %.3f seconds to multiply Eigen matrix\n",
time_diff(start, end));
#pragma omp parallel for
for (size_t i = 0; i < res1->get_num_rows(); i++) {
for (size_t j = 0; j < res1->get_num_cols(); j++) {
assert(res1->get(i, j) == eigen_res(i, j));
}
}
return res1;
}
/*
* This multiplies a large row-wise matrix with a small column-wise matrix.
* It should give us the best performance.
*/
template<class Type>
typename type_mem_dense_matrix<Type>::ptr test2(size_t nrow, size_t ncol,
size_t right_ncol)
{
struct timeval start, end;
gettimeofday(&start, NULL);
typename type_mem_dense_matrix<Type>::ptr m1
= type_mem_dense_matrix<Type>::create(nrow, ncol,
matrix_layout_t::L_ROW, set_row_operate(ncol));
gettimeofday(&end, NULL);
printf("It takes %.3f seconds to construct input row matrix\n",
time_diff(start, end));
typename type_mem_dense_matrix<Type>::ptr m2
= type_mem_dense_matrix<Type>::create(ncol, right_ncol,
matrix_layout_t::L_COL, set_col_operate(ncol));
typename type_mem_dense_matrix<Type>::ptr res_m
= type_mem_dense_matrix<Type>::create(nrow, right_ncol,
matrix_layout_t::L_ROW);
gettimeofday(&start, NULL);
const mem_row_dense_matrix &row_m
= (const mem_row_dense_matrix &) m1->get_matrix();
const mem_col_dense_matrix &col_m
= (const mem_col_dense_matrix &) m2->get_matrix();
const mem_row_dense_matrix &res_row_m
= (const mem_row_dense_matrix &) res_m->get_matrix();
#pragma omp parallel for
for (size_t i = 0; i < nrow; i++) {
const Type *in_row = (const Type *) row_m.get_row(i);
Type *out_row = (Type *) res_row_m.get_row(i);
for (size_t j = 0; j < right_ncol; j++) {
const Type *in_col = (const Type *) col_m.get_col(j);
out_row[j] = 0;
for (size_t k = 0; k < ncol; k++)
out_row[j] += in_row[k] * in_col[k];
}
}
gettimeofday(&end, NULL);
printf("It takes %.3f seconds to multiply row matrix\n",
time_diff(start, end));
return res_m;
}
/*
* This multiplies a large column-wise matrix with a small column-wise matrix
* directly. This implementation should have good performance.
*/
template<class Type>
typename type_mem_dense_matrix<Type>::ptr test3(size_t nrow, size_t ncol,
size_t right_ncol)
{
struct timeval start, end;
gettimeofday(&start, NULL);
typename type_mem_dense_matrix<Type>::ptr m1
= type_mem_dense_matrix<Type>::create(nrow, ncol,
matrix_layout_t::L_COL, set_col_operate(ncol));
gettimeofday(&end, NULL);
printf("It takes %.3f seconds to construct input column matrix\n",
time_diff(start, end));
typename type_mem_dense_matrix<Type>::ptr m2
= type_mem_dense_matrix<Type>::create(ncol, right_ncol,
matrix_layout_t::L_COL, set_col_operate(ncol));
typename type_mem_dense_matrix<Type>::ptr res_m
= type_mem_dense_matrix<Type>::create(nrow, right_ncol,
matrix_layout_t::L_COL);
gettimeofday(&start, NULL);
const mem_col_dense_matrix &left_m
= (const mem_col_dense_matrix &) m1->get_matrix();
const mem_col_dense_matrix &right_m
= (const mem_col_dense_matrix &) m2->get_matrix();
const mem_col_dense_matrix &res_col_m
= (const mem_col_dense_matrix &) res_m->get_matrix();
#pragma omp parallel for
for (size_t i = 0; i < nrow; i++) {
for (size_t j = 0; j < right_ncol; j++) {
const Type *right_col = (const Type *) right_m.get_col(j);
Type *out_col = (Type *) res_col_m.get_col(j);
out_col[i] = 0;
for (size_t k = 0; k < ncol; k++) {
const Type *left_col = (const Type *) left_m.get_col(k);
out_col[i] += left_col[i] * right_col[k];
}
}
}
gettimeofday(&end, NULL);
printf("It takes %.3f seconds to multiply column matrix\n",
time_diff(start, end));
return res_m;
}
template<class Type>
void check_result(typename type_mem_dense_matrix<Type>::ptr m1,
typename type_mem_dense_matrix<Type>::ptr m2)
{
assert(m1->get_num_rows() == m2->get_num_rows());
assert(m1->get_num_cols() == m2->get_num_cols());
#pragma omp parallel for
for (size_t i = 0; i < m1->get_num_rows(); i++) {
for (size_t j = 0; j < m1->get_num_cols(); j++) {
assert(m1->get(i, j) == m2->get(i, j));
}
}
}
int main()
{
size_t nrow = 1024 * 1024 * 124;
size_t ncol = 5;
D_mem_dense_matrix::ptr res1 = test1<double>(nrow, ncol, ncol);
D_mem_dense_matrix::ptr res2 = test2<double>(nrow, ncol, ncol);
check_result<double>(res1, res2);
res2 = test3<double>(nrow, ncol, ncol);
check_result<double>(res1, res2);
}
<commit_msg>[Matrix]: reconstruct the test for matrix multiplication.<commit_after>#include <stdio.h>
#include <eigen3/Eigen/Dense>
#include "common.h"
#include "mem_dense_matrix.h"
using namespace fm;
class set_col_operate: public type_set_operate<double>
{
size_t num_cols;
public:
set_col_operate(size_t num_cols) {
this->num_cols = num_cols;
}
void set(double *arr, size_t num_eles, off_t row_idx, off_t col_idx) const {
for (size_t i = 0; i < num_eles; i++) {
arr[i] = (row_idx + i) * num_cols + col_idx;
}
}
};
class set_row_operate: public type_set_operate<double>
{
size_t num_cols;
public:
set_row_operate(size_t num_cols) {
this->num_cols = num_cols;
}
void set(double *arr, size_t num_eles, off_t row_idx, off_t col_idx) const {
for (size_t i = 0; i < num_eles; i++) {
arr[i] = row_idx * num_cols + col_idx + i;
}
}
};
template<class Type>
void test_eigen(size_t nrow, size_t ncol, size_t right_ncol)
{
struct timeval start, end;
printf("test eigen: M(%ld x %ld) * M(%ld %ld)\n", nrow, ncol, ncol, right_ncol);
gettimeofday(&start, NULL);
Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> eigen_m1(nrow, ncol);
#pragma omp parallel for
for (size_t i = 0; i < nrow; i++) {
for (size_t j = 0; j < ncol; j++)
eigen_m1(i, j) = i * ncol + j;
}
gettimeofday(&end, NULL);
printf("It takes %.3f seconds to construct input Eigen matrix\n",
time_diff(start, end));
Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> eigen_m2(ncol, right_ncol);
for (size_t i = 0; i < ncol; i++) {
for (size_t j = 0; j < right_ncol; j++)
eigen_m2(i, j) = i * right_ncol + j;
}
start = end;
Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> eigen_res = eigen_m1 * eigen_m2;
gettimeofday(&end, NULL);
printf("It takes %.3f seconds to multiply Eigen matrix\n",
time_diff(start, end));
}
/*
* This function is to compare the performance of inner product between
* in-memory column-wise dense matrix and Eigen matrix.
* I assume Eigen matrix should give us the best performance.
*/
template<class Type>
typename type_mem_dense_matrix<Type>::ptr test_MM1(size_t nrow, size_t ncol,
size_t right_ncol)
{
struct timeval start, end;
printf("test tall col-wise matrix: M(%ld x %ld) * M(%ld %ld)\n",
nrow, ncol, ncol, right_ncol);
gettimeofday(&start, NULL);
typename type_mem_dense_matrix<Type>::ptr m1
= type_mem_dense_matrix<Type>::create(nrow, ncol,
matrix_layout_t::L_COL, set_col_operate(ncol), true);
gettimeofday(&end, NULL);
printf("It takes %.3f seconds to construct input column matrix\n",
time_diff(start, end));
typename type_mem_dense_matrix<Type>::ptr m2
= type_mem_dense_matrix<Type>::create(ncol, right_ncol,
matrix_layout_t::L_COL, set_col_operate(ncol));
gettimeofday(&start, NULL);
typename type_mem_dense_matrix<Type>::ptr res1
= par_multiply<Type, Type, Type>(*m1, *m2);
gettimeofday(&end, NULL);
printf("It takes %.3f seconds to multiply column matrix in parallel\n",
time_diff(start, end));
assert(res1->get_num_rows() == m1->get_num_rows());
assert(res1->get_num_cols() == m2->get_num_cols());
printf("The result matrix has %ld rows and %ld columns\n",
res1->get_num_rows(), res1->get_num_cols());
return res1;
}
/*
* This multiplies a large (tall and narrow) row-wise matrix with a small
* column-wise matrix. It should give us the best performance.
*/
template<class Type>
typename type_mem_dense_matrix<Type>::ptr test_MM2(size_t nrow, size_t ncol,
size_t right_ncol)
{
struct timeval start, end;
printf("test tall row-wise matrix (best case): M(%ld x %ld) * M(%ld %ld)\n",
nrow, ncol, ncol, right_ncol);
gettimeofday(&start, NULL);
typename type_mem_dense_matrix<Type>::ptr m1
= type_mem_dense_matrix<Type>::create(nrow, ncol,
matrix_layout_t::L_ROW, set_row_operate(ncol), true);
gettimeofday(&end, NULL);
printf("It takes %.3f seconds to construct input row matrix\n",
time_diff(start, end));
typename type_mem_dense_matrix<Type>::ptr m2
= type_mem_dense_matrix<Type>::create(ncol, right_ncol,
matrix_layout_t::L_COL, set_col_operate(ncol));
typename type_mem_dense_matrix<Type>::ptr res_m
= type_mem_dense_matrix<Type>::create(nrow, right_ncol,
matrix_layout_t::L_ROW);
gettimeofday(&start, NULL);
const mem_row_dense_matrix &row_m
= (const mem_row_dense_matrix &) m1->get_matrix();
const mem_col_dense_matrix &col_m
= (const mem_col_dense_matrix &) m2->get_matrix();
const mem_row_dense_matrix &res_row_m
= (const mem_row_dense_matrix &) res_m->get_matrix();
#pragma omp parallel for
for (size_t i = 0; i < nrow; i++) {
const Type *in_row = (const Type *) row_m.get_row(i);
Type *out_row = (Type *) res_row_m.get_row(i);
for (size_t j = 0; j < right_ncol; j++) {
const Type *in_col = (const Type *) col_m.get_col(j);
out_row[j] = 0;
for (size_t k = 0; k < ncol; k++)
out_row[j] += in_row[k] * in_col[k];
}
}
gettimeofday(&end, NULL);
printf("It takes %.3f seconds to multiply row matrix in parallel\n",
time_diff(start, end));
return res_m;
}
/*
* This multiplies a large column-wise matrix with a small column-wise matrix
* directly. So this implementation potentially generates many CPU cache misses.
*/
template<class Type>
typename type_mem_dense_matrix<Type>::ptr test_MM3(size_t nrow, size_t ncol,
size_t right_ncol)
{
struct timeval start, end;
printf("test tall col-wise matrix (bad impl): M(%ld x %ld) * M(%ld %ld)\n",
nrow, ncol, ncol, right_ncol);
gettimeofday(&start, NULL);
typename type_mem_dense_matrix<Type>::ptr m1
= type_mem_dense_matrix<Type>::create(nrow, ncol,
matrix_layout_t::L_COL, set_col_operate(ncol), true);
gettimeofday(&end, NULL);
printf("It takes %.3f seconds to construct input column matrix\n",
time_diff(start, end));
typename type_mem_dense_matrix<Type>::ptr m2
= type_mem_dense_matrix<Type>::create(ncol, right_ncol,
matrix_layout_t::L_COL, set_col_operate(ncol));
typename type_mem_dense_matrix<Type>::ptr res_m
= type_mem_dense_matrix<Type>::create(nrow, right_ncol,
matrix_layout_t::L_COL);
gettimeofday(&start, NULL);
const mem_col_dense_matrix &left_m
= (const mem_col_dense_matrix &) m1->get_matrix();
const mem_col_dense_matrix &right_m
= (const mem_col_dense_matrix &) m2->get_matrix();
const mem_col_dense_matrix &res_col_m
= (const mem_col_dense_matrix &) res_m->get_matrix();
#pragma omp parallel for
for (size_t i = 0; i < nrow; i++) {
for (size_t j = 0; j < right_ncol; j++) {
const Type *right_col = (const Type *) right_m.get_col(j);
Type *out_col = (Type *) res_col_m.get_col(j);
out_col[i] = 0;
for (size_t k = 0; k < ncol; k++) {
const Type *left_col = (const Type *) left_m.get_col(k);
out_col[i] += left_col[i] * right_col[k];
}
}
}
gettimeofday(&end, NULL);
printf("It takes %.3f seconds to multiply column matrix in parallel\n",
time_diff(start, end));
return res_m;
}
template<class Type>
void check_result(typename type_mem_dense_matrix<Type>::ptr m1,
typename type_mem_dense_matrix<Type>::ptr m2)
{
assert(m1->get_num_rows() == m2->get_num_rows());
assert(m1->get_num_cols() == m2->get_num_cols());
#pragma omp parallel for
for (size_t i = 0; i < m1->get_num_rows(); i++) {
for (size_t j = 0; j < m1->get_num_cols(); j++) {
assert(m1->get(i, j) == m2->get(i, j));
}
}
}
void matrix_mul_tests()
{
size_t nrow = 1024 * 1024 * 124;
size_t ncol = 20;
printf("Multiplication of a large and tall matrix and a small square matrix\n");
test_eigen<double>(nrow, ncol, ncol);
D_mem_dense_matrix::ptr res1 = test_MM1<double>(nrow, ncol, ncol);
D_mem_dense_matrix::ptr res2 = test_MM2<double>(nrow, ncol, ncol);
check_result<double>(res1, res2);
res2 = test_MM3<double>(nrow, ncol, ncol);
check_result<double>(res1, res2);
}
int main()
{
matrix_mul_tests();
}
<|endoftext|> |
<commit_before>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include <exception>
#include <iomanip>
#include <iostream>
#include <list>
#include <memory>
#include <random>
#include "ngraph/descriptor/layout/tensor_layout.hpp"
#include "ngraph/file_util.hpp"
#include "ngraph/log.hpp"
#include "ngraph/runtime/backend.hpp"
#include "ngraph/runtime/tensor.hpp"
#include "ngraph/serializer.hpp"
namespace ngraph
{
class Node;
class Function;
}
bool validate_list(const std::list<std::shared_ptr<ngraph::Node>>& nodes);
std::shared_ptr<ngraph::Function> make_test_graph();
std::shared_ptr<ngraph::Function> make_function_from_file(const std::string& file_name);
template <typename T>
void copy_data(std::shared_ptr<ngraph::runtime::Tensor> tv, const std::vector<T>& data)
{
size_t data_size = data.size() * sizeof(T);
tv->write(data.data(), 0, data_size);
}
template <typename T>
std::vector<T> read_vector(std::shared_ptr<ngraph::runtime::Tensor> tv)
{
if (ngraph::element::from<T>() != tv->get_tensor_layout()->get_element_type())
{
throw std::invalid_argument("read_vector type must match Tensor type");
}
size_t element_count = ngraph::shape_size(tv->get_shape());
size_t size = element_count * sizeof(T);
std::vector<T> rc(element_count);
tv->read(rc.data(), 0, size);
return rc;
}
std::vector<float> read_float_vector(std::shared_ptr<ngraph::runtime::Tensor> tv);
template <typename T>
void write_vector(std::shared_ptr<ngraph::runtime::Tensor> tv, const std::vector<T>& values)
{
tv->write(values.data(), 0, values.size() * sizeof(T));
}
template <typename T>
std::vector<std::shared_ptr<T>> get_ops_of_type(std::shared_ptr<ngraph::Function> f)
{
std::vector<std::shared_ptr<T>> ops;
for (auto op : f->get_ops())
{
if (auto cop = std::dynamic_pointer_cast<T>(op))
{
ops.push_back(cop);
}
}
return ops;
}
template <typename T>
size_t count_ops_of_type(std::shared_ptr<ngraph::Function> f)
{
size_t count = 0;
for (auto op : f->get_ops())
{
if (std::dynamic_pointer_cast<T>(op))
{
count++;
}
}
return count;
}
template <typename T>
void init_int_tv(ngraph::runtime::Tensor* tv, std::default_random_engine& engine, T min, T max)
{
size_t size = tv->get_element_count();
std::uniform_int_distribution<T> dist(min, max);
std::vector<T> vec(size);
for (T& element : vec)
{
element = dist(engine);
}
tv->write(vec.data(), 0, vec.size() * sizeof(T));
}
template <typename T>
void init_real_tv(ngraph::runtime::Tensor* tv, std::default_random_engine& engine, T min, T max)
{
size_t size = tv->get_element_count();
std::uniform_real_distribution<T> dist(min, max);
std::vector<T> vec(size);
for (T& element : vec)
{
element = dist(engine);
}
tv->write(vec.data(), 0, vec.size() * sizeof(T));
}
void random_init(ngraph::runtime::Tensor* tv, std::default_random_engine& engine);
template <typename T>
std::vector<std::shared_ptr<ngraph::runtime::Tensor>>
prepare_and_run(const std::shared_ptr<ngraph::Function>& function,
std::vector<std::vector<T>> args,
const std::string& backend_id)
{
auto backend = ngraph::runtime::Backend::create(backend_id);
auto parms = function->get_parameters();
if (parms.size() != args.size())
{
throw ngraph::ngraph_error("number of parameters and arguments don't match");
}
std::vector<std::shared_ptr<ngraph::runtime::Tensor>> arg_tensors(args.size());
for (size_t i = 0; i < args.size(); i++)
{
auto t = backend->create_tensor(parms.at(i)->get_element_type(), parms.at(i)->get_shape());
copy_data(t, args.at(i));
arg_tensors.at(i) = t;
}
auto results = function->get_results();
std::vector<std::shared_ptr<ngraph::runtime::Tensor>> result_tensors(results.size());
for (size_t i = 0; i < results.size(); i++)
{
result_tensors.at(i) =
backend->create_tensor(results.at(i)->get_element_type(), results.at(i)->get_shape());
}
auto handle = backend->compile(function);
backend->call_with_validate(handle, result_tensors, arg_tensors);
return result_tensors;
}
template <typename T, typename T1 = T>
std::vector<std::vector<T1>> execute(const std::shared_ptr<ngraph::Function>& function,
std::vector<std::vector<T>> args,
const std::string& backend_id)
{
std::vector<std::shared_ptr<ngraph::runtime::Tensor>> result_tensors =
prepare_and_run(function, args, backend_id);
std::vector<std::vector<T1>> result_vectors;
for (auto rt : result_tensors)
{
result_vectors.push_back(read_vector<T1>(rt));
}
return result_vectors;
}
template <typename T>
std::string
get_results_str(std::vector<T>& ref_data, std::vector<T>& actual_data, size_t max_results = 16)
{
std::stringstream ss;
size_t num_results = std::min(static_cast<size_t>(max_results), ref_data.size());
ss << "First " << num_results << " results";
for (size_t i = 0; i < num_results; ++i)
{
ss << "\n"
<< std::setw(4) << i << " ref: " << std::setw(16) << std::left << ref_data[i]
<< " actual: " << std::setw(16) << std::left << actual_data[i];
}
ss << "\n";
return ss.str();
}
template <>
std::string get_results_str(std::vector<char>& ref_data,
std::vector<char>& actual_data,
size_t max_results);
<commit_msg>Utility function for reading binary file content. (#2423)<commit_after>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include <exception>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <list>
#include <memory>
#include <random>
#include <vector>
#include "ngraph/descriptor/layout/tensor_layout.hpp"
#include "ngraph/file_util.hpp"
#include "ngraph/log.hpp"
#include "ngraph/runtime/backend.hpp"
#include "ngraph/runtime/tensor.hpp"
#include "ngraph/serializer.hpp"
namespace ngraph
{
class Node;
class Function;
}
bool validate_list(const std::list<std::shared_ptr<ngraph::Node>>& nodes);
std::shared_ptr<ngraph::Function> make_test_graph();
std::shared_ptr<ngraph::Function> make_function_from_file(const std::string& file_name);
template <typename T>
void copy_data(std::shared_ptr<ngraph::runtime::Tensor> tv, const std::vector<T>& data)
{
size_t data_size = data.size() * sizeof(T);
tv->write(data.data(), 0, data_size);
}
template <typename T>
std::vector<T> read_vector(std::shared_ptr<ngraph::runtime::Tensor> tv)
{
if (ngraph::element::from<T>() != tv->get_tensor_layout()->get_element_type())
{
throw std::invalid_argument("read_vector type must match Tensor type");
}
size_t element_count = ngraph::shape_size(tv->get_shape());
size_t size = element_count * sizeof(T);
std::vector<T> rc(element_count);
tv->read(rc.data(), 0, size);
return rc;
}
std::vector<float> read_float_vector(std::shared_ptr<ngraph::runtime::Tensor> tv);
template <typename T>
void write_vector(std::shared_ptr<ngraph::runtime::Tensor> tv, const std::vector<T>& values)
{
tv->write(values.data(), 0, values.size() * sizeof(T));
}
template <typename T>
std::vector<std::shared_ptr<T>> get_ops_of_type(std::shared_ptr<ngraph::Function> f)
{
std::vector<std::shared_ptr<T>> ops;
for (auto op : f->get_ops())
{
if (auto cop = std::dynamic_pointer_cast<T>(op))
{
ops.push_back(cop);
}
}
return ops;
}
template <typename T>
size_t count_ops_of_type(std::shared_ptr<ngraph::Function> f)
{
size_t count = 0;
for (auto op : f->get_ops())
{
if (std::dynamic_pointer_cast<T>(op))
{
count++;
}
}
return count;
}
template <typename T>
void init_int_tv(ngraph::runtime::Tensor* tv, std::default_random_engine& engine, T min, T max)
{
size_t size = tv->get_element_count();
std::uniform_int_distribution<T> dist(min, max);
std::vector<T> vec(size);
for (T& element : vec)
{
element = dist(engine);
}
tv->write(vec.data(), 0, vec.size() * sizeof(T));
}
template <typename T>
void init_real_tv(ngraph::runtime::Tensor* tv, std::default_random_engine& engine, T min, T max)
{
size_t size = tv->get_element_count();
std::uniform_real_distribution<T> dist(min, max);
std::vector<T> vec(size);
for (T& element : vec)
{
element = dist(engine);
}
tv->write(vec.data(), 0, vec.size() * sizeof(T));
}
void random_init(ngraph::runtime::Tensor* tv, std::default_random_engine& engine);
template <typename T>
std::vector<std::shared_ptr<ngraph::runtime::Tensor>>
prepare_and_run(const std::shared_ptr<ngraph::Function>& function,
std::vector<std::vector<T>> args,
const std::string& backend_id)
{
auto backend = ngraph::runtime::Backend::create(backend_id);
auto parms = function->get_parameters();
if (parms.size() != args.size())
{
throw ngraph::ngraph_error("number of parameters and arguments don't match");
}
std::vector<std::shared_ptr<ngraph::runtime::Tensor>> arg_tensors(args.size());
for (size_t i = 0; i < args.size(); i++)
{
auto t = backend->create_tensor(parms.at(i)->get_element_type(), parms.at(i)->get_shape());
copy_data(t, args.at(i));
arg_tensors.at(i) = t;
}
auto results = function->get_results();
std::vector<std::shared_ptr<ngraph::runtime::Tensor>> result_tensors(results.size());
for (size_t i = 0; i < results.size(); i++)
{
result_tensors.at(i) =
backend->create_tensor(results.at(i)->get_element_type(), results.at(i)->get_shape());
}
auto handle = backend->compile(function);
backend->call_with_validate(handle, result_tensors, arg_tensors);
return result_tensors;
}
template <typename T, typename T1 = T>
std::vector<std::vector<T1>> execute(const std::shared_ptr<ngraph::Function>& function,
std::vector<std::vector<T>> args,
const std::string& backend_id)
{
std::vector<std::shared_ptr<ngraph::runtime::Tensor>> result_tensors =
prepare_and_run(function, args, backend_id);
std::vector<std::vector<T1>> result_vectors;
for (auto rt : result_tensors)
{
result_vectors.push_back(read_vector<T1>(rt));
}
return result_vectors;
}
template <typename T>
std::string
get_results_str(std::vector<T>& ref_data, std::vector<T>& actual_data, size_t max_results = 16)
{
std::stringstream ss;
size_t num_results = std::min(static_cast<size_t>(max_results), ref_data.size());
ss << "First " << num_results << " results";
for (size_t i = 0; i < num_results; ++i)
{
ss << "\n"
<< std::setw(4) << i << " ref: " << std::setw(16) << std::left << ref_data[i]
<< " actual: " << std::setw(16) << std::left << actual_data[i];
}
ss << "\n";
return ss.str();
}
template <>
std::string get_results_str(std::vector<char>& ref_data,
std::vector<char>& actual_data,
size_t max_results);
/// \brief Reads a binary file to a vector.
///
/// \param[in] path The path where the file is located.
///
/// \tparam T The type we want to interpret as the elements in binary file.
///
/// \return Return vector of data read from input binary file.
///
template <typename T>
std::vector<T> read_binary_file(const std::string& path)
{
std::vector<T> file_content;
std::ifstream inputs_fs{path, std::ios::in | std::ios::binary};
if (!inputs_fs)
{
throw std::runtime_error("Failed to open the file: " + path);
}
inputs_fs.seekg(0, std::ios::end);
auto size = inputs_fs.tellg();
inputs_fs.seekg(0, std::ios::beg);
if (size % sizeof(T) != 0)
{
throw std::runtime_error(
"Error reading binary file content: Input file size (in bytes) "
"is not a multiple of requested data type size.");
}
file_content.resize(size / sizeof(T));
inputs_fs.read(reinterpret_cast<char*>(file_content.data()), size);
return file_content;
}
<|endoftext|> |
<commit_before>#include "connected_test.h"
#include <iostream>
using namespace AmqpClient;
TEST_F(connected_test, basic_consume)
{
std::string queue = channel->DeclareQueue("");
std::string consumer = channel->BasicConsume(queue);
}
TEST_F(connected_test, basic_consume_badqueue)
{
EXPECT_THROW(channel->BasicConsume("test_consume_noexistqueue"), ChannelException);
}
TEST_F(connected_test, basic_consume_duplicatetag)
{
std::string queue = channel->DeclareQueue("");
std::string consumer = channel->BasicConsume(queue);
EXPECT_THROW(channel->BasicConsume(queue, consumer), ChannelException);
}
TEST_F(connected_test, basic_cancel_consumer)
{
std::string queue = channel->DeclareQueue("");
std::string consumer = channel->BasicConsume(queue);
channel->BasicCancel(consumer);
}
TEST_F(connected_test, basic_cancel_bad_consumer)
{
EXPECT_THROW(channel->BasicCancel("test_consume_noexistconsumer"), ConsumerTagNotFoundException);
}
TEST_F(connected_test, basic_cancel_cancelled_consumer)
{
std::string queue = channel->DeclareQueue("");
std::string consumer = channel->BasicConsume(queue);
channel->BasicCancel(consumer);
EXPECT_THROW(channel->BasicCancel(consumer), ConsumerTagNotFoundException);
}
TEST_F(connected_test, basic_consume_message)
{
BasicMessage::ptr_t message = BasicMessage::Create("Message Body");
std::string queue = channel->DeclareQueue("");
std::string consumer = channel->BasicConsume(queue);
channel->BasicPublish("", queue, message);
Envelope::ptr_t delivered;
EXPECT_TRUE(channel->BasicConsumeMessage(consumer, delivered, -1));
EXPECT_EQ(consumer, delivered->ConsumerTag());
EXPECT_EQ("", delivered->Exchange());
EXPECT_EQ(queue, delivered->RoutingKey());
EXPECT_EQ(message->Body(), delivered->Message()->Body());
}
TEST_F(connected_test, basic_consume_message_bad_consumer)
{
EXPECT_THROW(channel->BasicConsumeMessage("test_consume_noexistconsumer"), ConsumerTagNotFoundException);
}
TEST_F(connected_test, basic_consume_inital_qos)
{
BasicMessage::ptr_t message1 = BasicMessage::Create("Message1");
BasicMessage::ptr_t message2 = BasicMessage::Create("Message2");
BasicMessage::ptr_t message3 = BasicMessage::Create("Message3");
std::string queue = channel->DeclareQueue("");
channel->BasicPublish("", queue, message1, true);
channel->BasicPublish("", queue, message2, true);
channel->BasicPublish("", queue, message3, true);
std::string consumer = channel->BasicConsume(queue, "", true, false, true, 1);
Envelope::ptr_t received1, received2;
EXPECT_TRUE(channel->BasicConsumeMessage(consumer, received1, 1));
EXPECT_FALSE(channel->BasicConsumeMessage(consumer, received2, 0));
channel->BasicAck(received1);
EXPECT_TRUE(channel->BasicConsumeMessage(consumer, received2, 1));
}
TEST_F(connected_test, basic_consume_2consumers)
{
BasicMessage::ptr_t message1 = BasicMessage::Create("Message1");
BasicMessage::ptr_t message2 = BasicMessage::Create("Message2");
BasicMessage::ptr_t message3 = BasicMessage::Create("Message3");
std::string queue1 = channel->DeclareQueue("");
std::string queue2 = channel->DeclareQueue("");
std::string queue3 = channel->DeclareQueue("");
channel->BasicPublish("", queue1, message1);
channel->BasicPublish("", queue2, message2);
channel->BasicPublish("", queue3, message3);
std::string consumer1 = channel->BasicConsume(queue1, "", true, false);
std::string consumer2 = channel->BasicConsume(queue2, "", true, false);
Envelope::ptr_t envelope1;
Envelope::ptr_t envelope2;
Envelope::ptr_t envelope3;
channel->BasicConsumeMessage(consumer1, envelope1);
channel->BasicAck(envelope1);
channel->BasicConsumeMessage(consumer2, envelope2);
channel->BasicAck(envelope2);
channel->BasicGet(envelope3, queue3);
channel->BasicAck(envelope3);
}
TEST_F(connected_test, basic_consume_1000messages)
{
BasicMessage::ptr_t message1 = BasicMessage::Create("Message1");
std::string queue = channel->DeclareQueue("");
std::string consumer = channel->BasicConsume(queue, "");
Envelope::ptr_t msg;
for (int i = 0; i < 1000; ++i)
{
message1->Timestamp(i);
channel->BasicPublish("", queue, message1, true);
channel->BasicConsumeMessage(consumer, msg);
}
}<commit_msg>Adding basic.qos and basic.recover test cases<commit_after>#include "connected_test.h"
#include <iostream>
using namespace AmqpClient;
TEST_F(connected_test, basic_consume)
{
std::string queue = channel->DeclareQueue("");
std::string consumer = channel->BasicConsume(queue);
}
TEST_F(connected_test, basic_consume_badqueue)
{
EXPECT_THROW(channel->BasicConsume("test_consume_noexistqueue"), ChannelException);
}
TEST_F(connected_test, basic_consume_duplicatetag)
{
std::string queue = channel->DeclareQueue("");
std::string consumer = channel->BasicConsume(queue);
EXPECT_THROW(channel->BasicConsume(queue, consumer), ChannelException);
}
TEST_F(connected_test, basic_cancel_consumer)
{
std::string queue = channel->DeclareQueue("");
std::string consumer = channel->BasicConsume(queue);
channel->BasicCancel(consumer);
}
TEST_F(connected_test, basic_cancel_bad_consumer)
{
EXPECT_THROW(channel->BasicCancel("test_consume_noexistconsumer"), ConsumerTagNotFoundException);
}
TEST_F(connected_test, basic_cancel_cancelled_consumer)
{
std::string queue = channel->DeclareQueue("");
std::string consumer = channel->BasicConsume(queue);
channel->BasicCancel(consumer);
EXPECT_THROW(channel->BasicCancel(consumer), ConsumerTagNotFoundException);
}
TEST_F(connected_test, basic_consume_message)
{
BasicMessage::ptr_t message = BasicMessage::Create("Message Body");
std::string queue = channel->DeclareQueue("");
std::string consumer = channel->BasicConsume(queue);
channel->BasicPublish("", queue, message);
Envelope::ptr_t delivered;
EXPECT_TRUE(channel->BasicConsumeMessage(consumer, delivered, -1));
EXPECT_EQ(consumer, delivered->ConsumerTag());
EXPECT_EQ("", delivered->Exchange());
EXPECT_EQ(queue, delivered->RoutingKey());
EXPECT_EQ(message->Body(), delivered->Message()->Body());
}
TEST_F(connected_test, basic_consume_message_bad_consumer)
{
EXPECT_THROW(channel->BasicConsumeMessage("test_consume_noexistconsumer"), ConsumerTagNotFoundException);
}
TEST_F(connected_test, basic_consume_inital_qos)
{
BasicMessage::ptr_t message1 = BasicMessage::Create("Message1");
BasicMessage::ptr_t message2 = BasicMessage::Create("Message2");
BasicMessage::ptr_t message3 = BasicMessage::Create("Message3");
std::string queue = channel->DeclareQueue("");
channel->BasicPublish("", queue, message1, true);
channel->BasicPublish("", queue, message2, true);
channel->BasicPublish("", queue, message3, true);
std::string consumer = channel->BasicConsume(queue, "", true, false, true, 1);
Envelope::ptr_t received1, received2;
EXPECT_TRUE(channel->BasicConsumeMessage(consumer, received1, 1));
EXPECT_FALSE(channel->BasicConsumeMessage(consumer, received2, 0));
channel->BasicAck(received1);
EXPECT_TRUE(channel->BasicConsumeMessage(consumer, received2, 1));
}
TEST_F(connected_test, basic_consume_2consumers)
{
BasicMessage::ptr_t message1 = BasicMessage::Create("Message1");
BasicMessage::ptr_t message2 = BasicMessage::Create("Message2");
BasicMessage::ptr_t message3 = BasicMessage::Create("Message3");
std::string queue1 = channel->DeclareQueue("");
std::string queue2 = channel->DeclareQueue("");
std::string queue3 = channel->DeclareQueue("");
channel->BasicPublish("", queue1, message1);
channel->BasicPublish("", queue2, message2);
channel->BasicPublish("", queue3, message3);
std::string consumer1 = channel->BasicConsume(queue1, "", true, false);
std::string consumer2 = channel->BasicConsume(queue2, "", true, false);
Envelope::ptr_t envelope1;
Envelope::ptr_t envelope2;
Envelope::ptr_t envelope3;
channel->BasicConsumeMessage(consumer1, envelope1);
channel->BasicAck(envelope1);
channel->BasicConsumeMessage(consumer2, envelope2);
channel->BasicAck(envelope2);
channel->BasicGet(envelope3, queue3);
channel->BasicAck(envelope3);
}
TEST_F(connected_test, basic_consume_1000messages)
{
BasicMessage::ptr_t message1 = BasicMessage::Create("Message1");
std::string queue = channel->DeclareQueue("");
std::string consumer = channel->BasicConsume(queue, "");
Envelope::ptr_t msg;
for (int i = 0; i < 1000; ++i)
{
message1->Timestamp(i);
channel->BasicPublish("", queue, message1, true);
channel->BasicConsumeMessage(consumer, msg);
}
}
TEST_F(connected_test, basic_recover)
{
BasicMessage::ptr_t message = BasicMessage::Create("Message1");
std::string queue = channel->DeclareQueue("");
std::string consumer = channel->BasicConsume(queue, "", true, false);
channel->BasicPublish("", queue, message);
Envelope::ptr_t message1;
Envelope::ptr_t message2;
EXPECT_TRUE(channel->BasicConsumeMessage(consumer, message1));
channel->BasicRecover(consumer);
EXPECT_TRUE(channel->BasicConsumeMessage(consumer, message2));
channel->DeleteQueue(queue);
}
TEST_F(connected_test, basic_recover_badconsumer)
{
EXPECT_THROW(channel->BasicRecover("consumer_notexist"), ConsumerTagNotFoundException);
}
TEST_F(connected_test, basic_qos)
{
std::string queue = channel->DeclareQueue("");
std::string consumer = channel->BasicConsume(queue, "", true, false);
channel->BasicPublish("", queue, BasicMessage::Create("Message1"));
channel->BasicPublish("", queue, BasicMessage::Create("Message2"));
Envelope::ptr_t incoming;
EXPECT_TRUE(channel->BasicConsumeMessage(consumer, incoming, 1));
EXPECT_FALSE(channel->BasicConsumeMessage(consumer, incoming, 1));
channel->BasicQos(consumer, 2);
EXPECT_TRUE(channel->BasicConsumeMessage(consumer, incoming, 1));
channel->DeleteQueue(queue);
}
TEST_F(connected_test, basic_qos_badconsumer)
{
EXPECT_THROW(channel->BasicQos("consumer_notexist", 1), ConsumerTagNotFoundException);
}<|endoftext|> |
<commit_before>// Copyright 2015 PDFium 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 "testing/test_support.h"
#include <stdio.h>
#include <string.h>
#include <string>
#include "testing/utils/path_service.h"
#ifdef PDF_ENABLE_V8
#include "v8/include/libplatform/libplatform.h"
#endif
namespace {
#ifdef PDF_ENABLE_V8
#ifdef V8_USE_EXTERNAL_STARTUP_DATA
// Returns the full path for an external V8 data file based on either
// the currect exectuable path or an explicit override.
std::string GetFullPathForSnapshotFile(const std::string& exe_path,
const std::string& bin_dir,
const std::string& filename) {
std::string result;
if (!bin_dir.empty()) {
result = bin_dir;
if (*bin_dir.rbegin() != PATH_SEPARATOR) {
result += PATH_SEPARATOR;
}
} else if (!exe_path.empty()) {
size_t last_separator = exe_path.rfind(PATH_SEPARATOR);
if (last_separator != std::string::npos) {
result = exe_path.substr(0, last_separator + 1);
}
}
result += filename;
return result;
}
bool GetExternalData(const std::string& exe_path,
const std::string& bin_dir,
const std::string& filename,
v8::StartupData* result_data) {
std::string full_path =
GetFullPathForSnapshotFile(exe_path, bin_dir, filename);
size_t data_length = 0;
std::unique_ptr<char, pdfium::FreeDeleter> data_buffer =
GetFileContents(full_path.c_str(), &data_length);
if (!data_buffer)
return false;
result_data->data = data_buffer.release();
result_data->raw_size = data_length;
return true;
}
#endif // V8_USE_EXTERNAL_STARTUP_DATA
void InitializeV8Common(const char* exe_path, v8::Platform** platform) {
v8::V8::InitializeICUDefaultLocation(exe_path);
*platform = v8::platform::CreateDefaultPlatform();
v8::V8::InitializePlatform(*platform);
v8::V8::Initialize();
// By enabling predictable mode, V8 won't post any background tasks.
const char predictable_flag[] = "--predictable";
v8::V8::SetFlagsFromString(predictable_flag,
static_cast<int>(strlen(predictable_flag)));
}
#endif // PDF_ENABLE_V8
} // namespace
std::unique_ptr<char, pdfium::FreeDeleter> GetFileContents(const char* filename,
size_t* retlen) {
FILE* file = fopen(filename, "rb");
if (!file) {
fprintf(stderr, "Failed to open: %s\n", filename);
return nullptr;
}
(void)fseek(file, 0, SEEK_END);
size_t file_length = ftell(file);
if (!file_length) {
return nullptr;
}
(void)fseek(file, 0, SEEK_SET);
std::unique_ptr<char, pdfium::FreeDeleter> buffer(
static_cast<char*>(malloc(file_length)));
if (!buffer) {
return nullptr;
}
size_t bytes_read = fread(buffer.get(), 1, file_length, file);
(void)fclose(file);
if (bytes_read != file_length) {
fprintf(stderr, "Failed to read: %s\n", filename);
return nullptr;
}
*retlen = bytes_read;
return buffer;
}
std::wstring GetPlatformWString(FPDF_WIDESTRING wstr) {
if (!wstr)
return nullptr;
size_t characters = 0;
while (wstr[characters])
++characters;
std::wstring platform_string(characters, L'\0');
for (size_t i = 0; i < characters + 1; ++i) {
const unsigned char* ptr = reinterpret_cast<const unsigned char*>(&wstr[i]);
platform_string[i] = ptr[0] + 256 * ptr[1];
}
return platform_string;
}
std::vector<std::string> StringSplit(const std::string& str, char delimiter) {
std::vector<std::string> result;
size_t pos = 0;
while (1) {
size_t found = str.find(delimiter, pos);
if (found == std::string::npos)
break;
result.push_back(str.substr(pos, found - pos));
pos = found + 1;
}
result.push_back(str.substr(pos));
return result;
}
std::unique_ptr<unsigned short, pdfium::FreeDeleter> GetFPDFWideString(
const std::wstring& wstr) {
size_t length = sizeof(uint16_t) * (wstr.length() + 1);
std::unique_ptr<unsigned short, pdfium::FreeDeleter> result(
static_cast<unsigned short*>(malloc(length)));
char* ptr = reinterpret_cast<char*>(result.get());
size_t i = 0;
for (wchar_t w : wstr) {
ptr[i++] = w & 0xff;
ptr[i++] = (w >> 8) & 0xff;
}
ptr[i++] = 0;
ptr[i] = 0;
return result;
}
#ifdef PDF_ENABLE_V8
#ifdef V8_USE_EXTERNAL_STARTUP_DATA
bool InitializeV8ForPDFium(const std::string& exe_path,
const std::string& bin_dir,
v8::StartupData* natives_blob,
v8::StartupData* snapshot_blob,
v8::Platform** platform) {
InitializeV8Common(exe_path.c_str(), platform);
if (natives_blob && snapshot_blob) {
if (!GetExternalData(exe_path, bin_dir, "natives_blob.bin", natives_blob))
return false;
if (!GetExternalData(exe_path, bin_dir, "snapshot_blob.bin", snapshot_blob))
return false;
v8::V8::SetNativesDataBlob(natives_blob);
v8::V8::SetSnapshotDataBlob(snapshot_blob);
}
return true;
}
#else // V8_USE_EXTERNAL_STARTUP_DATA
bool InitializeV8ForPDFium(const std::string& exe_path,
v8::Platform** platform) {
InitializeV8Common(exe_path.c_str(), platform);
return true;
}
#endif // V8_USE_EXTERNAL_STARTUP_DATA
#endif // PDF_ENABLE_V8
TestLoader::TestLoader(const char* pBuf, size_t len)
: m_pBuf(pBuf), m_Len(len) {
}
// static
int TestLoader::GetBlock(void* param,
unsigned long pos,
unsigned char* pBuf,
unsigned long size) {
TestLoader* pLoader = static_cast<TestLoader*>(param);
if (pos + size < pos || pos + size > pLoader->m_Len)
return 0;
memcpy(pBuf, pLoader->m_pBuf + pos, size);
return 1;
}
TestSaver::TestSaver() {
FPDF_FILEWRITE::version = 1;
FPDF_FILEWRITE::WriteBlock = WriteBlockCallback;
}
void TestSaver::ClearString() {
m_String.clear();
}
// static
int TestSaver::WriteBlockCallback(FPDF_FILEWRITE* pFileWrite,
const void* data,
unsigned long size) {
TestSaver* pThis = static_cast<TestSaver*>(pFileWrite);
pThis->m_String.append(static_cast<const char*>(data), size);
return 1;
}
<commit_msg>Pass expose-gc flag to pdfium test programs.<commit_after>// Copyright 2015 PDFium 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 "testing/test_support.h"
#include <stdio.h>
#include <string.h>
#include <string>
#include "testing/utils/path_service.h"
#ifdef PDF_ENABLE_V8
#include "v8/include/libplatform/libplatform.h"
#endif
namespace {
#ifdef PDF_ENABLE_V8
#ifdef V8_USE_EXTERNAL_STARTUP_DATA
// Returns the full path for an external V8 data file based on either
// the currect exectuable path or an explicit override.
std::string GetFullPathForSnapshotFile(const std::string& exe_path,
const std::string& bin_dir,
const std::string& filename) {
std::string result;
if (!bin_dir.empty()) {
result = bin_dir;
if (*bin_dir.rbegin() != PATH_SEPARATOR) {
result += PATH_SEPARATOR;
}
} else if (!exe_path.empty()) {
size_t last_separator = exe_path.rfind(PATH_SEPARATOR);
if (last_separator != std::string::npos) {
result = exe_path.substr(0, last_separator + 1);
}
}
result += filename;
return result;
}
bool GetExternalData(const std::string& exe_path,
const std::string& bin_dir,
const std::string& filename,
v8::StartupData* result_data) {
std::string full_path =
GetFullPathForSnapshotFile(exe_path, bin_dir, filename);
size_t data_length = 0;
std::unique_ptr<char, pdfium::FreeDeleter> data_buffer =
GetFileContents(full_path.c_str(), &data_length);
if (!data_buffer)
return false;
result_data->data = data_buffer.release();
result_data->raw_size = data_length;
return true;
}
#endif // V8_USE_EXTERNAL_STARTUP_DATA
void InitializeV8Common(const char* exe_path, v8::Platform** platform) {
v8::V8::InitializeICUDefaultLocation(exe_path);
*platform = v8::platform::CreateDefaultPlatform();
v8::V8::InitializePlatform(*platform);
// By enabling predictable mode, V8 won't post any background tasks.
// By enabling GC, it makes it easier to chase use-after-free.
const char v8_flags[] = "--predictable --expose-gc";
v8::V8::SetFlagsFromString(v8_flags, static_cast<int>(strlen(v8_flags)));
v8::V8::Initialize();
}
#endif // PDF_ENABLE_V8
} // namespace
std::unique_ptr<char, pdfium::FreeDeleter> GetFileContents(const char* filename,
size_t* retlen) {
FILE* file = fopen(filename, "rb");
if (!file) {
fprintf(stderr, "Failed to open: %s\n", filename);
return nullptr;
}
(void)fseek(file, 0, SEEK_END);
size_t file_length = ftell(file);
if (!file_length) {
return nullptr;
}
(void)fseek(file, 0, SEEK_SET);
std::unique_ptr<char, pdfium::FreeDeleter> buffer(
static_cast<char*>(malloc(file_length)));
if (!buffer) {
return nullptr;
}
size_t bytes_read = fread(buffer.get(), 1, file_length, file);
(void)fclose(file);
if (bytes_read != file_length) {
fprintf(stderr, "Failed to read: %s\n", filename);
return nullptr;
}
*retlen = bytes_read;
return buffer;
}
std::wstring GetPlatformWString(FPDF_WIDESTRING wstr) {
if (!wstr)
return nullptr;
size_t characters = 0;
while (wstr[characters])
++characters;
std::wstring platform_string(characters, L'\0');
for (size_t i = 0; i < characters + 1; ++i) {
const unsigned char* ptr = reinterpret_cast<const unsigned char*>(&wstr[i]);
platform_string[i] = ptr[0] + 256 * ptr[1];
}
return platform_string;
}
std::vector<std::string> StringSplit(const std::string& str, char delimiter) {
std::vector<std::string> result;
size_t pos = 0;
while (1) {
size_t found = str.find(delimiter, pos);
if (found == std::string::npos)
break;
result.push_back(str.substr(pos, found - pos));
pos = found + 1;
}
result.push_back(str.substr(pos));
return result;
}
std::unique_ptr<unsigned short, pdfium::FreeDeleter> GetFPDFWideString(
const std::wstring& wstr) {
size_t length = sizeof(uint16_t) * (wstr.length() + 1);
std::unique_ptr<unsigned short, pdfium::FreeDeleter> result(
static_cast<unsigned short*>(malloc(length)));
char* ptr = reinterpret_cast<char*>(result.get());
size_t i = 0;
for (wchar_t w : wstr) {
ptr[i++] = w & 0xff;
ptr[i++] = (w >> 8) & 0xff;
}
ptr[i++] = 0;
ptr[i] = 0;
return result;
}
#ifdef PDF_ENABLE_V8
#ifdef V8_USE_EXTERNAL_STARTUP_DATA
bool InitializeV8ForPDFium(const std::string& exe_path,
const std::string& bin_dir,
v8::StartupData* natives_blob,
v8::StartupData* snapshot_blob,
v8::Platform** platform) {
InitializeV8Common(exe_path.c_str(), platform);
if (natives_blob && snapshot_blob) {
if (!GetExternalData(exe_path, bin_dir, "natives_blob.bin", natives_blob))
return false;
if (!GetExternalData(exe_path, bin_dir, "snapshot_blob.bin", snapshot_blob))
return false;
v8::V8::SetNativesDataBlob(natives_blob);
v8::V8::SetSnapshotDataBlob(snapshot_blob);
}
return true;
}
#else // V8_USE_EXTERNAL_STARTUP_DATA
bool InitializeV8ForPDFium(const std::string& exe_path,
v8::Platform** platform) {
InitializeV8Common(exe_path.c_str(), platform);
return true;
}
#endif // V8_USE_EXTERNAL_STARTUP_DATA
#endif // PDF_ENABLE_V8
TestLoader::TestLoader(const char* pBuf, size_t len)
: m_pBuf(pBuf), m_Len(len) {
}
// static
int TestLoader::GetBlock(void* param,
unsigned long pos,
unsigned char* pBuf,
unsigned long size) {
TestLoader* pLoader = static_cast<TestLoader*>(param);
if (pos + size < pos || pos + size > pLoader->m_Len)
return 0;
memcpy(pBuf, pLoader->m_pBuf + pos, size);
return 1;
}
TestSaver::TestSaver() {
FPDF_FILEWRITE::version = 1;
FPDF_FILEWRITE::WriteBlock = WriteBlockCallback;
}
void TestSaver::ClearString() {
m_String.clear();
}
// static
int TestSaver::WriteBlockCallback(FPDF_FILEWRITE* pFileWrite,
const void* data,
unsigned long size) {
TestSaver* pThis = static_cast<TestSaver*>(pFileWrite);
pThis->m_String.append(static_cast<const char*>(data), size);
return 1;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2020 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkCanvas.h"
#include "include/core/SkSurface.h"
#include "include/core/SkTextBlob.h"
#include "src/core/SkSurfacePriv.h"
#include "tests/Test.h"
#include "tools/ToolUtils.h"
SkBitmap rasterize_blob(SkTextBlob* blob,
const SkPaint& paint,
GrRecordingContext* rContext,
const SkMatrix& matrix) {
const SkImageInfo info =
SkImageInfo::Make(500, 500, kN32_SkColorType, kPremul_SkAlphaType);
auto surface = SkSurface::MakeRenderTarget(rContext, SkBudgeted::kNo, info);
auto canvas = surface->getCanvas();
canvas->drawColor(SK_ColorWHITE);
canvas->concat(matrix);
canvas->drawTextBlob(blob, 10, 250, paint);
SkBitmap bitmap;
bitmap.allocN32Pixels(500, 500);
surface->readPixels(bitmap, 0, 0);
return bitmap;
}
bool check_for_black(const SkBitmap& bm) {
for (int y = 0; y < bm.height(); y++) {
for (int x = 0; x < bm.width(); x++) {
if (bm.getColor(x, y) == SK_ColorBLACK) {
return true;
}
}
}
return false;
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrTextBlobScaleAnimation, reporter, ctxInfo) {
auto tf = ToolUtils::create_portable_typeface("Mono", SkFontStyle());
SkFont font{tf};
font.setHinting(SkFontHinting::kNormal);
font.setSize(12);
font.setEdging(SkFont::Edging::kAntiAlias);
font.setSubpixel(true);
SkTextBlobBuilder builder;
const auto& runBuffer = builder.allocRunPosH(font, 30, 0, nullptr);
for (int i = 0; i < 30; i++) {
runBuffer.glyphs[i] = static_cast<SkGlyphID>(i);
runBuffer.pos[i] = SkIntToScalar(i);
}
auto blob = builder.make();
auto dContext = ctxInfo.directContext();
bool anyBlack = false;
for (int n = -13; n < 5; n++) {
SkMatrix m = SkMatrix::Scale(std::exp2(n), std::exp2(n));
auto bm = rasterize_blob(blob.get(), SkPaint(), dContext, m);
anyBlack |= check_for_black(bm);
}
REPORTER_ASSERT(reporter, anyBlack);
}
<commit_msg>test for extents of SkTextBlob drawing<commit_after>/*
* Copyright 2020 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkCanvas.h"
#include "include/core/SkSurface.h"
#include "include/core/SkTextBlob.h"
#include "src/core/SkSurfacePriv.h"
#include "tests/Test.h"
#include "tools/ToolUtils.h"
SkBitmap rasterize_blob(SkTextBlob* blob,
const SkPaint& paint,
GrRecordingContext* rContext,
const SkMatrix& matrix) {
const SkImageInfo info =
SkImageInfo::Make(500, 500, kN32_SkColorType, kPremul_SkAlphaType);
auto surface = SkSurface::MakeRenderTarget(rContext, SkBudgeted::kNo, info);
auto canvas = surface->getCanvas();
canvas->drawColor(SK_ColorWHITE);
canvas->concat(matrix);
canvas->drawTextBlob(blob, 10, 250, paint);
SkBitmap bitmap;
bitmap.allocN32Pixels(500, 500);
surface->readPixels(bitmap, 0, 0);
return bitmap;
}
bool check_for_black(const SkBitmap& bm) {
for (int y = 0; y < bm.height(); y++) {
for (int x = 0; x < bm.width(); x++) {
if (bm.getColor(x, y) == SK_ColorBLACK) {
return true;
}
}
}
return false;
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrTextBlobScaleAnimation, reporter, ctxInfo) {
auto tf = ToolUtils::create_portable_typeface("Mono", SkFontStyle());
SkFont font{tf};
font.setHinting(SkFontHinting::kNormal);
font.setSize(12);
font.setEdging(SkFont::Edging::kAntiAlias);
font.setSubpixel(true);
SkTextBlobBuilder builder;
const auto& runBuffer = builder.allocRunPosH(font, 30, 0, nullptr);
for (int i = 0; i < 30; i++) {
runBuffer.glyphs[i] = static_cast<SkGlyphID>(i);
runBuffer.pos[i] = SkIntToScalar(i);
}
auto blob = builder.make();
auto dContext = ctxInfo.directContext();
bool anyBlack = false;
for (int n = -13; n < 5; n++) {
SkMatrix m = SkMatrix::Scale(std::exp2(n), std::exp2(n));
auto bm = rasterize_blob(blob.get(), SkPaint(), dContext, m);
anyBlack |= check_for_black(bm);
}
REPORTER_ASSERT(reporter, anyBlack);
}
// Test extreme positions for all combinations of positions, origins, and translation matrices.
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrTextBlobMoveAround, reporter, ctxInfo) {
auto tf = ToolUtils::create_portable_typeface("Mono", SkFontStyle());
SkFont font{tf};
font.setHinting(SkFontHinting::kNormal);
font.setSize(12);
font.setEdging(SkFont::Edging::kAntiAlias);
font.setSubpixel(true);
auto makeBlob = [&](SkPoint delta) {
SkTextBlobBuilder builder;
const auto& runBuffer = builder.allocRunPos(font, 30, nullptr);
for (int i = 0; i < 30; i++) {
runBuffer.glyphs[i] = static_cast<SkGlyphID>(i);
runBuffer.points()[i] = SkPoint::Make(SkIntToScalar(i*10) + delta.x(), 50 + delta.y());
}
return builder.make();
};
auto dContext = ctxInfo.directContext();
auto rasterizeBlob = [&](SkTextBlob* blob, SkPoint origin, const SkMatrix& matrix) {
SkPaint paint;
const SkImageInfo info =
SkImageInfo::Make(350, 80, kN32_SkColorType, kPremul_SkAlphaType);
auto surface = SkSurface::MakeRenderTarget(dContext, SkBudgeted::kNo, info);
auto canvas = surface->getCanvas();
canvas->drawColor(SK_ColorWHITE);
canvas->concat(matrix);
canvas->drawTextBlob(blob, 10 + origin.x(), 40 + origin.y(), paint);
SkBitmap bitmap;
bitmap.allocN32Pixels(350, 80);
surface->readPixels(bitmap, 0, 0);
return bitmap;
};
SkBitmap benchMark;
{
auto blob = makeBlob({0, 0});
benchMark = rasterizeBlob(blob.get(), {0,0}, SkMatrix::I());
}
auto checkBitmap = [&](const SkBitmap& bitmap) {
REPORTER_ASSERT(reporter, benchMark.width() == bitmap.width());
REPORTER_ASSERT(reporter, benchMark.width() == bitmap.width());
for (int y = 0; y < benchMark.height(); y++) {
for (int x = 0; x < benchMark.width(); x++) {
if (benchMark.getColor(x, y) != bitmap.getColor(x, y)) {
return false;
}
}
}
return true;
};
SkScalar interestingNumbers[] = {-10'000'000, -1'000'000, -1, 0, +1, +1'000'000, +10'000'000};
for (auto originX : interestingNumbers) {
for (auto originY : interestingNumbers) {
for (auto translateX : interestingNumbers) {
for (auto translateY : interestingNumbers) {
// Make sure everything adds to zero.
SkScalar deltaPosX = -(originX + translateX);
SkScalar deltaPosY = -(originY + translateY);
auto blob = makeBlob({deltaPosX, deltaPosY});
SkMatrix t = SkMatrix::Translate(translateX, translateY);
auto bitmap = rasterizeBlob(blob.get(), {originX, originY}, t);
REPORTER_ASSERT(reporter, checkBitmap(bitmap));
}
}
}
}
}
<|endoftext|> |
<commit_before><commit_msg>fix for root 6.24<commit_after><|endoftext|> |
<commit_before>/***********************************************************************
* filename: InputInjection.cpp
* created: 21/5/2013
* author: Timotei Dolean
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 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 <boost/test/unit_test.hpp>
#include <vector>
#include <iostream>
#include "CEGUI/CEGUI.h"
using namespace CEGUI;
struct InputInjectionFixture
{
InputInjectionFixture()
: d_buttonHandledCount(0)
, d_windowHandledCount(0)
{
System::getSingleton().notifyDisplaySizeChanged(Sizef(100, 100));
Rectf constraint_area(0, 0, 100, 100);
System::getSingleton().getDefaultGUIContext().getMouseCursor().setConstraintArea(&constraint_area);
d_window = WindowManager::getSingleton().createWindow("DefaultWindow");
d_window->setPosition(UVector2(cegui_reldim(0.0f), cegui_reldim(0.0f)));
d_window->setSize(USize(cegui_reldim(1.0f), cegui_reldim(1.0f)));
d_button = WindowManager::getSingleton().createWindow("CEGUI/PushButton");
d_button->setPosition(UVector2(cegui_reldim(0.2f), cegui_reldim(0.2f)));
d_button->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f)));
d_editbox = WindowManager::getSingleton().createWindow("TaharezLook/Editbox");
d_editbox->setPosition(UVector2(cegui_reldim(0.9f), cegui_reldim(0.9f)));
d_editbox->setSize(USize(cegui_reldim(0.1f), cegui_reldim(0.1f)));
d_window->addChild(d_editbox);
d_window->addChild(d_button);
System::getSingleton().getDefaultGUIContext().setRootWindow(d_window);
d_windowConnections.push_back(
d_window->subscribeEvent(Window::EventMouseClick,
Event::Subscriber(&InputInjectionFixture::handleWindowEvent, this))
);
d_buttonConnections.push_back(
d_button->subscribeEvent(PushButton::EventClicked,
Event::Subscriber(&InputInjectionFixture::handleButtonEvent, this))
);
}
~InputInjectionFixture()
{
disconnectConnections(d_windowConnections);
disconnectConnections(d_buttonConnections);
System::getSingleton().getDefaultGUIContext().setRootWindow(0);
WindowManager::getSingleton().destroyWindow(d_window);
}
bool handleButtonEvent(const EventArgs& e)
{
++d_buttonHandledCount;
return true;
}
bool handleWindowEvent(const EventArgs& e)
{
++d_windowHandledCount;
return true;
}
void disconnectConnections(std::vector<Event::Connection>& connections)
{
for(std::vector<Event::Connection>::iterator itor = connections.begin();
itor != connections.end(); ++itor)
{
(*itor)->disconnect();
}
}
int d_buttonHandledCount;
int d_windowHandledCount;
Window* d_window;
Window* d_button;
Window* d_editbox;
std::vector<Event::Connection> d_windowConnections;
std::vector<Event::Connection> d_buttonConnections;
};
//----------------------------------------------------------------------------//
static inline GUIContext& getGUIContext()
{
return System::getSingleton().getDefaultGUIContext();
}
static void doClick(float position_x, float position_y)
{
getGUIContext().injectMousePosition(position_x, position_y);
getGUIContext().injectMouseButtonDown(LeftButton);
getGUIContext().injectMouseButtonUp(LeftButton);
}
//----------------------------------------------------------------------------//
BOOST_FIXTURE_TEST_SUITE(InputInjection, InputInjectionFixture)
BOOST_AUTO_TEST_CASE(OneClickOnWindow)
{
// we check for both: a) being handled, b) have the expected final result
BOOST_REQUIRE_EQUAL(getGUIContext().injectMouseButtonClick(LeftButton), true);
BOOST_REQUIRE_EQUAL(d_windowHandledCount, 1);
BOOST_REQUIRE_EQUAL(d_buttonHandledCount, 0);
}
BOOST_AUTO_TEST_CASE(MultipleClicksOnWindow)
{
BOOST_REQUIRE_EQUAL(getGUIContext().injectMouseButtonClick(LeftButton), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectMouseButtonClick(LeftButton), true);
BOOST_REQUIRE_EQUAL(d_windowHandledCount, 2);
BOOST_REQUIRE_EQUAL(d_buttonHandledCount, 0);
}
BOOST_AUTO_TEST_CASE(OneClickOnButton)
{
doClick(30.0f, 30.0f);
BOOST_REQUIRE_EQUAL(d_windowHandledCount, 0);
BOOST_REQUIRE_EQUAL(d_buttonHandledCount, 1);
}
BOOST_AUTO_TEST_CASE(InsertSimpleText)
{
// focus the editbox
doClick(91.0f, 91.0f);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('W'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('o'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('W'), true);
BOOST_REQUIRE_EQUAL(d_editbox->getText(), "WoW");
}
BOOST_AUTO_TEST_CASE(DeleteTextWithBackspace)
{
// focus the editbox
doClick(91.0f, 91.0f);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('W'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('o'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('k'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectKeyDown(Key::Backspace), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('W'), true);
BOOST_REQUIRE_EQUAL(d_editbox->getText(), "WoW");
}
BOOST_AUTO_TEST_CASE(DeleteTextWithDelete)
{
// focus the editbox
doClick(91.0f, 91.0f);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('W'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('o'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('k'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('W'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectKeyDown(Key::ArrowLeft), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectKeyDown(Key::ArrowLeft), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectKeyDown(Key::Delete), true);
BOOST_REQUIRE_EQUAL(d_editbox->getText(), "WoW");
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fix the line ending for 'InputInjection' tests<commit_after>/***********************************************************************
* filename: InputInjection.cpp
* created: 21/5/2013
* author: Timotei Dolean
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 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 <boost/test/unit_test.hpp>
#include <vector>
#include <iostream>
#include "CEGUI/CEGUI.h"
using namespace CEGUI;
struct InputInjectionFixture
{
InputInjectionFixture()
: d_buttonHandledCount(0)
, d_windowHandledCount(0)
{
System::getSingleton().notifyDisplaySizeChanged(Sizef(100, 100));
Rectf constraint_area(0, 0, 100, 100);
System::getSingleton().getDefaultGUIContext().getMouseCursor().setConstraintArea(&constraint_area);
d_window = WindowManager::getSingleton().createWindow("DefaultWindow");
d_window->setPosition(UVector2(cegui_reldim(0.0f), cegui_reldim(0.0f)));
d_window->setSize(USize(cegui_reldim(1.0f), cegui_reldim(1.0f)));
d_button = WindowManager::getSingleton().createWindow("CEGUI/PushButton");
d_button->setPosition(UVector2(cegui_reldim(0.2f), cegui_reldim(0.2f)));
d_button->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f)));
d_editbox = WindowManager::getSingleton().createWindow("TaharezLook/Editbox");
d_editbox->setPosition(UVector2(cegui_reldim(0.9f), cegui_reldim(0.9f)));
d_editbox->setSize(USize(cegui_reldim(0.1f), cegui_reldim(0.1f)));
d_window->addChild(d_editbox);
d_window->addChild(d_button);
System::getSingleton().getDefaultGUIContext().setRootWindow(d_window);
d_windowConnections.push_back(
d_window->subscribeEvent(Window::EventMouseClick,
Event::Subscriber(&InputInjectionFixture::handleWindowEvent, this))
);
d_buttonConnections.push_back(
d_button->subscribeEvent(PushButton::EventClicked,
Event::Subscriber(&InputInjectionFixture::handleButtonEvent, this))
);
}
~InputInjectionFixture()
{
disconnectConnections(d_windowConnections);
disconnectConnections(d_buttonConnections);
System::getSingleton().getDefaultGUIContext().setRootWindow(0);
WindowManager::getSingleton().destroyWindow(d_window);
}
bool handleButtonEvent(const EventArgs& e)
{
++d_buttonHandledCount;
return true;
}
bool handleWindowEvent(const EventArgs& e)
{
++d_windowHandledCount;
return true;
}
void disconnectConnections(std::vector<Event::Connection>& connections)
{
for(std::vector<Event::Connection>::iterator itor = connections.begin();
itor != connections.end(); ++itor)
{
(*itor)->disconnect();
}
}
int d_buttonHandledCount;
int d_windowHandledCount;
Window* d_window;
Window* d_button;
Window* d_editbox;
std::vector<Event::Connection> d_windowConnections;
std::vector<Event::Connection> d_buttonConnections;
};
//----------------------------------------------------------------------------//
static inline GUIContext& getGUIContext()
{
return System::getSingleton().getDefaultGUIContext();
}
static void doClick(float position_x, float position_y)
{
getGUIContext().injectMousePosition(position_x, position_y);
getGUIContext().injectMouseButtonDown(LeftButton);
getGUIContext().injectMouseButtonUp(LeftButton);
}
//----------------------------------------------------------------------------//
BOOST_FIXTURE_TEST_SUITE(InputInjection, InputInjectionFixture)
BOOST_AUTO_TEST_CASE(OneClickOnWindow)
{
// we check for both: a) being handled, b) have the expected final result
BOOST_REQUIRE_EQUAL(getGUIContext().injectMouseButtonClick(LeftButton), true);
BOOST_REQUIRE_EQUAL(d_windowHandledCount, 1);
BOOST_REQUIRE_EQUAL(d_buttonHandledCount, 0);
}
BOOST_AUTO_TEST_CASE(MultipleClicksOnWindow)
{
BOOST_REQUIRE_EQUAL(getGUIContext().injectMouseButtonClick(LeftButton), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectMouseButtonClick(LeftButton), true);
BOOST_REQUIRE_EQUAL(d_windowHandledCount, 2);
BOOST_REQUIRE_EQUAL(d_buttonHandledCount, 0);
}
BOOST_AUTO_TEST_CASE(OneClickOnButton)
{
doClick(30.0f, 30.0f);
BOOST_REQUIRE_EQUAL(d_windowHandledCount, 0);
BOOST_REQUIRE_EQUAL(d_buttonHandledCount, 1);
}
BOOST_AUTO_TEST_CASE(InsertSimpleText)
{
// focus the editbox
doClick(91.0f, 91.0f);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('W'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('o'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('W'), true);
BOOST_REQUIRE_EQUAL(d_editbox->getText(), "WoW");
}
BOOST_AUTO_TEST_CASE(DeleteTextWithBackspace)
{
// focus the editbox
doClick(91.0f, 91.0f);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('W'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('o'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('k'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectKeyDown(Key::Backspace), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('W'), true);
BOOST_REQUIRE_EQUAL(d_editbox->getText(), "WoW");
}
BOOST_AUTO_TEST_CASE(DeleteTextWithDelete)
{
// focus the editbox
doClick(91.0f, 91.0f);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('W'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('o'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('k'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectChar('W'), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectKeyDown(Key::ArrowLeft), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectKeyDown(Key::ArrowLeft), true);
BOOST_REQUIRE_EQUAL(getGUIContext().injectKeyDown(Key::Delete), true);
BOOST_REQUIRE_EQUAL(d_editbox->getText(), "WoW");
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include "config_manager.h"
using namespace std;
using namespace TOOLS;
ConfigDataKeeper::ConfigDataKeeper(const ConfigDataKeeper& obj)
: storage(obj.storage), tinfo(obj.tinfo) { }
ConfigDataKeeper::ConfigDataKeeper(void* data, const string& tinfo)
: storage(data), tinfo(tinfo) { }
ConfigDataKeeper::ConfigDataKeeper(const string& tinfo)
: storage(nullptr), tinfo(tinfo) { }
// return verbose type string
string ConfigDataKeeper::verbose_type() const {
if(tinfo == typeid(int).name())
return "integer";
else if(tinfo == typeid(double).name())
return "float";
else if(tinfo == typeid(string).name())
return "string";
else if(tinfo == typeid(tStringList).name())
return "string list";
else if(tinfo == typeid(tStringMap).name())
return "string map";
else if(tinfo == typeid(bool).name())
return "boolean";
return "unknown data type!!! ";
}
// return verbose data string representation
string ConfigDataKeeper::verbose_data(void* raw_data) const {
string out;
const ConfigDataKeeper* cdk;
if(raw_data != nullptr)
cdk = new ConfigDataKeeper(raw_data, tinfo);
else
cdk = this;
if(tinfo == typeid(int).name())
out = str(cdk->get<int>());
else if(tinfo == typeid(double).name())
out = str(cdk->get<double>());
else if(tinfo == typeid(string).name())
out = cdk->get<string>();
else if(tinfo == typeid(tStringList).name())
out = XString(",").join(cdk->get<tStringList>());
else if(tinfo == typeid(tStringMap).name()) {
tStringList tmp;
for(auto& key_val : cdk->get<tStringMap>())
tmp.push_back(key_val.first + "=" + key_val.second);
out = XString(",").join(tmp);
} else if(tinfo == typeid(bool).name())
out = (cdk->get<bool>()) ? "true" : "false";
else
out = "unknown data";
if(raw_data != nullptr)
delete cdk;
return out;
}
ConfigOption::ConfigOption(const std::string& id, const std::string& desc, \
const std::string& tinfo, const std::string& scmd)
: data(tinfo), default_data(tinfo), id(id), cmd_short(scmd), desc(desc),
was_set(false), has_default(false), parent(NULL) { }
string ConfigOption::verbose_type() const {
return data.verbose_type();
}
string ConfigOption::verbose_data() const {
return data.verbose_data();
}
string ConfigOption::verbose_default() const {
if(has_default)
return default_data.verbose_data();
return "<no default set>";
}
ConfigGroup::ConfigGroup(const std::string& name, ConfigManager* par)
: name(name), parent(par) {}
ConfigGroup::iterator ConfigGroup::begin() {
return members.begin();
}
ConfigGroup::const_iterator ConfigGroup::begin() const {
return members.begin();
}
ConfigGroup::iterator ConfigGroup::end() {
return members.end();
}
ConfigGroup::const_iterator ConfigGroup::end() const {
return members.end();
}
ConfigOption& ConfigGroup::get_option(const std::string& id) {
tOptionIter it = members.find(id);
if(it != members.end())
return *it->second;
throw OptionNotFound(id);
}
ConfigGroup& ConfigManager::new_group(const std::string& name) {
groups[name] = new ConfigGroup(name, this);
return *groups[name];
}
ConfigGroup& ConfigManager::get_group(const string& name) {
tGroupIter it = groups.find(name);
if(it == groups.end())
throw GroupNotFound(name);
return *it->second;
}
ConfigGroup& ConfigManager::get_group_from_option(const string& name) {
return *(get_option(name).parent);
}
ConfigOption& ConfigManager::get_option(const std::string& id) {
tOptionIter it = members.find(id);
if(it == members.end())
throw OptionNotFound(id);
return *(it->second);
}
ConfigManager::iterator ConfigManager::begin() {
return groups.begin();
}
ConfigManager::const_iterator ConfigManager::begin() const {
return groups.begin();
}
ConfigManager::iterator ConfigManager::end() {
return groups.end();
}
ConfigManager::const_iterator ConfigManager::end() const {
return groups.end();
}
ConfigManager::ConfigManager(const std::string& start_command)
: command(start_command) { }
void ConfigManager::parse(tStringList* args) {
string cmd = args->at(0);
if(cmdmap.find(cmd) == cmdmap.end())
throw UnknownParameter(cmd);
string id = cmdmap[cmd];
ConfigDataKeeper* tmp = &members[id]->data;
// catch boolean value as this doesn't need an arg
if(tmp->same_data_types<bool>()) {
if(members[id]->has_default)
set<bool>(id, !get<bool>(id));
else
set<bool>(id, true);
args->erase(args->begin());
return;
}
if(args->size() < 2)
throw MissingParameter(cmd + " - found no more args");
string arg = args->at(1);
// check for integer and double
try {
if(tmp->same_data_types<int>()) {
set<int>(id, integer(arg));
args->erase(args->begin(), args->begin()+2);
return;
} else if(tmp->same_data_types<double>()) {
set<double>(id, real(arg));
args->erase(args->begin(), args->begin()+2);
return;
}
} catch(ConvertValueError e) {
throw IncompatibleDataTypes("data: " + tmp->verbose_type() + " passed: " + arg);
}
// get string
if(tmp->same_data_types<string>()) {
set<string>(id, str(arg));
args->erase(args->begin(), args->begin()+2);
return;
}
// build tStringList from "," separated input
if(tmp->same_data_types<tStringList>()) {
set<tStringList>(id, XString(arg).split(","));
args->erase(args->begin(), args->begin()+2);
return;
// build tStringMap from "," and "=" separated input
}
if(tmp->same_data_types<tStringMap>()) {
tStringList tmp = XString(arg).split(",");
tStringMap tmpmap;
for(tStringIter i=tmp.begin(); i!=tmp.end(); ++i) {
tStringList two = XString(*i).split("=");
tmpmap[two[0]] = two[1];
}
set<tStringMap>(id, tmpmap);
args->erase(args->begin(), args->begin()+2);
return;
}
throw IncompatibleDataTypes("data: " + tmp->verbose_type() + " passed: " + arg);
}
void ConfigManager::parse_cmdline(int argc, char* argv[]) {
tStringList args;
for(int i=1; i<argc; ++i)
args.push_back(argv[i]);
while(args.size() > 0)
parse(&args);
}
void ConfigManager::write_config_file(ostream& fd, bool shorter) {
fd << endl;
fd << "###" << endl;
fd << "### config file for: " << command << endl;
fd << "###" << endl;
fd << endl;
for(tGroupPair& grp : groups) {
if(!shorter)
fd << "####################################################" << endl;
fd << "# [ " << grp.first << " ]" << endl;
for(tOptionPair& opt : *grp.second) {
const ConfigOption* c = opt.second;
const string& id = opt.first;
// write desc/help text
if(!shorter) {
fd << "# " << c->desc << " [" << c->verbose_type() << "]";
// write if ConfigOption has default
if(c->has_default)
fd << " default: " << c->verbose_default();
fd << endl;
}
// ConfigOption was set, output its value
if(c->was_set) {
fd << id << " = " << c->verbose_data() << endl;
// ConfigOption was _not_ set, output commented out line and default
} else if(c->has_default) {
fd << "# " << id << " = " << c->verbose_default() << endl;
// ConfigOption was neither set nor has a default value
} else {
if(!shorter)
fd << "# " << id << " = " << "<not set>" << endl;
}
if(!shorter)
fd << endl;
}
}
}
void ConfigManager::parse_config_file(const string& fn) {
ifstream fd(fn.c_str(), ios::in);
XString line;
tStringList tokens;
while(fd.good()) {
getline(fd, line);
line.strip().strip("\n");
if(line.length() == 0)
continue;
if(line.startswith("#"))
continue;
if(line.find("=") == string::npos) {
tokens.push_back("--" + line);
continue;
}
tStringList lr = line.split("=");
XString left(lr[0]), right(lr[1]);
left.strip();
right.strip();
tokens.push_back("--" + left);
tokens.push_back(right);
}
fd.close();
try {
while(tokens.size() > 0)
parse(&tokens);
} catch(IncompatibleDataTypes& e) {
e.message += " (inside configfile)";
throw e;
}
}
bool ConfigManager::is_group_active(const std::string& name) {
tOptionMap& opts = groups[name]->members;
for(tOptionIter i=opts.begin(); i!=opts.end(); ++i)
if(i->second->was_set)
return true;
return false;
}
bool ConfigManager::is_option_set(const std::string& id) {
return (get_option(id).was_set || get_option(id).has_default);
}
void ConfigManager::usage(ostream& ss) {
ss << "Usage: " << command << " <options>" << endl;
ss << endl << "Options:" << endl;
string::size_type id_len = 0, scmd_len = 0, desc_len = 0;
for(tStringMapIter i=cmdmap.begin(); i!=cmdmap.end(); ++i) {
ConfigOption* opt = members[i->second];
if(i->first.find("--") != string::npos)
id_len = max(opt->id.length(), id_len);
else
scmd_len = max(opt->cmd_short.length(), scmd_len);
desc_len = max(opt->desc.length(), desc_len);
}
for(tGroupIter g=groups.begin(); g!=groups.end(); ++g) {
ConfigGroup* grp = g->second;
ss << endl << "--- Group: " << grp->name << endl;
for(tOptionIter i=grp->members.begin(); i!=grp->members.end(); ++i) {
ConfigOption* opt = grp->members[i->first];
ss << right << setw(scmd_len+1) << ((opt->cmd_short.size() > 0) ? \
("-" + opt->cmd_short) : "") << " | " << flush;
ss << left << setw(id_len+2) << ("--" + opt->id) << " " << opt->desc;
ss << " [" << opt->data.verbose_type() << "]";
ss << endl;
}
}
ss << endl;
}
<commit_msg>wohooo goood work at configparser<commit_after>#include "config_manager.h"
using namespace std;
using namespace TOOLS;
ConfigDataKeeper::ConfigDataKeeper(const ConfigDataKeeper& obj)
: storage(obj.storage), tinfo(obj.tinfo) { }
ConfigDataKeeper::ConfigDataKeeper(void* data, const string& tinfo)
: storage(data), tinfo(tinfo) { }
ConfigDataKeeper::ConfigDataKeeper(const string& tinfo)
: storage(nullptr), tinfo(tinfo) { }
// return verbose type string
string ConfigDataKeeper::verbose_type() const {
if(tinfo == typeid(int).name())
return "integer";
else if(tinfo == typeid(double).name())
return "float";
else if(tinfo == typeid(string).name())
return "string";
else if(tinfo == typeid(tStringList).name())
return "string list";
else if(tinfo == typeid(tStringMap).name())
return "string map";
else if(tinfo == typeid(bool).name())
return "boolean";
return "unknown data type!!! ";
}
// return verbose data string representation
string ConfigDataKeeper::verbose_data(void* raw_data) const {
string out;
const ConfigDataKeeper* cdk;
if(raw_data != nullptr)
cdk = new ConfigDataKeeper(raw_data, tinfo);
else
cdk = this;
if(tinfo == typeid(int).name())
out = str(cdk->get<int>());
else if(tinfo == typeid(double).name())
out = str(cdk->get<double>());
else if(tinfo == typeid(string).name())
out = cdk->get<string>();
else if(tinfo == typeid(tStringList).name())
out = XString(",").join(cdk->get<tStringList>());
else if(tinfo == typeid(tStringMap).name()) {
tStringList tmp;
for(auto& key_val : cdk->get<tStringMap>())
tmp.push_back(key_val.first + ":" + key_val.second);
out = XString(",").join(tmp);
} else if(tinfo == typeid(bool).name())
out = (cdk->get<bool>()) ? "true" : "false";
else
out = "unknown data";
if(raw_data != nullptr)
delete cdk;
return out;
}
ConfigOption::ConfigOption(const std::string& id, const std::string& desc, \
const std::string& tinfo, const std::string& scmd)
: data(tinfo), default_data(tinfo), id(id), cmd_short(scmd), desc(desc),
was_set(false), has_default(false), parent(NULL) { }
string ConfigOption::verbose_type() const {
return data.verbose_type();
}
string ConfigOption::verbose_data() const {
return data.verbose_data();
}
string ConfigOption::verbose_default() const {
if(has_default)
return default_data.verbose_data();
return "<no default set>";
}
ConfigGroup::ConfigGroup(const std::string& name, ConfigManager* par)
: name(name), parent(par) {}
ConfigGroup::iterator ConfigGroup::begin() {
return members.begin();
}
ConfigGroup::const_iterator ConfigGroup::begin() const {
return members.begin();
}
ConfigGroup::iterator ConfigGroup::end() {
return members.end();
}
ConfigGroup::const_iterator ConfigGroup::end() const {
return members.end();
}
ConfigOption& ConfigGroup::get_option(const std::string& id) {
tOptionIter it = members.find(id);
if(it != members.end())
return *it->second;
throw OptionNotFound(id);
}
ConfigGroup& ConfigManager::new_group(const std::string& name) {
groups[name] = new ConfigGroup(name, this);
return *groups[name];
}
ConfigGroup& ConfigManager::get_group(const string& name) {
tGroupIter it = groups.find(name);
if(it == groups.end())
throw GroupNotFound(name);
return *it->second;
}
ConfigGroup& ConfigManager::get_group_from_option(const string& name) {
return *(get_option(name).parent);
}
ConfigOption& ConfigManager::get_option(const std::string& id) {
tOptionIter it = members.find(id);
if(it == members.end())
throw OptionNotFound(id);
return *(it->second);
}
ConfigManager::iterator ConfigManager::begin() {
return groups.begin();
}
ConfigManager::const_iterator ConfigManager::begin() const {
return groups.begin();
}
ConfigManager::iterator ConfigManager::end() {
return groups.end();
}
ConfigManager::const_iterator ConfigManager::end() const {
return groups.end();
}
ConfigManager::ConfigManager(const std::string& start_command)
: command(start_command) { }
void ConfigManager::parse(tStringList* args) {
string cmd = args->at(0);
if(cmdmap.find(cmd) == cmdmap.end())
throw UnknownParameter(cmd);
string id = cmdmap[cmd];
ConfigDataKeeper* tmp = &members[id]->data;
// catch boolean value as this doesn't need an arg
if(tmp->same_data_types<bool>()) {
// even if possible, a arg for bools may be passed
bool explicit_set = false;
if(args->at(1) == "true") {
explicit_set = true;
set<bool>(id, true);
} else if(args->at(1) == "false") {
explicit_set = true;
set<bool>(id, false);
}
if(explicit_set) {
args->erase(args->begin(), args->begin()+2);
return;
}
// if not passed, just toggle or set to true
if(members[id]->has_default)
set<bool>(id, !get<bool>(id));
else
set<bool>(id, true);
args->erase(args->begin());
}
if(args->size() < 2)
throw MissingParameter(cmd + " - found no more args");
string arg = args->at(1);
// check for integer and double
try {
if(tmp->same_data_types<int>()) {
set<int>(id, integer(arg));
args->erase(args->begin(), args->begin()+2);
return;
} else if(tmp->same_data_types<double>()) {
set<double>(id, real(arg));
args->erase(args->begin(), args->begin()+2);
return;
}
} catch(ConvertValueError e) {
throw IncompatibleDataTypes("data: " + tmp->verbose_type() + " passed: " + arg);
}
// get string
if(tmp->same_data_types<string>()) {
set<string>(id, str(arg));
args->erase(args->begin(), args->begin()+2);
return;
}
// build tStringList from "," separated input
if(tmp->same_data_types<tStringList>()) {
set<tStringList>(id, XString(arg).split(","));
args->erase(args->begin(), args->begin()+2);
return;
// build tStringMap from "," and ":" separated input
}
if(tmp->same_data_types<tStringMap>()) {
tStringList tmp = XString(arg).split(",");
tStringMap tmpmap;
for(tStringIter i=tmp.begin(); i!=tmp.end(); ++i) {
tStringList two = XString(*i).split(":");
tmpmap[two[0]] = two[1];
}
set<tStringMap>(id, tmpmap);
args->erase(args->begin(), args->begin()+2);
return;
}
throw IncompatibleDataTypes("data: " + tmp->verbose_type() + " passed: " + arg);
}
void ConfigManager::parse_cmdline(int argc, char* argv[]) {
tStringList args;
for(int i=1; i<argc; ++i)
args.push_back(argv[i]);
while(args.size() > 0)
parse(&args);
}
void ConfigManager::write_config_file(ostream& fd, bool shorter) {
fd << endl;
fd << "###" << endl;
fd << "### config file for: " << command << endl;
fd << "###" << endl;
fd << endl;
for(tGroupPair& grp : groups) {
if(!shorter)
fd << "####################################################" << endl;
else
fd << endl;
fd << "# [ " << grp.first << " ]" << endl;
for(tOptionPair& opt : *grp.second) {
const ConfigOption* c = opt.second;
const string& id = opt.first;
// write desc/help text
if(!shorter) {
fd << "# " << c->desc << " [" << c->verbose_type() << "]";
// write if ConfigOption has default
if(c->has_default)
fd << " default: " << c->verbose_default();
fd << endl;
}
// ConfigOption was set, output its value
if(c->was_set) {
fd << id << " = " << c->verbose_data() << endl;
// ConfigOption was _not_ set, output commented out line and default
} else if(c->has_default) {
fd << "# " << id << " = " << c->verbose_default() << endl;
// ConfigOption was neither set nor has a default value
} else {
if(!shorter)
fd << "# " << id << " = " << "<not set>" << endl;
}
if(!shorter)
fd << endl;
}
}
}
void ConfigManager::parse_config_file(const string& fn) {
ifstream fd(fn.c_str(), ios::in);
XString line;
tStringList tokens;
while(fd.good()) {
getline(fd, line);
line.strip().strip("\n");
if(line.length() == 0)
continue;
if(line.startswith("#"))
continue;
if(line.find("=") == string::npos) {
tokens.push_back("--" + line);
continue;
}
tStringList lr = line.split("=");
XString left(lr[0]), right(lr[1]);
left.strip();
right.strip();
tokens.push_back("--" + left);
tokens.push_back(right);
}
fd.close();
try {
while(tokens.size() > 0)
parse(&tokens);
} catch(IncompatibleDataTypes& e) {
e.message += " (inside configfile)";
throw e;
}
}
bool ConfigManager::is_group_active(const std::string& name) {
tOptionMap& opts = groups[name]->members;
for(tOptionIter i=opts.begin(); i!=opts.end(); ++i)
if(i->second->was_set)
return true;
return false;
}
bool ConfigManager::is_option_set(const std::string& id) {
return (get_option(id).was_set || get_option(id).has_default);
}
void ConfigManager::usage(ostream& ss) {
ss << "Usage: " << command << " <options>" << endl;
ss << endl << "Options:" << endl;
string::size_type id_len = 0, scmd_len = 0, desc_len = 0;
for(tStringMapIter i=cmdmap.begin(); i!=cmdmap.end(); ++i) {
ConfigOption* opt = members[i->second];
if(i->first.find("--") != string::npos)
id_len = max(opt->id.length(), id_len);
else
scmd_len = max(opt->cmd_short.length(), scmd_len);
desc_len = max(opt->desc.length(), desc_len);
}
for(tGroupIter g=groups.begin(); g!=groups.end(); ++g) {
ConfigGroup* grp = g->second;
ss << endl << "--- Group: " << grp->name << endl;
for(tOptionIter i=grp->members.begin(); i!=grp->members.end(); ++i) {
ConfigOption* opt = grp->members[i->first];
ss << right << setw(scmd_len+1) << ((opt->cmd_short.size() > 0) ? \
("-" + opt->cmd_short) : "") << " | " << flush;
ss << left << setw(id_len+2) << ("--" + opt->id) << " " << opt->desc;
ss << " [" << opt->data.verbose_type() << "]";
ss << endl;
}
}
ss << endl;
}
<|endoftext|> |
<commit_before>// Title : Implementation of Coroutine in Cpp
// Author : hanzh.xu@gmail.com
// Date : 11-21-2020
// License : MIT License
/*
Implementation of Coroutine in Cpp
Compiler:
// clang version 3.8.1-24+rpi1 (tags/RELEASE_381/final)
// Target: armv6--linux-gnueabihf
// Thread model: posix
// clang -std=c++0x -lstdc++
Usage:
// class MyGen : public Gen<Output type of the generator>
class OneMoreHanoiGen : public Gen<string> {
public:
// Local variables of the generator.
int n;
string a, b, c;
shared_ptr<Gen<string> > iter;
// Constructor of the generator.
OneMoreHanoiGen(int _n, string _a, string _b, string _c):
n(_n), a(_a), b(_b), c(_c) {}
// Write your code in the step method.
// It is very straight forward.
// You just need to replace all control statements with the MACRO in your generator.
// bool step(string& output);
// Args:
// output: the output of your generator, set the output before doing yield.
// Return:
// The return value is used by the framework.
// You don't need to return true or false by yourself, and the MACRO will take care of it.
bool step(string& output) {
// Declare all the control statements at first.
// IMPORTANT: You can NOT use a control MACRO without declaring its name.
// DEC_BEG : begin the declaration.
// DEF_IF(if_name) : declare a if statement named if_name.
// DEF_LOOP(loop_name) : declare a loop statement named loop_name.
// DEC_YIELD(yield_name) : declare a loop statement named yield_name.
// DEC_END : end the declaration.
DEC_BEG
DEC_IF(if1), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_LOOP(loop3),
DEC_YIELD(y1), DEC_YIELD(y2), DEC_YIELD(y3), DEC_YIELD(y4)
DEC_END
// Using the control MACRO to write the code.
// PRG_BEG -> Begin the program.
// IF(name, condition, true_block, false_block); -> A if statment with name.
// WHILE(name, condition loop_block); -> A while loop with name.
// BREAK(loop_name); -> Jump to the end of the loop named loop_name
// CONTINUE(loop_name); -> Jump to the begin of the loop named loop_name
// YIELD(name); -> A yield statement with name.
// RETURN(); -> Finish the generator.
// PRG_END -> End the program.
PRG_BEG
IF(if1, n == 1, {
output = a + " --> " + c;
YIELD(y1);
}, {
iter = make_shared<OneMoreHanoiGen>(n - 1, a, c, b);
WHILE(loop1, iter->next(output), YIELD(y2));
iter = make_shared<OneMoreHanoiGen>(1, a, b, c);
WHILE(loop2, iter->next(output), YIELD(y3));
iter = make_shared<OneMoreHanoiGen>(n - 1, b, a, c);
WHILE(loop3, iter->next(output), YIELD(y4));
});
PRG_END
}
};
int main() {
string output;
// Build a HanoiGen with Args (3, "A", "B", "C").
OneMoreHanoiGen hanoiGen(3, "A", "B", "C");
// Get the next output, until the generator returns false.
// bool isAlive = hanoiGen(output);
// if(isAlive) cout << output << endl;
while(hanoiGen(output)) cout << output << endl;
return 0;
}
// You also can create a coroutine having full functionality, if you want to do some interactive operations with the coroutine.
// The only difference is that the step method has an extra argument input now.
// The input argument represents the input variable that you pass into the Coroutine.
// See the example class GuessNumber to know how to use it.
template<typename S, typename T>
class Coroutine : public std::enable_shared_from_this<Coroutine<S,T>> {
public:
virtual bool step(S& input, T& output) = 0;
*/
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <functional>
#include <memory>
#include <string>
#include <tuple>
#include <typeinfo>
#include <utility>
#include <vector>
using namespace std;
template<typename S>
class Source : public std::enable_shared_from_this<Source<S>> {
public:
virtual ~Source() {}
virtual bool operator()(S& output) = 0;
bool next(S& output) {
return (*this)(output);
}
shared_ptr<Source<S>> getPtr() { return this->shared_from_this(); }
};
template<typename S>
class Gen : public Source<S> {
public:
int state;
bool isAlive;
Gen() : state(0), isAlive(true) {}
virtual bool step(S& output) = 0;
bool operator()(S& output) {
while(!step(output));
return isAlive;
}
};
template<typename S, typename T>
class Coroutine : public std::enable_shared_from_this<Coroutine<S,T>> {
public:
int state;
bool isAlive;
Coroutine() : state(0), isAlive(true) {}
virtual ~Coroutine() {}
virtual bool step(S& input, T& output) = 0;
bool next(S& input, T& output) {
while(!step(input, output));
return isAlive;
}
bool operator()(S& input, T& output) {
return next(input, output);
}
shared_ptr<Coroutine<S,T>> getPtr() { return this->shared_from_this(); }
};
#define PRG_BEG \
switch(state) { \
case PBEG: {}
#define PRG_END \
case PEND: {} \
default: { isAlive = false; return true; } }
#define BEG(name) BEG_##name
#define ELSE(name) ELSE_##name
#define END(name) END_##name
#define IF(name,c,a,b) \
case BEG(name): { if(c) { {a;} state = END(name); return false; } else { state = ELSE(name); } } \
case ELSE(name): { b; } \
case END(name): {}
#define LOOP(name,s) \
case BEG(name): { {s;} state = BEG(name); return false; } \
case END(name): {}
#define WHILE(name,c,s) \
case BEG(name): { if(!(c)) { state = END(name); return false; } {s;} state = BEG(name); return false; } \
case END(name): {}
#define YIELD(name) \
case BEG(name): { state = END(name); isAlive = true; return true; } \
case END(name): {}
#define CONTINUE(loop) { state = BEG(loop); return false; }
#define BREAK(loop) { state = END(loop); return false; }
#define GOTO(label) { state = label; return false; }
#define RETURN() { state = PEND; return false; }
#define DEC_BEG enum { PBEG = 0, PEND,
#define DEC_IF(name) BEG(name), ELSE(name), END(name)
#define DEC_LOOP(name) BEG(name), END(name)
#define DEC_YIELD(name) BEG(name), END(name)
#define DEC_END };
/*
L: def prod_iter(s):
0: if len(s) == 0:
1: yield []
2: else:
3: x = 0
4: while true:
5: xs = []
6: iter = generator.create(prod_iter(s[1:]))
7: while true:
8: xs, isAlive = iter.resume()
9: if !isAlive:
10 break
11 yield [x] + xs
12 x += 1
13 if x >= s[0]:
14 break
-1 return
*/
class OneMoreProdGen : public Gen<vector<int> > {
public:
vector<unsigned int> s;
int x;
shared_ptr<Source<vector<int> > > iter;
vector<int> xs;
OneMoreProdGen(const vector<unsigned int>& _s) : s(_s) {}
bool step(vector<int>& output) {
DEC_BEG
DEC_IF(if1), DEC_IF(if2), DEC_IF(if3),
DEC_LOOP(loop1), DEC_LOOP(loop2),
DEC_YIELD(y1), DEC_YIELD(y2)
DEC_END
PRG_BEG
IF(if1, s.size()==0, {
output.clear();
YIELD(y1);
}, {
x = 0;
WHILE(loop1, true, {
IF(if3, x >= s[0], BREAK(loop1), {});
{
vector<unsigned int> ss(s.begin() + 1, s.end());
iter = make_shared<OneMoreProdGen>(ss);
}
WHILE(loop2, iter->next(xs), {
output.clear();
output.push_back(x);
output.insert(output.end(), xs.begin(), xs.end());
YIELD(y2);
});
x += 1;
})
});
PRG_END
}
};
/*
def hanoi(n, a, b, c):
if n == 1:
s = str(a) + ' --> ' + str(c)
yield s
else:
for s in hanoi(n - 1, a, c, b):
yield s
for s in hanoi(1 , a, b, c):
yield s
for s in hanoi(n - 1, b, a, c):
yield s
*/
class OneMoreHanoiGen : public Gen<string> {
public:
int n;
string a, b, c;
shared_ptr<Gen<string> > iter;
OneMoreHanoiGen(int _n, string _a, string _b, string _c):
n(_n), a(_a), b(_b), c(_c) {}
bool step(string& output) {
DEC_BEG
DEC_IF(if1), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_LOOP(loop3),
DEC_YIELD(y1), DEC_YIELD(y2), DEC_YIELD(y3), DEC_YIELD(y4)
DEC_END
PRG_BEG
IF(if1, n == 1, {
output = a + " --> " + c;
YIELD(y1);
}, {
iter = make_shared<OneMoreHanoiGen>(n - 1, a, c, b);
WHILE(loop1, iter->next(output), YIELD(y2));
iter = make_shared<OneMoreHanoiGen>(1, a, b, c);
WHILE(loop2, iter->next(output), YIELD(y3));
iter = make_shared<OneMoreHanoiGen>(n - 1, b, a, c);
WHILE(loop3, iter->next(output), YIELD(y4));
});
PRG_END
}
};
class PrimeGen : public Gen<int> {
public:
vector<int> primes;
int i, j;
PrimeGen() {}
bool step(int& output) {
DEC_BEG
DEC_IF(if1), DEC_IF(if2),
DEC_LOOP(loop1), DEC_LOOP(loop2),
DEC_YIELD(y1)
DEC_END
PRG_BEG
i = 2;
WHILE(loop1, true, {
j = 0;
WHILE(loop2, j < primes.size(), {
IF(if1, i % primes[j] == 0, {i++; CONTINUE(loop1);}, j++);
});
primes.push_back(i);
output = i;
YIELD(y1);
});
PRG_END
}
};
class GuessNumber : public Coroutine<int, int> {
public:
int t, num;
GuessNumber() {}
bool step(int& input, int& output) {
DEC_BEG
DEC_IF(if1), DEC_IF(if2),
DEC_LOOP(loop1), DEC_LOOP(loop2),
DEC_YIELD(y1), DEC_YIELD(y2)
DEC_END
PRG_BEG
t = 0;
srand(time(0));
cout << "Guess a number between 0 and 100!" << endl;
WHILE(loop1, true, {
cout << "Match " << t << endl;
num = rand() % 100;
cout << "input a number:";
YIELD(y1);
WHILE(loop2, input != num, {
IF(if2, input == -1, BREAK(loop1), {});
IF(if1, input < num, {
cout << "Too small!" << endl;
output = -1;
}, {
cout << "Too large!" << endl;
output = 1;
});
cout << "input a number agian:";
YIELD(y2);
});
cout << "Bingo! It's " << num << "!" << endl;
cout << "Let's play it again!" << endl;
t++;
output = 0;
});
cout << "ByeBye!" << endl;
PRG_END
}
};
template<typename T>
void print(vector<T>& vec) {
for(int i = 0; i < vec.size(); ++i) {
cout << vec[i] << " ";
}
cout << endl;
}
void testGuessNumber() {
GuessNumber guess;
int num, output;
guess(num, output);
do {
cin >> num;
} while(guess(num, output));
}
int main() {
cout << "HanoiGen" << endl;
string s;
OneMoreHanoiGen hanoiGen(3, "A", "B", "C");
while(hanoiGen(s)) cout << s << endl;
cout << "CartesianProduct" << endl;
vector<unsigned int> dimSize({2,3,4});
vector<int> output(dimSize.size());
OneMoreProdGen prodGen(dimSize);
while(prodGen(output)) print(output);
cout << "Prime numbers" << endl;
PrimeGen primeGen;
int p;
for(int i = 0; i < 30; ++i) {
primeGen(p);
cout << p << " ";
}
cout << endl;
testGuessNumber();
return 0;
}
<commit_msg>Update macro_yield.cpp<commit_after>// Title : Implementation of Coroutine in Cpp
// Author : hanzh.xu@gmail.com
// Date : 11-21-2020
// License : MIT License
/*
Implementation of Coroutine in Cpp
Compiler:
// clang version 3.8.1-24+rpi1 (tags/RELEASE_381/final)
// Target: armv6--linux-gnueabihf
// Thread model: posix
// clang -std=c++0x -lstdc++
Usage:
// class MyGen : public Gen<Output type of the generator>
class OneMoreHanoiGen : public Gen<string> {
public:
// Local variables of the generator.
int n;
string a, b, c;
shared_ptr<Gen<string> > iter;
// Constructor of the generator.
OneMoreHanoiGen(int _n, string _a, string _b, string _c):
n(_n), a(_a), b(_b), c(_c) {}
// Write your code in the step method.
// It is very straight forward.
// You just need to replace all control statements with the MACRO in your generator.
// bool step(string& output);
// Args:
// output: the output of your generator, set the output before doing yield.
// Return:
// The return value is used by the framework.
// DO NOT return true or false by yourself, let the MACRO takes care of it.
bool step(string& output) {
// Declare all the control statements at first.
// IMPORTANT: You can NOT use a control MACRO without declaring its name.
// DEC_BEG : begin the declaration.
// DEF_IF(if_name) : declare a if statement named if_name.
// DEF_LOOP(loop_name) : declare a loop statement named loop_name.
// DEC_YIELD(yield_name) : declare a loop statement named yield_name.
// DEC_END : end the declaration.
DEC_BEG
DEC_IF(if1), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_LOOP(loop3),
DEC_YIELD(y1), DEC_YIELD(y2), DEC_YIELD(y3), DEC_YIELD(y4)
DEC_END
// Using the control MACRO to write the code.
// PRG_BEG -> Begin the program.
// IF(name, condition, true_block, false_block); -> A if statment with name.
// WHILE(name, condition loop_block); -> A while loop with name.
// BREAK(loop_name); -> Jump to the end of the loop named loop_name
// CONTINUE(loop_name); -> Jump to the begin of the loop named loop_name
// YIELD(name); -> A yield statement with name.
// RETURN(); -> Finish the generator.
// PRG_END -> End the program.
PRG_BEG
IF(if1, n == 1, {
output = a + " --> " + c;
YIELD(y1);
}, {
iter = make_shared<OneMoreHanoiGen>(n - 1, a, c, b);
WHILE(loop1, iter->next(output), YIELD(y2));
iter = make_shared<OneMoreHanoiGen>(1, a, b, c);
WHILE(loop2, iter->next(output), YIELD(y3));
iter = make_shared<OneMoreHanoiGen>(n - 1, b, a, c);
WHILE(loop3, iter->next(output), YIELD(y4));
});
PRG_END
}
};
int main() {
string output;
// Build a HanoiGen with Args (3, "A", "B", "C").
OneMoreHanoiGen hanoiGen(3, "A", "B", "C");
// Get the next output, until the generator returns false.
// bool isAlive = hanoiGen(output);
// if(isAlive) cout << output << endl;
while(hanoiGen(output)) cout << output << endl;
return 0;
}
// You also can create a coroutine having full functionality, if you want to do some interactive operations with the coroutine.
// The only difference is that the step method has an extra argument input now.
// The input argument represents the input variable that you pass into the Coroutine.
// See the example class GuessNumber to know how to use it.
template<typename S, typename T>
class Coroutine : public std::enable_shared_from_this<Coroutine<S,T>> {
public:
virtual bool step(S& input, T& output) = 0;
*/
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <functional>
#include <memory>
#include <string>
#include <tuple>
#include <typeinfo>
#include <utility>
#include <vector>
using namespace std;
template<typename S>
class Source : public std::enable_shared_from_this<Source<S>> {
public:
virtual ~Source() {}
virtual bool operator()(S& output) = 0;
bool next(S& output) {
return (*this)(output);
}
shared_ptr<Source<S>> getPtr() { return this->shared_from_this(); }
};
template<typename S>
class Gen : public Source<S> {
public:
int state;
bool isAlive;
Gen() : state(0), isAlive(true) {}
virtual bool step(S& output) = 0;
bool operator()(S& output) {
while(!step(output));
return isAlive;
}
};
template<typename S, typename T>
class Coroutine : public std::enable_shared_from_this<Coroutine<S,T>> {
public:
int state;
bool isAlive;
Coroutine() : state(0), isAlive(true) {}
virtual ~Coroutine() {}
virtual bool step(S& input, T& output) = 0;
bool next(S& input, T& output) {
while(!step(input, output));
return isAlive;
}
bool operator()(S& input, T& output) {
return next(input, output);
}
shared_ptr<Coroutine<S,T>> getPtr() { return this->shared_from_this(); }
};
#define PRG_BEG \
switch(state) { \
case PBEG: {}
#define PRG_END \
case PEND: {} \
default: { isAlive = false; return true; } }
#define BEG(name) BEG_##name
#define ELSE(name) ELSE_##name
#define END(name) END_##name
#define IF(name,c,a,b) \
case BEG(name): { if(c) { {a;} state = END(name); return false; } else { state = ELSE(name); } } \
case ELSE(name): { b; } \
case END(name): {}
#define LOOP(name,s) \
case BEG(name): { {s;} state = BEG(name); return false; } \
case END(name): {}
#define WHILE(name,c,s) \
case BEG(name): { if(!(c)) { state = END(name); return false; } {s;} state = BEG(name); return false; } \
case END(name): {}
#define YIELD(name) \
case BEG(name): { state = END(name); isAlive = true; return true; } \
case END(name): {}
#define CONTINUE(loop) { state = BEG(loop); return false; }
#define BREAK(loop) { state = END(loop); return false; }
#define GOTO(label) { state = label; return false; }
#define RETURN() { state = PEND; return false; }
#define DEC_BEG enum { PBEG = 0, PEND,
#define DEC_IF(name) BEG(name), ELSE(name), END(name)
#define DEC_LOOP(name) BEG(name), END(name)
#define DEC_YIELD(name) BEG(name), END(name)
#define DEC_END };
/*
L: def prod_iter(s):
0: if len(s) == 0:
1: yield []
2: else:
3: x = 0
4: while true:
5: xs = []
6: iter = generator.create(prod_iter(s[1:]))
7: while true:
8: xs, isAlive = iter.resume()
9: if !isAlive:
10 break
11 yield [x] + xs
12 x += 1
13 if x >= s[0]:
14 break
-1 return
*/
class OneMoreProdGen : public Gen<vector<int> > {
public:
vector<unsigned int> s;
int x;
shared_ptr<Source<vector<int> > > iter;
vector<int> xs;
OneMoreProdGen(const vector<unsigned int>& _s) : s(_s) {}
bool step(vector<int>& output) {
DEC_BEG
DEC_IF(if1), DEC_IF(if2), DEC_IF(if3),
DEC_LOOP(loop1), DEC_LOOP(loop2),
DEC_YIELD(y1), DEC_YIELD(y2)
DEC_END
PRG_BEG
IF(if1, s.size()==0, {
output.clear();
YIELD(y1);
}, {
x = 0;
WHILE(loop1, true, {
IF(if3, x >= s[0], BREAK(loop1), {});
{
vector<unsigned int> ss(s.begin() + 1, s.end());
iter = make_shared<OneMoreProdGen>(ss);
}
WHILE(loop2, iter->next(xs), {
output.clear();
output.push_back(x);
output.insert(output.end(), xs.begin(), xs.end());
YIELD(y2);
});
x += 1;
})
});
PRG_END
}
};
/*
def hanoi(n, a, b, c):
if n == 1:
s = str(a) + ' --> ' + str(c)
yield s
else:
for s in hanoi(n - 1, a, c, b):
yield s
for s in hanoi(1 , a, b, c):
yield s
for s in hanoi(n - 1, b, a, c):
yield s
*/
class OneMoreHanoiGen : public Gen<string> {
public:
int n;
string a, b, c;
shared_ptr<Gen<string> > iter;
OneMoreHanoiGen(int _n, string _a, string _b, string _c):
n(_n), a(_a), b(_b), c(_c) {}
bool step(string& output) {
DEC_BEG
DEC_IF(if1), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_LOOP(loop3),
DEC_YIELD(y1), DEC_YIELD(y2), DEC_YIELD(y3), DEC_YIELD(y4)
DEC_END
PRG_BEG
IF(if1, n == 1, {
output = a + " --> " + c;
YIELD(y1);
}, {
iter = make_shared<OneMoreHanoiGen>(n - 1, a, c, b);
WHILE(loop1, iter->next(output), YIELD(y2));
iter = make_shared<OneMoreHanoiGen>(1, a, b, c);
WHILE(loop2, iter->next(output), YIELD(y3));
iter = make_shared<OneMoreHanoiGen>(n - 1, b, a, c);
WHILE(loop3, iter->next(output), YIELD(y4));
});
PRG_END
}
};
class PrimeGen : public Gen<int> {
public:
vector<int> primes;
int i, j;
PrimeGen() {}
bool step(int& output) {
DEC_BEG
DEC_IF(if1), DEC_IF(if2),
DEC_LOOP(loop1), DEC_LOOP(loop2),
DEC_YIELD(y1)
DEC_END
PRG_BEG
i = 2;
WHILE(loop1, true, {
j = 0;
WHILE(loop2, j < primes.size(), {
IF(if1, i % primes[j] == 0, {i++; CONTINUE(loop1);}, j++);
});
primes.push_back(i);
output = i;
YIELD(y1);
});
PRG_END
}
};
class GuessNumber : public Coroutine<int, int> {
public:
int t, num;
GuessNumber() {}
bool step(int& input, int& output) {
DEC_BEG
DEC_IF(if1), DEC_IF(if2),
DEC_LOOP(loop1), DEC_LOOP(loop2),
DEC_YIELD(y1), DEC_YIELD(y2)
DEC_END
PRG_BEG
t = 0;
srand(time(0));
cout << "Guess a number between 0 and 100!" << endl;
WHILE(loop1, true, {
cout << "Match " << t << endl;
num = rand() % 100;
cout << "input a number:";
YIELD(y1);
WHILE(loop2, input != num, {
IF(if2, input == -1, BREAK(loop1), {});
IF(if1, input < num, {
cout << "Too small!" << endl;
output = -1;
}, {
cout << "Too large!" << endl;
output = 1;
});
cout << "input a number agian:";
YIELD(y2);
});
cout << "Bingo! It's " << num << "!" << endl;
cout << "Let's play it again!" << endl;
t++;
output = 0;
});
cout << "ByeBye!" << endl;
PRG_END
}
};
template<typename T>
void print(vector<T>& vec) {
for(int i = 0; i < vec.size(); ++i) {
cout << vec[i] << " ";
}
cout << endl;
}
void testGuessNumber() {
GuessNumber guess;
int num, output;
guess(num, output);
do {
cin >> num;
} while(guess(num, output));
}
int main() {
cout << "HanoiGen" << endl;
string s;
OneMoreHanoiGen hanoiGen(3, "A", "B", "C");
while(hanoiGen(s)) cout << s << endl;
cout << "CartesianProduct" << endl;
vector<unsigned int> dimSize({2,3,4});
vector<int> output(dimSize.size());
OneMoreProdGen prodGen(dimSize);
while(prodGen(output)) print(output);
cout << "Prime numbers" << endl;
PrimeGen primeGen;
int p;
for(int i = 0; i < 30; ++i) {
primeGen(p);
cout << p << " ";
}
cout << endl;
testGuessNumber();
return 0;
}
<|endoftext|> |
<commit_before>#include"../header/IThreadPoolItemBase.hpp"
#include<utility> //forward, move
#include"../../lib/header/thread/CSemaphore.hpp"
#include"../../lib/header/thread/CSmartThread.hpp"
using namespace std;
namespace nThread
{
struct IThreadPoolItemBase::Impl
{
bool alive;
CSemaphore wait; //to wake up thr
CSmartThread thr; //must destroying before alive and wait
function<void()> func;
Impl();
template<class FuncFwdRef>
void exec(FuncFwdRef &&val)
{
func=forward<FuncFwdRef>(val);
wake();
}
inline void wake()
{
wait.signal();
}
~Impl();
};
IThreadPoolItemBase::Impl::Impl()
:alive{true},thr{[this]{
while(wait.wait(),alive)
func();
}}{}
IThreadPoolItemBase::Impl::~Impl()
{
alive=false;
wake();
}
IThreadPoolItemBase::IThreadPoolItemBase()=default;
IThreadPoolItemBase::IThreadPoolItemBase(IThreadPoolItemBase &&xval) noexcept=default;
IThreadPoolItemBase::id IThreadPoolItemBase::get_id() const noexcept
{
return impl_.get().thr.get_id();
}
IThreadPoolItemBase& IThreadPoolItemBase::operator=(IThreadPoolItemBase &&xval) noexcept=default;
IThreadPoolItemBase::~IThreadPoolItemBase()=default;
void IThreadPoolItemBase::exec_(const function<void()> &val)
{
impl_.get().exec(val);
}
void IThreadPoolItemBase::exec_(function<void()> &&xval)
{
impl_.get().exec(move(xval));
}
}<commit_msg>fix variable name<commit_after>#include"../header/IThreadPoolItemBase.hpp"
#include<utility> //forward, move
#include"../../lib/header/thread/CSemaphore.hpp"
#include"../../lib/header/thread/CSmartThread.hpp"
using namespace std;
namespace nThread
{
struct IThreadPoolItemBase::Impl
{
bool alive;
CSemaphore wait; //to wake up thr
CSmartThread thr; //must destroying before alive and wait
function<void()> func;
Impl();
template<class FuncFwdRef>
void exec(FuncFwdRef &&val)
{
func=forward<FuncFwdRef>(val);
wake();
}
inline void wake()
{
wait.signal();
}
~Impl();
};
IThreadPoolItemBase::Impl::Impl()
:alive{true},thr{[this]{
while(wait.wait(),alive)
func();
}}{}
IThreadPoolItemBase::Impl::~Impl()
{
alive=false;
wake();
}
IThreadPoolItemBase::IThreadPoolItemBase()=default;
IThreadPoolItemBase::IThreadPoolItemBase(IThreadPoolItemBase &&) noexcept=default;
IThreadPoolItemBase::id IThreadPoolItemBase::get_id() const noexcept
{
return impl_.get().thr.get_id();
}
IThreadPoolItemBase& IThreadPoolItemBase::operator=(IThreadPoolItemBase &&) noexcept=default;
IThreadPoolItemBase::~IThreadPoolItemBase()=default;
void IThreadPoolItemBase::exec_(const function<void()> &val)
{
impl_.get().exec(val);
}
void IThreadPoolItemBase::exec_(function<void()> &&val)
{
impl_.get().exec(move(val));
}
}<|endoftext|> |
<commit_before>/*
Copyright (C) 2009 George Kiagiadakis <kiagiadakis.george@gmail.com>
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 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 Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "qgsttest.h"
#include <QGlib/Value>
#include <QGst/Object>
class ValueTest : public QGstTest
{
Q_OBJECT
private Q_SLOTS:
void intTest();
void stringTest();
void enumTest();
void copyTest();
void castTest();
void qdebugTest();
};
void ValueTest::intTest()
{
QGlib::Value v(10);
QVERIFY(v.isValid());
QCOMPARE(v.type(), QGlib::GetType<int>());
QCOMPARE(v.get<int>(), 10);
}
void ValueTest::stringTest()
{
QGlib::Value v;
QVERIFY(!v.isValid());
v.init<QString>();
v.set(QString::fromUtf8("Γειά σου κόσμε"));
QCOMPARE(v.type(), QGlib::GetType<QString>());
QByteArray b = v.get<QByteArray>();
QCOMPARE(QString::fromUtf8(b), QString::fromUtf8("Γειά σου κόσμε"));
QCOMPARE(v.get<QString>(), QString::fromUtf8("Γειά σου κόσμε"));
}
void ValueTest::enumTest()
{
QGlib::Value v;
v.init<QGst::PadDirection>();
v.set(QGst::PadSink);
QVERIFY(v.isValid());
QCOMPARE(v.type(), QGlib::GetType<QGst::PadDirection>());
QCOMPARE(v.get<QGst::PadDirection>(), QGst::PadSink);
}
void ValueTest::copyTest()
{
QGlib::Value v(10);
QGlib::SharedValue sv(v);
QVERIFY(sv.isValid());
QCOMPARE(sv.type(), QGlib::GetType<int>());
QCOMPARE(sv.get<int>(), 10);
sv.set(20);
QCOMPARE(v.get<int>(), 20);
{
QGlib::Value v2(sv);
QVERIFY(v2.isValid());
QCOMPARE(v2.type(), QGlib::GetType<int>());
QCOMPARE(v2.get<int>(), 20);
v2.set(30);
QCOMPARE(v.get<int>(), 20);
QCOMPARE(sv.get<int>(), 20);
QCOMPARE(v2.get<int>(), 30);
v2 = v;
QCOMPARE(v2.get<int>(), 20);
}
{
QGlib::Value v2(v);
QVERIFY(v2.isValid());
QCOMPARE(v2.type(), QGlib::GetType<int>());
QCOMPARE(v2.get<int>(), 20);
v2.set(30);
QCOMPARE(v.get<int>(), 20);
QCOMPARE(sv.get<int>(), 20);
QCOMPARE(v2.get<int>(), 30);
v2 = sv;
QCOMPARE(v2.get<int>(), 20);
}
}
void ValueTest::castTest()
{
QGlib::Value v(10);
GValue *gv = v;
QCOMPARE(G_VALUE_TYPE(gv), G_TYPE_INT);
QCOMPARE(g_value_get_int(gv), 10);
}
void ValueTest::qdebugTest()
{
qDebug() << QGlib::Value(10);
qDebug() << QGlib::Value(QByteArray("Hello world"));
qDebug() << QGlib::Value(QGlib::ObjectPtr());
}
QTEST_APPLESS_MAIN(ValueTest)
#include "moc_qgsttest.cpp"
#include "valuetest.moc"
<commit_msg>Add more tests for Value.<commit_after>/*
Copyright (C) 2009 George Kiagiadakis <kiagiadakis.george@gmail.com>
Copyright (C) 2010 Collabora Ltd.
@author George Kiagiadakis <george.kiagiadakis@collabora.co.uk>
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 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 Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "qgsttest.h"
#include <QGlib/Value>
#include <QGst/Bin>
#include <QGst/Message>
#include <limits>
class ValueTest : public QGstTest
{
Q_OBJECT
private Q_SLOTS:
void intTest();
void stringTest();
void stringLiteralTest();
void constCharTest();
void enumTest();
void flagsTest();
void objectTest();
void miniObjectTest();
void capsTest();
void conversionsTest();
void copyTest();
void castTest();
void qdebugTest();
};
void ValueTest::intTest()
{
QGlib::Value v(10);
QVERIFY(v.isValid());
QCOMPARE(v.type(), QGlib::GetType<int>());
QCOMPARE(v.get<int>(), 10);
}
void ValueTest::stringTest()
{
QGlib::Value v;
QVERIFY(!v.isValid());
v.init<QString>();
v.set(QString::fromUtf8("Γειά σου κόσμε"));
QCOMPARE(v.type(), QGlib::GetType<QString>());
QByteArray b = v.get<QByteArray>();
QCOMPARE(QString::fromUtf8(b), QString::fromUtf8("Γειά σου κόσμε"));
QCOMPARE(v.get<QString>(), QString::fromUtf8("Γειά σου κόσμε"));
}
void ValueTest::stringLiteralTest()
{
QGlib::Value v("Hello world");
QCOMPARE(v.type(), QGlib::GetType<QString>());
QCOMPARE(v.get<QString>(), QString("Hello world"));
}
void ValueTest::constCharTest()
{
const char *foo = "Hello world";
QGlib::Value v(foo);
QCOMPARE(v.type(), QGlib::GetType<QString>());
QCOMPARE(v.get<QString>(), QString("Hello world"));
}
void ValueTest::enumTest()
{
QGlib::Value v;
v.init<QGst::PadDirection>();
v.set(QGst::PadSink);
QVERIFY(v.isValid());
QCOMPARE(v.type(), QGlib::GetType<QGst::PadDirection>());
QCOMPARE(v.get<QGst::PadDirection>(), QGst::PadSink);
}
void ValueTest::flagsTest()
{
QGlib::Value v(QGst::PadBlocked | QGst::PadFlushing | QGst::PadFlagLast);
QCOMPARE(v.type(), QGlib::GetType<QGst::PadFlags>());
QCOMPARE(v.get<QGst::PadFlags>(), QGst::PadBlocked | QGst::PadFlushing | QGst::PadFlagLast);
}
void ValueTest::objectTest()
{
QGst::BinPtr bin = QGst::Bin::create();
QGlib::Value v(bin);
QCOMPARE(v.type(), QGlib::GetType<QGst::Bin>());
QCOMPARE(static_cast<GstBin*>(v.get<QGst::BinPtr>()), static_cast<GstBin*>(bin));
}
void ValueTest::miniObjectTest()
{
QGst::BinPtr bin = QGst::Bin::create();
QGst::EosMessagePtr msg = QGst::EosMessage::create(bin);
QGlib::Value v;
v.init<QGst::Message>();
v.set(msg);
QCOMPARE(v.type(), QGlib::GetType<QGst::Message>());
QCOMPARE(static_cast<GstMessage*>(v.get<QGst::MessagePtr>()), static_cast<GstMessage*>(msg));
}
void ValueTest::capsTest()
{
QGst::CapsPtr caps = QGst::Caps::createSimple("video/x-raw-rgb");
QGlib::Value v(caps);
QCOMPARE(v.type(), QGlib::GetType<QGst::Caps>());
QCOMPARE(static_cast<GstCaps*>(v.get<QGst::CapsPtr>()), static_cast<GstCaps*>(caps));
QCOMPARE(v.get<QGst::CapsPtr>()->toString(), QString("video/x-raw-rgb"));
QCOMPARE(v.get<QString>(), QString("video/x-raw-rgb"));
}
void ValueTest::conversionsTest()
{
QGlib::Value v;
v.init<QGst::PadDirection>();
v.set(1);
QCOMPARE(v.get<int>(), 1);
QCOMPARE(v.get<uint>(), 1U);
QCOMPARE(v.get<QGst::PadDirection>(), QGst::PadSrc);
QCOMPARE(v.get<QString>(), QString("GST_PAD_SRC"));
v.set(2U);
QCOMPARE(v.get<int>(), 2);
QCOMPARE(v.get<uint>(), 2U);
QCOMPARE(v.get<QGst::PadDirection>(), QGst::PadSink);
QCOMPARE(v.get<QString>(), QString("GST_PAD_SINK"));
v.init<uint>();
v.set(100); //setting int here, not uint
QCOMPARE(v.get<int>(), 100);
QCOMPARE(v.get<uint>(), 100U);
QCOMPARE(v.get<long>(), 100L);
QCOMPARE(v.get<ulong>(), 100UL);
QCOMPARE(v.get<qint64>(), Q_INT64_C(100));
QCOMPARE(v.get<quint64>(), Q_UINT64_C(100));
QCOMPARE(v.get<QString>(), QString("100"));
v.set(-1);
QCOMPARE(v.get<int>(), -1);
QCOMPARE(v.get<uint>(), std::numeric_limits<uint>::max());
}
void ValueTest::copyTest()
{
QGlib::Value v(10);
QGlib::SharedValue sv(v);
QVERIFY(sv.isValid());
QCOMPARE(sv.type(), QGlib::GetType<int>());
QCOMPARE(sv.get<int>(), 10);
sv.set(20);
QCOMPARE(v.get<int>(), 20);
{
QGlib::Value v2(sv);
QVERIFY(v2.isValid());
QCOMPARE(v2.type(), QGlib::GetType<int>());
QCOMPARE(v2.get<int>(), 20);
v2.set(30);
QCOMPARE(v.get<int>(), 20);
QCOMPARE(sv.get<int>(), 20);
QCOMPARE(v2.get<int>(), 30);
v2 = v;
QCOMPARE(v2.get<int>(), 20);
}
{
QGlib::Value v2(v);
QVERIFY(v2.isValid());
QCOMPARE(v2.type(), QGlib::GetType<int>());
QCOMPARE(v2.get<int>(), 20);
v2.set(30);
QCOMPARE(v.get<int>(), 20);
QCOMPARE(sv.get<int>(), 20);
QCOMPARE(v2.get<int>(), 30);
v2 = sv;
QCOMPARE(v2.get<int>(), 20);
}
}
void ValueTest::castTest()
{
QGlib::Value v(10);
GValue *gv = v;
QCOMPARE(G_VALUE_TYPE(gv), G_TYPE_INT);
QCOMPARE(g_value_get_int(gv), 10);
}
void ValueTest::qdebugTest()
{
qDebug() << QGlib::Value(10);
qDebug() << QGlib::Value(QByteArray("Hello world"));
qDebug() << QGlib::Value(QGlib::ObjectPtr());
}
QTEST_APPLESS_MAIN(ValueTest)
#include "moc_qgsttest.cpp"
#include "valuetest.moc"
<|endoftext|> |
<commit_before>#include "TaskbarNotificationAreaIcon.h"
#define ICON_UID 0 //Only one icon allowed
std::unique_ptr<TskbrNtfAreaIcon> TskbrNtfAreaIcon::instance;
UINT TskbrNtfAreaIcon::WmTaskbarCreated=RegisterWindowMessage(L"TaskbarCreated");
std::function<bool(TskbrNtfAreaIcon* sender, WPARAM wParam, LPARAM lParam)> TskbrNtfAreaIcon::OnWmCommand;
TskbrNtfAreaIcon* TskbrNtfAreaIcon::MakeInstance(HINSTANCE hInstance, UINT icon_wm, const wchar_t* icon_tooltip, UINT icon_resid, const wchar_t* icon_class, UINT icon_menuid, UINT default_menuid)
{
instance.reset(new TskbrNtfAreaIcon(hInstance, icon_wm, icon_tooltip, icon_resid, icon_class, icon_menuid, default_menuid));
return instance.get();
}
TskbrNtfAreaIcon* TskbrNtfAreaIcon::GetInstance()
{
if (instance)
return instance.get();
else
return NULL;
}
TskbrNtfAreaIcon::~TskbrNtfAreaIcon()
{
if (valid) {
icon_ntfdata.uFlags=0;
Shell_NotifyIcon(NIM_DELETE, &icon_ntfdata);
}
if (icon_ntfdata.hWnd)
DestroyWindow(icon_ntfdata.hWnd);
}
//Using first version of NOTIFYICONDATA to be compatible with pre-Win2000 OS versions
TskbrNtfAreaIcon::TskbrNtfAreaIcon(HINSTANCE hInstance, UINT icon_wm, const wchar_t* icon_tooltip, UINT icon_resid, const wchar_t* icon_class, UINT icon_menuid, UINT default_menuid):
valid(false), app_instance(hInstance), default_menuid(default_menuid), icon_ntfdata{
NOTIFYICONDATA_V1_SIZE, //cbSize
NULL, //hWnd (will set it later)
ICON_UID, //uID
NIF_MESSAGE|NIF_ICON|NIF_TIP, //uFlags
icon_wm, //uCallbackMessage
LoadIcon(hInstance, MAKEINTRESOURCE(icon_resid)) //hIcon (szTip and uVersion are initialized with NULLs)
}
{
WNDCLASSEX wcex={
sizeof(WNDCLASSEX), //cbSize
CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS, //style
(WNDPROC)WindowProc, //lpfnWndProc
0, //cbClsExtra
0, //cbWndExtra
hInstance, //hInstance
0, //hIcon
0, //hCursor
0, //hbrBackground
MAKEINTRESOURCE(icon_menuid), //lpszMenuName
icon_class, //lpszClassName
0 //hIconSm
};
//Exit only if registration failed not because of already registered class
//This is done because during a single app run we can try to create taskbar icon several times
//E.g. first attempt will fail somewhere after class registration, so subsequent attempt will have already registered class at it's disposition
if (!RegisterClassEx(&wcex)&&GetLastError()!=ERROR_CLASS_ALREADY_EXISTS)
return;
if (!(icon_ntfdata.hWnd=CreateWindow(icon_class, L"", WS_POPUP,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, 0, hInstance, 0)))
return;
wcsncpy(icon_ntfdata.szTip, icon_tooltip, 63); //First version of NOTIFYICONDATA only allowes szTip no more than 64 characters in length (including NULL-terminator)
if (!Shell_NotifyIcon(NIM_ADD, &icon_ntfdata))
return;
valid=true;
icon_menu=GetSubMenu(GetMenu(icon_ntfdata.hWnd), 0);
SetMenuDefaultItem(icon_menu, default_menuid, FALSE);
}
bool TskbrNtfAreaIcon::IsValid()
{
return valid;
}
HMENU TskbrNtfAreaIcon::GetIconMenu()
{
return icon_menu; //Is set to NULL if instance is not valid
}
void TskbrNtfAreaIcon::ChangeIconTooltip(const wchar_t* icon_tooltip)
{
if (!valid)
return;
wcsncpy(icon_ntfdata.szTip, icon_tooltip, 63); //First version of NOTIFYICONDATA only allowes szTip no more than 64 characters in length (including NULL-terminator)
Shell_NotifyIcon(NIM_MODIFY, &icon_ntfdata);
}
void TskbrNtfAreaIcon::ChangeIcon(UINT icon_resid)
{
if (!valid)
return;
icon_ntfdata.hIcon=LoadIcon(app_instance, MAKEINTRESOURCE(icon_resid));
Shell_NotifyIcon(NIM_MODIFY, &icon_ntfdata);
}
void TskbrNtfAreaIcon::Exit()
{
PostQuitMessage(0);
}
BOOL TskbrNtfAreaIcon::ModifyIconMenu(UINT uPosition, UINT uFlags, UINT_PTR uIDNewItem, LPCWSTR lpNewItem)
{
if (!valid)
return FALSE;
return ModifyMenu(icon_menu, uPosition, uFlags, uIDNewItem, lpNewItem);
}
BOOL TskbrNtfAreaIcon::EnableIconMenuItem(UINT uIDEnableItem, UINT uEnable)
{
if (!valid)
return FALSE;
return EnableMenuItem(icon_menu, uIDEnableItem, uEnable);
}
LRESULT CALLBACK TskbrNtfAreaIcon::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (instance&&instance->valid&&instance->icon_ntfdata.hWnd==hWnd) {
switch (message) {
case WM_CREATE:
return 0;
case WM_SETTINGCHANGE: //WM_SETTINGCHANGE with wParam set to SPI_SETWORKAREA signal that icon should be recreated
if (wParam==SPI_SETWORKAREA)
Shell_NotifyIcon(NIM_ADD, &instance->icon_ntfdata);
return 0;
case WM_COMMAND:
if (OnWmCommand&&OnWmCommand(instance.get(), wParam, lParam))
return 0;
break; //Let DefWindowProc handle the rest of WM_COMMAND variations if OnWmCommand returned FALSE
default:
//Non-const cases goes here
if (message==instance->icon_ntfdata.uCallbackMessage) { //Messages that are sent to taskbar icon
//For the first version of NOTIFYICONDATA lParam (as a whole, not just LOWORD) holds the mouse or keyboard messages and wParam holds icon ID
if (wParam==ICON_UID) {
switch (lParam) {
case WM_RBUTTONUP:
POINT cur_mouse_pt;
GetCursorPos(&cur_mouse_pt);
SetForegroundWindow(hWnd);
TrackPopupMenu(instance->icon_menu, TPM_LEFTBUTTON|TPM_LEFTALIGN, cur_mouse_pt.x, cur_mouse_pt.y, 0, hWnd, NULL);
SendMessage(hWnd, WM_NULL, 0, 0);
return 0;
case WM_LBUTTONDBLCLK:
if (OnWmCommand)
OnWmCommand(instance.get(), instance->default_menuid, 0);
return 0;
}
}
//Let DefWindowProc handle the rest of uCallbackMessage variations
} else if (message==WmTaskbarCreated) { //WM_TASKBARCREATED signal that icon should be recreated
Shell_NotifyIcon(NIM_ADD, &instance->icon_ntfdata);
return 0;
}
//Let DefWindowProc handle all other messages
}
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
<commit_msg>Frogot to default-initialize var<commit_after>#include "TaskbarNotificationAreaIcon.h"
#define ICON_UID 0 //Only one icon allowed
std::unique_ptr<TskbrNtfAreaIcon> TskbrNtfAreaIcon::instance;
UINT TskbrNtfAreaIcon::WmTaskbarCreated=RegisterWindowMessage(L"TaskbarCreated");
std::function<bool(TskbrNtfAreaIcon* sender, WPARAM wParam, LPARAM lParam)> TskbrNtfAreaIcon::OnWmCommand;
TskbrNtfAreaIcon* TskbrNtfAreaIcon::MakeInstance(HINSTANCE hInstance, UINT icon_wm, const wchar_t* icon_tooltip, UINT icon_resid, const wchar_t* icon_class, UINT icon_menuid, UINT default_menuid)
{
instance.reset(new TskbrNtfAreaIcon(hInstance, icon_wm, icon_tooltip, icon_resid, icon_class, icon_menuid, default_menuid));
return instance.get();
}
TskbrNtfAreaIcon* TskbrNtfAreaIcon::GetInstance()
{
if (instance)
return instance.get();
else
return NULL;
}
TskbrNtfAreaIcon::~TskbrNtfAreaIcon()
{
if (valid) {
icon_ntfdata.uFlags=0;
Shell_NotifyIcon(NIM_DELETE, &icon_ntfdata);
}
if (icon_ntfdata.hWnd)
DestroyWindow(icon_ntfdata.hWnd);
}
//Using first version of NOTIFYICONDATA to be compatible with pre-Win2000 OS versions
TskbrNtfAreaIcon::TskbrNtfAreaIcon(HINSTANCE hInstance, UINT icon_wm, const wchar_t* icon_tooltip, UINT icon_resid, const wchar_t* icon_class, UINT icon_menuid, UINT default_menuid):
valid(false), app_instance(hInstance), icon_menu(NULL), default_menuid(default_menuid), icon_ntfdata{
NOTIFYICONDATA_V1_SIZE, //cbSize
NULL, //hWnd (will set it later)
ICON_UID, //uID
NIF_MESSAGE|NIF_ICON|NIF_TIP, //uFlags
icon_wm, //uCallbackMessage
LoadIcon(hInstance, MAKEINTRESOURCE(icon_resid)) //hIcon (szTip and uVersion are initialized with NULLs)
}
{
WNDCLASSEX wcex={
sizeof(WNDCLASSEX), //cbSize
CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS, //style
(WNDPROC)WindowProc, //lpfnWndProc
0, //cbClsExtra
0, //cbWndExtra
hInstance, //hInstance
0, //hIcon
0, //hCursor
0, //hbrBackground
MAKEINTRESOURCE(icon_menuid), //lpszMenuName
icon_class, //lpszClassName
0 //hIconSm
};
//Exit only if registration failed not because of already registered class
//This is done because during a single app run we can try to create taskbar icon several times
//E.g. first attempt will fail somewhere after class registration, so subsequent attempt will have already registered class at it's disposition
if (!RegisterClassEx(&wcex)&&GetLastError()!=ERROR_CLASS_ALREADY_EXISTS)
return;
if (!(icon_ntfdata.hWnd=CreateWindow(icon_class, L"", WS_POPUP,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, 0, hInstance, 0)))
return;
wcsncpy(icon_ntfdata.szTip, icon_tooltip, 63); //First version of NOTIFYICONDATA only allowes szTip no more than 64 characters in length (including NULL-terminator)
if (!Shell_NotifyIcon(NIM_ADD, &icon_ntfdata))
return;
valid=true;
icon_menu=GetSubMenu(GetMenu(icon_ntfdata.hWnd), 0);
SetMenuDefaultItem(icon_menu, default_menuid, FALSE);
}
bool TskbrNtfAreaIcon::IsValid()
{
return valid;
}
HMENU TskbrNtfAreaIcon::GetIconMenu()
{
return icon_menu; //Is set to NULL if instance is not valid
}
void TskbrNtfAreaIcon::ChangeIconTooltip(const wchar_t* icon_tooltip)
{
if (!valid)
return;
wcsncpy(icon_ntfdata.szTip, icon_tooltip, 63); //First version of NOTIFYICONDATA only allowes szTip no more than 64 characters in length (including NULL-terminator)
Shell_NotifyIcon(NIM_MODIFY, &icon_ntfdata);
}
void TskbrNtfAreaIcon::ChangeIcon(UINT icon_resid)
{
if (!valid)
return;
icon_ntfdata.hIcon=LoadIcon(app_instance, MAKEINTRESOURCE(icon_resid));
Shell_NotifyIcon(NIM_MODIFY, &icon_ntfdata);
}
void TskbrNtfAreaIcon::Exit()
{
PostQuitMessage(0);
}
BOOL TskbrNtfAreaIcon::ModifyIconMenu(UINT uPosition, UINT uFlags, UINT_PTR uIDNewItem, LPCWSTR lpNewItem)
{
if (!valid)
return FALSE;
return ModifyMenu(icon_menu, uPosition, uFlags, uIDNewItem, lpNewItem);
}
BOOL TskbrNtfAreaIcon::EnableIconMenuItem(UINT uIDEnableItem, UINT uEnable)
{
if (!valid)
return FALSE;
return EnableMenuItem(icon_menu, uIDEnableItem, uEnable);
}
LRESULT CALLBACK TskbrNtfAreaIcon::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (instance&&instance->valid&&instance->icon_ntfdata.hWnd==hWnd) {
switch (message) {
case WM_CREATE:
return 0;
case WM_SETTINGCHANGE: //WM_SETTINGCHANGE with wParam set to SPI_SETWORKAREA signal that icon should be recreated
if (wParam==SPI_SETWORKAREA)
Shell_NotifyIcon(NIM_ADD, &instance->icon_ntfdata);
return 0;
case WM_COMMAND:
if (OnWmCommand&&OnWmCommand(instance.get(), wParam, lParam))
return 0;
break; //Let DefWindowProc handle the rest of WM_COMMAND variations if OnWmCommand returned FALSE
default:
//Non-const cases goes here
if (message==instance->icon_ntfdata.uCallbackMessage) { //Messages that are sent to taskbar icon
//For the first version of NOTIFYICONDATA lParam (as a whole, not just LOWORD) holds the mouse or keyboard messages and wParam holds icon ID
if (wParam==ICON_UID) {
switch (lParam) {
case WM_RBUTTONUP:
POINT cur_mouse_pt;
GetCursorPos(&cur_mouse_pt);
SetForegroundWindow(hWnd);
TrackPopupMenu(instance->icon_menu, TPM_LEFTBUTTON|TPM_LEFTALIGN, cur_mouse_pt.x, cur_mouse_pt.y, 0, hWnd, NULL);
SendMessage(hWnd, WM_NULL, 0, 0);
return 0;
case WM_LBUTTONDBLCLK:
if (OnWmCommand)
OnWmCommand(instance.get(), instance->default_menuid, 0);
return 0;
}
}
//Let DefWindowProc handle the rest of uCallbackMessage variations
} else if (message==WmTaskbarCreated) { //WM_TASKBARCREATED signal that icon should be recreated
Shell_NotifyIcon(NIM_ADD, &instance->icon_ntfdata);
return 0;
}
//Let DefWindowProc handle all other messages
}
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "Core/Common.h"
#include "Core/Assembler.h"
#include "Archs/MIPS/Mips.h"
#include "Commands/CDirectiveFile.h"
#include "Tests.h"
#include <chrono>
#if defined(_WIN64) || defined(__x86_64__) || defined(__amd64__)
#define ARMIPSNAME "ARMIPS64"
#else
#define ARMIPSNAME "ARMIPS"
#endif
typedef std::chrono::steady_clock Clock;
int wmain(int argc, wchar_t* argv[])
{
ArmipsArguments parameters;
auto startTime = Clock::now();
#ifdef ARMIPS_TESTS
std::wstring name;
if (argc < 2)
return !runTests(L"Tests");
else
return !runTests(argv[1]);
#endif
Logger::printLine(L"%s Assembler v%d.%d.%d (%s %s) by Kingcom",
ARMIPSNAME,ARMIPS_VERSION_MAJOR,ARMIPS_VERSION_MINOR,ARMIPS_VERSION_REVISION,__DATE__,__TIME__);
StringList arguments = getStringListFromArray(argv,argc);
if (arguments.size() < 2)
{
Logger::printLine(L"Usage: %s file.asm [-temp temp.txt] [-sym symfile.sym]", argv[0]);
return 1;
}
parameters.inputFileName = arguments[1];
// turn it into an absolute path
if (isAbsolutePath(parameters.inputFileName) == false)
parameters.inputFileName = formatString(L"%s/%s",getCurrentDirectory(),arguments[1]);
if (fileExists(parameters.inputFileName) == false)
{
Logger::printLine(L"File %S not found\n",arguments[1]);
return 1;
}
size_t argpos = 2;
bool printTime = false;
while (argpos < arguments.size())
{
if (arguments[argpos] == L"-temp")
{
parameters.tempFileName = arguments[argpos+1];
argpos += 2;
} else if (arguments[argpos] == L"-sym")
{
parameters.symFileName = arguments[argpos+1];
parameters.symFileVersion = 1;
argpos += 2;
} else if (arguments[argpos] == L"-sym2")
{
parameters.symFileName = arguments[argpos+1];
parameters.symFileVersion = 2;
argpos += 2;
} else if (arguments[argpos] == L"-erroronwarning")
{
parameters.errorOnWarning = true;
argpos += 1;
} else if (arguments[argpos] == L"-equ")
{
EquationDefinition def;
def.name = arguments[argpos + 1];
def.value = arguments[argpos + 2];
parameters.equList.push_back(def);
argpos += 3;
} else if (arguments[argpos] == L"-strequ")
{
EquationDefinition def;
def.name = arguments[argpos + 1];
def.value = formatString(L"\"%s\"",arguments[argpos + 2]);
parameters.equList.push_back(def);
argpos += 3;
} else if (arguments[argpos] == L"-time")
{
printTime = true;
argpos += 1;
} else if (arguments[argpos] == L"-root")
{
changeDirectory(arguments[argpos + 1]);
argpos += 2;
} else {
Logger::printLine(L"Invalid parameter %S\n",arguments[argpos]);
return 1;
}
}
bool result = runArmips(parameters);
auto endTime = Clock::now();
auto executionTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime-startTime);
if (result == false)
{
if (printTime)
Logger::printLine(L"Aborting. Duration: %.3fs",executionTime.count()/1000.);
else
Logger::printLine(L"Aborting.");
return 1;
}
if (printTime)
Logger::printLine(L"Done. Duration: %.3fs",executionTime.count()/1000.);
else
Logger::printLine(L"Done.");
return 0;
}
#ifndef _WIN32
int main(int argc, char* argv[])
{
// convert input to wstring
std::vector<std::wstring> wideStrings;
for (int i = 0; i < argc; i++)
{
std::wstring str = convertUtf8ToWString(argv[i]);
wideStrings.push_back(str);
}
// create argv replacement
wchar_t** wargv = new wchar_t*[argc];
for (int i = 0; i < argc; i++)
{
wargv[i] = (wchar_t*) wideStrings[i].c_str();
}
int result = wmain(argc,wargv);
delete[] wargv;
return result;
}
#endif
<commit_msg>Less verbose program output on success, remove timing feature<commit_after>#include "stdafx.h"
#include "Core/Common.h"
#include "Core/Assembler.h"
#include "Archs/MIPS/Mips.h"
#include "Commands/CDirectiveFile.h"
#include "Tests.h"
#if defined(_WIN64) || defined(__x86_64__) || defined(__amd64__)
#define ARMIPSNAME "ARMIPS64"
#else
#define ARMIPSNAME "ARMIPS"
#endif
int wmain(int argc, wchar_t* argv[])
{
ArmipsArguments parameters;
#ifdef ARMIPS_TESTS
std::wstring name;
if (argc < 2)
return !runTests(L"Tests");
else
return !runTests(argv[1]);
#endif
StringList arguments = getStringListFromArray(argv,argc);
if (arguments.size() < 2)
{
Logger::printLine(L"%s Assembler v%d.%d.%d (%s %s) by Kingcom",
ARMIPSNAME,ARMIPS_VERSION_MAJOR,ARMIPS_VERSION_MINOR,ARMIPS_VERSION_REVISION,__DATE__,__TIME__);
Logger::printLine(L"Usage: %s file.asm [-temp temp.txt] [-sym symfile.sym]", argv[0]);
return 1;
}
parameters.inputFileName = arguments[1];
// turn it into an absolute path
if (isAbsolutePath(parameters.inputFileName) == false)
parameters.inputFileName = formatString(L"%s/%s",getCurrentDirectory(),arguments[1]);
if (fileExists(parameters.inputFileName) == false)
{
Logger::printLine(L"File %S not found\n",arguments[1]);
return 1;
}
size_t argpos = 2;
bool printTime = false;
while (argpos < arguments.size())
{
if (arguments[argpos] == L"-temp")
{
parameters.tempFileName = arguments[argpos+1];
argpos += 2;
} else if (arguments[argpos] == L"-sym")
{
parameters.symFileName = arguments[argpos+1];
parameters.symFileVersion = 1;
argpos += 2;
} else if (arguments[argpos] == L"-sym2")
{
parameters.symFileName = arguments[argpos+1];
parameters.symFileVersion = 2;
argpos += 2;
} else if (arguments[argpos] == L"-erroronwarning")
{
parameters.errorOnWarning = true;
argpos += 1;
} else if (arguments[argpos] == L"-equ")
{
EquationDefinition def;
def.name = arguments[argpos + 1];
def.value = arguments[argpos + 2];
parameters.equList.push_back(def);
argpos += 3;
} else if (arguments[argpos] == L"-strequ")
{
EquationDefinition def;
def.name = arguments[argpos + 1];
def.value = formatString(L"\"%s\"",arguments[argpos + 2]);
parameters.equList.push_back(def);
argpos += 3;
} else if (arguments[argpos] == L"-root")
{
changeDirectory(arguments[argpos + 1]);
argpos += 2;
} else {
Logger::printLine(L"Invalid parameter %S\n",arguments[argpos]);
return 1;
}
}
bool result = runArmips(parameters);
if (result == false)
{
Logger::printLine(L"Aborting.");
return 1;
}
return 0;
}
#ifndef _WIN32
int main(int argc, char* argv[])
{
// convert input to wstring
std::vector<std::wstring> wideStrings;
for (int i = 0; i < argc; i++)
{
std::wstring str = convertUtf8ToWString(argv[i]);
wideStrings.push_back(str);
}
// create argv replacement
wchar_t** wargv = new wchar_t*[argc];
for (int i = 0; i < argc; i++)
{
wargv[i] = (wchar_t*) wideStrings[i].c_str();
}
int result = wmain(argc,wargv);
delete[] wargv;
return result;
}
#endif
<|endoftext|> |
<commit_before><commit_msg>Fixed Test_UserInput function<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2016 Emaad Ahmed Manzoor
* License: Apache License, Version 2.0
* http://www3.cs.stonybrook.edu/~emanzoor/streamspot/
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <deque>
#include <iostream>
#include <queue>
#include <random>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "cluster.h"
#include "docopt.h"
#include "graph.h"
#include "hash.h"
#include "io.h"
#include "param.h"
#include "simhash.h"
#include "streamhash.h"
using namespace std;
static const char USAGE[] =
R"(StreamSpot.
Usage:
streamspot --edges=<edge file>
--feature=<feature>
streamspot (-h | --help)
Options:
-h, --help Show this screen.
--edges=<edge file> Incoming stream of edges.
--feature=<feature> Feature to compute for each graph.
)";
int main(int argc, char *argv[]) {
std::cout.precision(3);
map<string, docopt::value> args = docopt::docopt(USAGE, { argv + 1, argv + argc });
string edge_file(args["--edges"].asString());
string feature(args["--feature"].asString());
cout << "StreamSpot (";
cout << "Edges=" << edge_file << " ";
cout << "Feature=" << feature << "";
cout << ")" << endl;
unordered_set<uint32_t> train_gids;
for (uint32_t i = 0; i < 600; i++) {
train_gids.insert(i);
}
unordered_set<uint32_t> scenarios;
for (uint32_t i = 0; i < 6; i++) {
scenarios.insert(i);
}
uint32_t num_graphs;
uint32_t num_test_edges;
vector<edge> train_edges;
unordered_map<uint32_t,vector<edge>> test_edges;
tie(num_graphs, train_edges, test_edges, num_test_edges) =
read_edges(edge_file, train_gids, scenarios);
if (num_graphs == 0) {
cout << "0 graphs in file" << endl;
exit(-1);
}
vector<graph> graphs(num_graphs);
cout << "Constructing " << num_graphs << " graphs..." << endl;
for (auto& e : train_edges) {
update_graphs(e, graphs);
}
// feature computation
if (feature.compare("nverts") == 0) {
unordered_map<uint32_t,uint32_t> number_of_nodes;
for (uint32_t i = 0; i < num_graphs; i++) {
number_of_nodes[i] = get_number_of_nodes(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << number_of_nodes[i] << endl;
}
} else if (feature.compare("nedges") == 0) {
unordered_map<uint32_t,uint32_t> number_of_edges;
for (uint32_t i = 0; i < num_graphs; i++) {
number_of_edges[i] = get_number_of_edges(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << number_of_edges[i] << endl;
}
} else if (feature.compare("density") == 0) {
unordered_map<uint32_t,float> d;
for (uint32_t i = 0; i < num_graphs; i++) {
d[i] = get_density(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << d[i] << endl;
}
} else if (feature.compare("diameter") == 0) {
unordered_map<uint32_t,uint32_t> diameter;
for (uint32_t i = 0; i < num_graphs; i++) {
diameter[i] = get_diameter(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << diameter[i] << endl;
}
} else if (feature.compare("avg-path-length") == 0) {
unordered_map<uint32_t,float> avg;
for (uint32_t i = 0; i < num_graphs; i++) {
avg[i] = get_average_path_length(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << avg[i] << endl;
}
} else if (feature.compare("effective-diameter") == 0) {
unordered_map<uint32_t,float> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_effective_diameter(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("avg-degree") == 0) {
unordered_map<uint32_t,float> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_average_degree(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("max-degree") == 0) {
unordered_map<uint32_t,uint32_t> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_max_degree(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("90pct-degree") == 0) {
unordered_map<uint32_t,float> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_90pct_degree(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("avg-distinct-degree") == 0) {
unordered_map<uint32_t,float> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_average_distinct_degree(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("max-distinct-degree") == 0) {
unordered_map<uint32_t,uint32_t> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_max_distinct_degree(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("90pct-distinct-degree") == 0) {
unordered_map<uint32_t,float> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_90pct_distinct_degree(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("avg-eccentricity") == 0) {
unordered_map<uint32_t,float> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_average_eccentricity(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("max-eccentricity") == 0) {
unordered_map<uint32_t,uint32_t> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_max_eccentricity(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("radius") == 0) {
unordered_map<uint32_t,uint32_t> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_radius(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("90pct-eccentricity") == 0) {
unordered_map<uint32_t,float> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_90pct_eccentricity(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else {
cout << "Unknown feature: " << feature << ". Available features:" << endl;
cout << "\tnverts" << endl;
cout << "\tnedges" << endl;
cout << "\tdensity" << endl;
cout << "\tdiameter" << endl;
cout << "\tavg-path-length" << endl;
cout << "\teffective-diameter" << endl;
cout << "\tavg-degree" << endl;
cout << "\tmax-degree" << endl;
cout << "\t90pct-degree" << endl;
cout << "\tavg-distinct-degree" << endl;
cout << "\tmax-distinct-degree" << endl;
cout << "\t90pct-distinct-degree" << endl;
cout << "\tavg-eccentricity" << endl;
cout << "\tmax-eccentricity" << endl;
cout << "\tradius" << endl;
cout << "\t90pct-eccentricity" << endl;
exit(-1);
}
return 0;
}
<commit_msg>path len, degree, ecc distributions<commit_after>/*
* Copyright 2016 Emaad Ahmed Manzoor
* License: Apache License, Version 2.0
* http://www3.cs.stonybrook.edu/~emanzoor/streamspot/
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <deque>
#include <iostream>
#include <queue>
#include <random>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "cluster.h"
#include "docopt.h"
#include "graph.h"
#include "hash.h"
#include "io.h"
#include "param.h"
#include "simhash.h"
#include "streamhash.h"
using namespace std;
static const char USAGE[] =
R"(StreamSpot.
Usage:
streamspot --edges=<edge file>
--feature=<feature>
streamspot (-h | --help)
Options:
-h, --help Show this screen.
--edges=<edge file> Incoming stream of edges.
--feature=<feature> Feature to compute for each graph.
)";
int main(int argc, char *argv[]) {
std::cout.precision(3);
map<string, docopt::value> args = docopt::docopt(USAGE, { argv + 1, argv + argc });
string edge_file(args["--edges"].asString());
string feature(args["--feature"].asString());
cout << "StreamSpot (";
cout << "Edges=" << edge_file << " ";
cout << "Feature=" << feature << "";
cout << ")" << endl;
unordered_set<uint32_t> train_gids;
for (uint32_t i = 0; i < 600; i++) {
train_gids.insert(i);
}
unordered_set<uint32_t> scenarios;
for (uint32_t i = 0; i < 6; i++) {
scenarios.insert(i);
}
uint32_t num_graphs;
uint32_t num_test_edges;
vector<edge> train_edges;
unordered_map<uint32_t,vector<edge>> test_edges;
tie(num_graphs, train_edges, test_edges, num_test_edges) =
read_edges(edge_file, train_gids, scenarios);
if (num_graphs == 0) {
cout << "0 graphs in file" << endl;
exit(-1);
}
vector<graph> graphs(num_graphs);
cout << "Constructing " << num_graphs << " graphs..." << endl;
for (auto& e : train_edges) {
update_graphs(e, graphs);
}
// feature computation
if (feature.compare("nverts") == 0) {
unordered_map<uint32_t,uint32_t> number_of_nodes;
for (uint32_t i = 0; i < num_graphs; i++) {
number_of_nodes[i] = get_number_of_nodes(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << number_of_nodes[i] << endl;
}
} else if (feature.compare("nedges") == 0) {
unordered_map<uint32_t,uint32_t> number_of_edges;
for (uint32_t i = 0; i < num_graphs; i++) {
number_of_edges[i] = get_number_of_edges(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << number_of_edges[i] << endl;
}
} else if (feature.compare("density") == 0) {
unordered_map<uint32_t,float> d;
for (uint32_t i = 0; i < num_graphs; i++) {
d[i] = get_density(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << d[i] << endl;
}
} else if (feature.compare("diameter") == 0) {
unordered_map<uint32_t,uint32_t> diameter;
for (uint32_t i = 0; i < num_graphs; i++) {
diameter[i] = get_diameter(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << diameter[i] << endl;
}
} else if (feature.compare("avg-path-length") == 0) {
unordered_map<uint32_t,float> avg;
for (uint32_t i = 0; i < num_graphs; i++) {
avg[i] = get_average_path_length(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << avg[i] << endl;
}
} else if (feature.compare("path-length-distribution") == 0) {
unordered_map<uint32_t,vector<uint32_t>> d;
for (uint32_t i = 0; i < num_graphs; i++) {
d[i] = get_path_lengths(graphs[i]);
cout << i << "\t";
for (uint32_t j = 0; j < d[i].size(); j++) {
cout << fixed << static_cast<int>(d[i][j]) << "\t";
}
cout << endl;
}
} else if (feature.compare("effective-diameter") == 0) {
unordered_map<uint32_t,float> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_effective_diameter(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("avg-degree") == 0) {
unordered_map<uint32_t,float> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_average_degree(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("degree-distribution") == 0) {
unordered_map<uint32_t,vector<uint32_t>> d;
for (uint32_t i = 0; i < num_graphs; i++) {
d[i] = get_degrees(graphs[i]);
cout << i << "\t";
for (uint32_t j = 0; j < d[i].size(); j++) {
cout << fixed << static_cast<int>(d[i][j]) << "\t";
}
cout << endl;
}
} else if (feature.compare("max-degree") == 0) {
unordered_map<uint32_t,uint32_t> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_max_degree(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("90pct-degree") == 0) {
unordered_map<uint32_t,float> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_90pct_degree(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("avg-distinct-degree") == 0) {
unordered_map<uint32_t,float> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_average_distinct_degree(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("max-distinct-degree") == 0) {
unordered_map<uint32_t,uint32_t> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_max_distinct_degree(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("90pct-distinct-degree") == 0) {
unordered_map<uint32_t,float> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_90pct_distinct_degree(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("avg-eccentricity") == 0) {
unordered_map<uint32_t,float> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_average_eccentricity(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("eccentricity-distribution") == 0) {
unordered_map<uint32_t,vector<uint32_t>> d;
for (uint32_t i = 0; i < num_graphs; i++) {
d[i] = get_eccentricities(graphs[i]);
cout << i << "\t";
for (uint32_t j = 0; j < d[i].size(); j++) {
cout << fixed << static_cast<int>(d[i][j]) << "\t";
}
cout << endl;
}
} else if (feature.compare("max-eccentricity") == 0) {
unordered_map<uint32_t,uint32_t> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_max_eccentricity(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("radius") == 0) {
unordered_map<uint32_t,uint32_t> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_radius(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else if (feature.compare("90pct-eccentricity") == 0) {
unordered_map<uint32_t,float> ed;
for (uint32_t i = 0; i < num_graphs; i++) {
ed[i] = get_90pct_eccentricity(graphs[i]);
}
for (uint32_t i = 0; i < num_graphs; i++) {
cout << i << "\t" << fixed << ed[i] << endl;
}
} else {
cout << "Unknown feature: " << feature << ". Available features:" << endl;
cout << "\tnverts" << endl;
cout << "\tnedges" << endl;
cout << "\tdensity" << endl;
cout << "\tdiameter" << endl;
cout << "\tavg-path-length" << endl;
cout << "\tpath-length-distribution" << endl;
cout << "\teffective-diameter" << endl;
cout << "\tavg-degree" << endl;
cout << "\tdegree-distribution" << endl;
cout << "\tmax-degree" << endl;
cout << "\t90pct-degree" << endl;
cout << "\tavg-distinct-degree" << endl;
cout << "\tmax-distinct-degree" << endl;
cout << "\t90pct-distinct-degree" << endl;
cout << "\tavg-eccentricity" << endl;
cout << "\teccentricity-distribution" << endl;
cout << "\tmax-eccentricity" << endl;
cout << "\tradius" << endl;
cout << "\t90pct-eccentricity" << endl;
exit(-1);
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ScriptNameResolverImpl.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: dfoster $ $Date: 2002-10-24 13:57:02 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <vector>
#include <cppuhelper/implementationentry.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <util/util.hxx>
#include <util/scriptingconstants.hxx>
#include "ScriptNameResolverImpl.hxx"
#include "ScriptRuntimeManager.hxx"
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::drafts::com::sun::star::script::framework;
namespace scripting_runtimemgr
{
const sal_Char* const LANGUAGE_TO_RESOLVE_ON = "Java"; // should be configurable
OUString nrs_implName = OUString::createFromAscii(
"drafts.com.sun.star.script.framework.DefaultScriptNameResolver" );
OUString nrs_serviceName = OUString::createFromAscii(
"drafts.com.sun.star.script.framework.DefaultScriptNameResolver" );
Sequence< OUString > nrs_serviceNames = Sequence< OUString >( &nrs_serviceName, 1 );
extern ::rtl_StandardModuleCount s_moduleCount;
// define storages to search
static ::std::vector< sal_Int32 >* m_pSearchIDs = NULL;
//*************************************************************************
ScriptNameResolverImpl::ScriptNameResolverImpl(
const Reference< XComponentContext > & xContext ) :
m_xContext( xContext ), m_StorageFactory( xContext )
{
OSL_TRACE( "< ScriptNameResolverImpl ctor called >\n" );
if( !m_pSearchIDs )
{
osl::Guard< osl::Mutex > aGuard( m_mutex );
if( !m_pSearchIDs )
{
scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
scripting_constants::ScriptingConstantsPool::instance();
m_pSearchIDs = new ::std::vector< sal_Int32 >();
m_pSearchIDs->push_back( scriptingConstantsPool.DOC_STORAGE_ID_NOT_SET );
m_pSearchIDs->push_back( scriptingConstantsPool.USER_STORAGE_ID );
m_pSearchIDs->push_back( scriptingConstantsPool.SHARED_STORAGE_ID );
}
}
s_moduleCount.modCnt.acquire( &s_moduleCount.modCnt );
}
//*************************************************************************
ScriptNameResolverImpl::~ScriptNameResolverImpl()
{
OSL_TRACE( "< ScriptNameResolverImpl dtor called >\n" );
s_moduleCount.modCnt.release( &s_moduleCount.modCnt );
}
//*************************************************************************
Reference< XInterface > ScriptNameResolverImpl::resolve(
const ::rtl::OUString & scriptURI, Any& invocationCtx )
throw ( lang::IllegalArgumentException, script::CannotConvertException, RuntimeException )
{
Reference< XInterface > resolvedName;
Reference< beans::XPropertySet > xPropSetScriptingContext;
OSL_TRACE( "ScriptNameResolverImpl::resolve: in resolve - start" );
if ( sal_False == ( invocationCtx >>= xPropSetScriptingContext ) )
{
throw RuntimeException( OUSTR(
"ScriptNameResolverImpl::resolve : unable to get XScriptingContext from param" ),
Reference< XInterface > () );
}
Any any;
OUString docUri;
sal_Int32 docSid;
try
{
scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
scripting_constants::ScriptingConstantsPool::instance();
any = xPropSetScriptingContext->getPropertyValue(
scriptingConstantsPool.DOC_URI );
OSL_TRACE( "ScriptNameResolverImpl::resolve: in resolve - got anyUri" );
if ( sal_False == ( any >>= docUri ) )
{
throw RuntimeException( OUSTR(
"ScriptNameResolverImpl::resolve : unable to get doc Uri from xPropSetScriptingContext" ),
Reference< XInterface > () );
}
any = xPropSetScriptingContext->getPropertyValue(
scriptingConstantsPool.DOC_STORAGE_ID );
if ( sal_False == ( any >>= docSid ) )
{
throw RuntimeException( OUSTR(
"ScriptNameResolverImpl::resolve : unable to get doc storage id from xPropSetScriptingContext" ),
Reference< XInterface > () );
}
}
catch ( Exception & e )
{
OUString temp = OUSTR(
"ScriptNameResolverImpl::resolve : problem with getPropertyValue" );
throw RuntimeException( temp.concat( e.Message ),
Reference< XInterface > () );
}
#ifdef _DEBUG
catch ( ... )
{
throw RuntimeException( OUSTR(
"ScriptNameResolverImpl::resolve Unknown Exception caught - RuntimeException rethrown" ),
Reference< XInterface > () );
}
#endif
#ifdef _DEBUG
::rtl::OString docUriO(
::rtl::OUStringToOString( docUri , RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr,
"ScriptNameResolverImpl::resolve: *** >>> DOC URI: %s, doc sid is %d\n",
docUriO.pData->buffer, docSid );
#endif
OSL_TRACE( "ScriptNameResolverImpl::resolve Starting..." );
::std::vector< sal_Int32 >& m_vSearchIDs = *m_pSearchIDs;
m_vSearchIDs[ 0 ] = docSid;
::std::vector< sal_Int32 >::const_iterator iter;
::std::vector< sal_Int32 >::const_iterator iterEnd = m_vSearchIDs.end();
for ( iter = m_vSearchIDs.begin() ; iter != iterEnd; ++iter )
{
try
{
OSL_TRACE( "** about to resolve from storage using id %d from vector of size %d",
*iter, m_vSearchIDs.size() );
if ( ( resolvedName = resolveURIFromStorageID( *iter, scriptURI ) ).is() )
{
OSL_TRACE( "found match in uri from storage %d", *iter );
break;
}
}
catch ( Exception & e )
{
OSL_TRACE( "Exception thrown by storage %d, failed to match uri: %s",
*iter,
::rtl::OUStringToOString( e.Message,
RTL_TEXTENCODING_ASCII_US ).pData->buffer );
}
#ifdef _DEBUG
catch ( ... )
{
OSL_TRACE( "unknown exception thrown by storage %d, failed to match uri",
*iter );
}
#endif
}
return resolvedName;
}
//*************************************************************************
OUString SAL_CALL
ScriptNameResolverImpl::getImplementationName( )
throw( RuntimeException )
{
return nrs_implName;
}
//*************************************************************************
sal_Bool SAL_CALL
ScriptNameResolverImpl::supportsService( const OUString& serviceName )
throw( RuntimeException )
{
OUString const * pNames = nrs_serviceNames.getConstArray();
for ( sal_Int32 nPos = nrs_serviceNames.getLength(); nPos--; )
{
if ( serviceName.equals( pNames[ nPos ] ) )
{
return sal_True;
}
}
return sal_False;
}
//*************************************************************************
Reference< XInterface >
ScriptNameResolverImpl::resolveURIFromStorageID
( sal_Int32 sid, const ::rtl::OUString& scriptURI )
SAL_THROW ( ( lang::IllegalArgumentException, RuntimeException ) )
{
Reference< XInterface > resolvedName;
scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
scripting_constants::ScriptingConstantsPool::instance();
if ( sid == scriptingConstantsPool.DOC_STORAGE_ID_NOT_SET )
{
OSL_TRACE( "@@@@ **** ScriptNameResolverImpl::resolve DOC_STORAGE_ID_NOT_SET" );
return resolvedName;
}
try
{
Reference< storage::XScriptInfoAccess > storage =
m_StorageFactory.getStorageInstance( sid );
validateXRef( storage,
"ScriptNameResolverImpl::resolveURIFromStorageID: cannot get XScriptInfoAccess" );
Sequence< Reference< storage::XScriptInfo > > results =
storage->getImplementations( scriptURI );
const sal_Int32 length = results.getLength();
if ( !length )
{
return resolvedName;
}
OSL_TRACE( "ScriptNameResolverImpl::resolve Got some results..." );
for ( sal_Int32 index = 0;index < length;index++ )
{
Reference< storage::XScriptInfo > uri = results[ index ];
#ifdef _DEBUG
::rtl::OString locationO( ::rtl::OUStringToOString( uri->getScriptLocation(),
RTL_TEXTENCODING_ASCII_US ) );
::rtl::OString languageO( ::rtl::OUStringToOString( uri->getLanguage(),
RTL_TEXTENCODING_ASCII_US ) );
::rtl::OString functionName( ::rtl::OUStringToOString( uri->getFunctionName(),
RTL_TEXTENCODING_ASCII_US ) );
::rtl::OString logicalName( ::rtl::OUStringToOString( uri->getLogicalName(),
RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "[%d] URI, {location = %s}, {language = %s}, {funtionName = %s}, {logicalName = %s}\n",
index, locationO.pData->buffer, languageO.pData->buffer,
functionName.pData->buffer, logicalName.pData->buffer );
#endif
// just choose first one that has language=LANGUAGE_TO_RESOLVE_ON
::rtl::OUString language( uri->getLanguage() );
if ( ( language.compareToAscii( LANGUAGE_TO_RESOLVE_ON ) == 0 ) )
{
OSL_TRACE( "Found desired language\n" );
resolvedName = uri;
break;
}
}
}
catch ( lang::IllegalArgumentException & iae )
{
OUString temp = OUSTR(
"ScriptRuntimeManager::resolveURIFromStorageID IllegalArgumentException: " );
throw lang::IllegalArgumentException( temp.concat( iae.Message ),
Reference< XInterface > (),
iae.ArgumentPosition );
}
catch ( RuntimeException & re )
{
OUString temp = OUSTR(
"ScriptRuntimeManager::resolveURIFromStorageID RuntimeException: " );
throw RuntimeException( temp.concat( re.Message ),
Reference< XInterface > () );
}
catch ( Exception & e )
{
OUString temp = OUSTR(
"ScriptNameResolverImpl::resolveURIFromStorageID : Exception caught - RuntimeException rethrown" );
throw RuntimeException( temp.concat( e.Message ),
Reference< XInterface > () );
}
#ifdef _DEBUG
catch ( ... )
{
throw RuntimeException( OUSTR(
"ScriptNameResolverImpl::resolveURIFromStorageID Unknown exception caught - RuntimeException rethrown" ),
Reference< XInterface > () );
}
#endif
return resolvedName;
}
//*************************************************************************
Sequence<OUString> SAL_CALL
ScriptNameResolverImpl::getSupportedServiceNames( )
throw( RuntimeException )
{
return nrs_serviceNames;
}
//*************************************************************************
Reference< XInterface > SAL_CALL scriptnri_create(
Reference< XComponentContext > const & xComponentContext )
SAL_THROW( ( Exception ) )
{
return ( cppu::OWeakObject * ) new ScriptNameResolverImpl( xComponentContext );
}
//*************************************************************************
Sequence< OUString > scriptnri_getSupportedServiceNames() SAL_THROW( () )
{
return nrs_serviceNames;
}
//*************************************************************************
OUString scriptnri_getImplementationName() SAL_THROW( () )
{
return nrs_implName;
}
} // namespace scripting_runtimemgr
<commit_msg>resolved storage ID set on resolved context<commit_after>/*************************************************************************
*
* $RCSfile: ScriptNameResolverImpl.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: lkovacs $ $Date: 2002-10-30 14:25:26 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <vector>
#include <cppuhelper/implementationentry.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <util/util.hxx>
#include <util/scriptingconstants.hxx>
#include "ScriptNameResolverImpl.hxx"
#include "ScriptRuntimeManager.hxx"
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::drafts::com::sun::star::script::framework;
namespace scripting_runtimemgr
{
const sal_Char* const LANGUAGE_TO_RESOLVE_ON = "Java"; // should be configurable
OUString nrs_implName = OUString::createFromAscii(
"drafts.com.sun.star.script.framework.DefaultScriptNameResolver" );
OUString nrs_serviceName = OUString::createFromAscii(
"drafts.com.sun.star.script.framework.DefaultScriptNameResolver" );
Sequence< OUString > nrs_serviceNames = Sequence< OUString >( &nrs_serviceName, 1 );
extern ::rtl_StandardModuleCount s_moduleCount;
// define storages to search
static ::std::vector< sal_Int32 >* m_pSearchIDs = NULL;
//*************************************************************************
ScriptNameResolverImpl::ScriptNameResolverImpl(
const Reference< XComponentContext > & xContext ) :
m_xContext( xContext ), m_StorageFactory( xContext )
{
OSL_TRACE( "< ScriptNameResolverImpl ctor called >\n" );
if( !m_pSearchIDs )
{
osl::Guard< osl::Mutex > aGuard( m_mutex );
if( !m_pSearchIDs )
{
scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
scripting_constants::ScriptingConstantsPool::instance();
m_pSearchIDs = new ::std::vector< sal_Int32 >();
m_pSearchIDs->push_back( scriptingConstantsPool.DOC_STORAGE_ID_NOT_SET );
m_pSearchIDs->push_back( scriptingConstantsPool.USER_STORAGE_ID );
m_pSearchIDs->push_back( scriptingConstantsPool.SHARED_STORAGE_ID );
}
}
s_moduleCount.modCnt.acquire( &s_moduleCount.modCnt );
}
//*************************************************************************
ScriptNameResolverImpl::~ScriptNameResolverImpl()
{
OSL_TRACE( "< ScriptNameResolverImpl dtor called >\n" );
s_moduleCount.modCnt.release( &s_moduleCount.modCnt );
}
//*************************************************************************
Reference< XInterface > ScriptNameResolverImpl::resolve(
const ::rtl::OUString & scriptURI, Any& invocationCtx )
throw ( lang::IllegalArgumentException, script::CannotConvertException, RuntimeException )
{
Reference< XInterface > resolvedName;
Reference< beans::XPropertySet > xPropSetScriptingContext;
scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
scripting_constants::ScriptingConstantsPool::instance();
OSL_TRACE( "ScriptNameResolverImpl::resolve: in resolve - start" );
if ( sal_False == ( invocationCtx >>= xPropSetScriptingContext ) )
{
throw RuntimeException( OUSTR(
"ScriptNameResolverImpl::resolve : unable to get XScriptingContext from param" ),
Reference< XInterface > () );
}
Any any;
OUString docUri;
sal_Int32 docSid;
try
{
any = xPropSetScriptingContext->getPropertyValue(
scriptingConstantsPool.DOC_URI );
OSL_TRACE( "ScriptNameResolverImpl::resolve: in resolve - got anyUri" );
if ( sal_False == ( any >>= docUri ) )
{
throw RuntimeException( OUSTR(
"ScriptNameResolverImpl::resolve : unable to get doc Uri from xPropSetScriptingContext" ),
Reference< XInterface > () );
}
any = xPropSetScriptingContext->getPropertyValue(
scriptingConstantsPool.DOC_STORAGE_ID );
if ( sal_False == ( any >>= docSid ) )
{
throw RuntimeException( OUSTR(
"ScriptNameResolverImpl::resolve : unable to get doc storage id from xPropSetScriptingContext" ),
Reference< XInterface > () );
}
}
catch ( Exception & e )
{
OUString temp = OUSTR(
"ScriptNameResolverImpl::resolve : problem with getPropertyValue" );
throw RuntimeException( temp.concat( e.Message ),
Reference< XInterface > () );
}
#ifdef _DEBUG
catch ( ... )
{
throw RuntimeException( OUSTR(
"ScriptNameResolverImpl::resolve Unknown Exception caught - RuntimeException rethrown" ),
Reference< XInterface > () );
}
#endif
#ifdef _DEBUG
::rtl::OString docUriO(
::rtl::OUStringToOString( docUri , RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr,
"ScriptNameResolverImpl::resolve: *** >>> DOC URI: %s, doc sid is %d\n",
docUriO.pData->buffer, docSid );
#endif
OSL_TRACE( "ScriptNameResolverImpl::resolve Starting..." );
::std::vector< sal_Int32 >& m_vSearchIDs = *m_pSearchIDs;
m_vSearchIDs[ 0 ] = docSid;
::std::vector< sal_Int32 >::const_iterator iter;
::std::vector< sal_Int32 >::const_iterator iterEnd = m_vSearchIDs.end();
for ( iter = m_vSearchIDs.begin() ; iter != iterEnd; ++iter )
{
try
{
OSL_TRACE( "** about to resolve from storage using id %d from vector of size %d",
*iter, m_vSearchIDs.size() );
if ( ( resolvedName = resolveURIFromStorageID( *iter, scriptURI ) ).is() )
{
OSL_TRACE( "found match in uri from storage %d", *iter );
xPropSetScriptingContext->setPropertyValue(
scriptingConstantsPool.RESOLVED_STORAGE_ID, makeAny(*iter) );
break;
}
}
catch ( beans::UnknownPropertyException & e )
{
OUString temp = OUSTR(
"ScriptNameResolverImpl::resolve : UnknownPropertyException" );
throw RuntimeException( temp.concat( e.Message ),
Reference< XInterface > () );
}
catch ( beans::PropertyVetoException & e )
{
OUString temp = OUSTR(
"ScriptNameResolverImpl::resolve : PropertyVetoException " );
throw RuntimeException( temp.concat( e.Message ),
Reference< XInterface > () );
}
catch ( lang::IllegalArgumentException & e )
{
OUString temp = OUSTR(
"ScriptNameResolverImpl::resolve : IllegalArgumentException " );
throw RuntimeException( temp.concat( e.Message ),
Reference< XInterface > () );
}
catch ( lang::WrappedTargetException & e )
{
OUString temp = OUSTR(
"ScriptNameResolverImpl::resolve : WrappedTargetException " );
throw RuntimeException( temp.concat( e.Message ),
Reference< XInterface > () );
}
catch ( Exception & e )
{
OSL_TRACE( "Exception thrown by storage %d, failed to match uri: %s",
*iter,
::rtl::OUStringToOString( e.Message,
RTL_TEXTENCODING_ASCII_US ).pData->buffer );
OUString temp = OUSTR(
"ScriptNameResolverImpl::resolve : unknown exception" );
throw RuntimeException( temp.concat( e.Message ),
Reference< XInterface > () );
}
#ifdef _DEBUG
catch ( ... )
{
OSL_TRACE( "unknown exception thrown by storage %d, failed to match uri",
*iter );
OUString temp = OUSTR(
"ScriptNameResolverImpl::resolve Unknown exception caught - RuntimeException rethrown" );
throw RuntimeException( temp,
Reference< XInterface > () );
}
#endif
}
return resolvedName;
}
//*************************************************************************
OUString SAL_CALL
ScriptNameResolverImpl::getImplementationName( )
throw( RuntimeException )
{
return nrs_implName;
}
//*************************************************************************
sal_Bool SAL_CALL
ScriptNameResolverImpl::supportsService( const OUString& serviceName )
throw( RuntimeException )
{
OUString const * pNames = nrs_serviceNames.getConstArray();
for ( sal_Int32 nPos = nrs_serviceNames.getLength(); nPos--; )
{
if ( serviceName.equals( pNames[ nPos ] ) )
{
return sal_True;
}
}
return sal_False;
}
//*************************************************************************
Reference< XInterface >
ScriptNameResolverImpl::resolveURIFromStorageID
( sal_Int32 sid, const ::rtl::OUString& scriptURI )
SAL_THROW ( ( lang::IllegalArgumentException, RuntimeException ) )
{
Reference< XInterface > resolvedName;
scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
scripting_constants::ScriptingConstantsPool::instance();
if ( sid == scriptingConstantsPool.DOC_STORAGE_ID_NOT_SET )
{
OSL_TRACE( "@@@@ **** ScriptNameResolverImpl::resolve DOC_STORAGE_ID_NOT_SET" );
return resolvedName;
}
try
{
Reference< storage::XScriptInfoAccess > storage =
m_StorageFactory.getStorageInstance( sid );
validateXRef( storage,
"ScriptNameResolverImpl::resolveURIFromStorageID: cannot get XScriptInfoAccess" );
Sequence< Reference< storage::XScriptInfo > > results =
storage->getImplementations( scriptURI );
const sal_Int32 length = results.getLength();
if ( !length )
{
return resolvedName;
}
OSL_TRACE( "ScriptNameResolverImpl::resolve Got some results..." );
for ( sal_Int32 index = 0;index < length;index++ )
{
Reference< storage::XScriptInfo > uri = results[ index ];
#ifdef _DEBUG
::rtl::OString locationO( ::rtl::OUStringToOString( uri->getScriptLocation(),
RTL_TEXTENCODING_ASCII_US ) );
::rtl::OString languageO( ::rtl::OUStringToOString( uri->getLanguage(),
RTL_TEXTENCODING_ASCII_US ) );
::rtl::OString functionName( ::rtl::OUStringToOString( uri->getFunctionName(),
RTL_TEXTENCODING_ASCII_US ) );
::rtl::OString logicalName( ::rtl::OUStringToOString( uri->getLogicalName(),
RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "[%d] URI, {location = %s}, {language = %s}, {funtionName = %s}, {logicalName = %s}\n",
index, locationO.pData->buffer, languageO.pData->buffer,
functionName.pData->buffer, logicalName.pData->buffer );
#endif
// just choose first one that has language=LANGUAGE_TO_RESOLVE_ON
::rtl::OUString language( uri->getLanguage() );
if ( ( language.compareToAscii( LANGUAGE_TO_RESOLVE_ON ) == 0 ) )
{
OSL_TRACE( "Found desired language\n" );
resolvedName = uri;
break;
}
}
}
catch ( lang::IllegalArgumentException & iae )
{
OUString temp = OUSTR(
"ScriptRuntimeManager::resolveURIFromStorageID IllegalArgumentException: " );
throw lang::IllegalArgumentException( temp.concat( iae.Message ),
Reference< XInterface > (),
iae.ArgumentPosition );
}
catch ( RuntimeException & re )
{
OUString temp = OUSTR(
"ScriptRuntimeManager::resolveURIFromStorageID RuntimeException: " );
throw RuntimeException( temp.concat( re.Message ),
Reference< XInterface > () );
}
catch ( Exception & e )
{
OUString temp = OUSTR(
"ScriptNameResolverImpl::resolveURIFromStorageID : Exception caught - RuntimeException rethrown" );
throw RuntimeException( temp.concat( e.Message ),
Reference< XInterface > () );
}
#ifdef _DEBUG
catch ( ... )
{
throw RuntimeException( OUSTR(
"ScriptNameResolverImpl::resolveURIFromStorageID Unknown exception caught - RuntimeException rethrown" ),
Reference< XInterface > () );
}
#endif
return resolvedName;
}
//*************************************************************************
Sequence<OUString> SAL_CALL
ScriptNameResolverImpl::getSupportedServiceNames( )
throw( RuntimeException )
{
return nrs_serviceNames;
}
//*************************************************************************
Reference< XInterface > SAL_CALL scriptnri_create(
Reference< XComponentContext > const & xComponentContext )
SAL_THROW( ( Exception ) )
{
return ( cppu::OWeakObject * ) new ScriptNameResolverImpl( xComponentContext );
}
//*************************************************************************
Sequence< OUString > scriptnri_getSupportedServiceNames() SAL_THROW( () )
{
return nrs_serviceNames;
}
//*************************************************************************
OUString scriptnri_getImplementationName() SAL_THROW( () )
{
return nrs_implName;
}
} // namespace scripting_runtimemgr
<|endoftext|> |
<commit_before><commit_msg>Fixed userlevel check on parameter observation.<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2016 neurodata (http://neurodata.io/)
* Written by Disa Mhembere (disa@jhu.edu)
*
* This file is part of knor
*
* 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 CURRENT_KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cassert>
#include "io.hpp"
#include "util.hpp"
#include "clusters.hpp"
namespace knor { namespace base {
void clusters::clear() {
std::fill(means.begin(), means.end(), 0);
std::fill(num_members_v.begin(), num_members_v.end(), 0);
std::fill(complete_v.begin(), complete_v.end(), false);
}
/** \param idx the cluster index.
*/
void clusters::set_mean(const kmsvector& mean, const int idx) {
if (idx == -1) { // Set all means
means = mean;
} else {
std::copy(mean.begin(), mean.end(),
this->means.begin()+(idx*ncol));
}
}
void clusters::set_mean(const double* mean, const int idx) {
if (idx == -1) { // Set all means
if (means.size() != (ncol*nclust))
means.resize(ncol*nclust);
std::copy(&(mean[0]), &(mean[ncol*nclust]), this->means.begin());
} else {
std::copy(&(mean[0]), &(mean[ncol]), this->means.begin()+(idx*ncol));
}
}
void clusters::finalize(const unsigned idx) {
if (is_complete(idx)) {
return;
}
if (num_members_v[idx] > 1) { // Less than 2 is the same result
for (unsigned i = 0; i < ncol; i++) {
means[(idx*ncol)+i] /= double(num_members_v[idx]);
}
}
complete_v[idx] = true;
}
void clusters::unfinalize(const unsigned idx) {
if (!is_complete(idx)) {
return;
}
complete_v[idx] = false;
for (unsigned col = 0; col < ncol; col++) {
this->means[(ncol*idx) + col] *= (double)num_members_v[idx];
}
}
void clusters::finalize_all() {
for (unsigned c = 0; c < get_nclust(); c++)
finalize(c);
}
void clusters::unfinalize_all() {
for (unsigned c = 0; c < get_nclust(); c++)
unfinalize(c);
}
void clusters::set_num_members_v(const size_t* arg) {
std::copy(&(arg[0]), &(arg[nclust]), num_members_v.begin());
}
clusters& clusters::operator=(clusters& other) {
this->means = other.get_means();
this->num_members_v = other.get_num_members_v();
this->ncol = other.get_ncol();
this->nclust = other.get_nclust();
return *this;
}
bool clusters::operator==(clusters& other) {
return (get_ncol() == other.get_ncol() &&
get_nclust() == other.get_nclust() &&
v_eq(get_num_members_v(), other.get_num_members_v()) &&
v_eq(get_means(), other.get_means())
);
}
clusters& clusters::operator+=(clusters& rhs) {
for (unsigned i = 0; i < size(); i++)
this->means[i] += rhs[i];
for (unsigned idx = 0; idx < nclust; idx++)
num_members_peq(rhs.get_num_members(idx), idx);
return *this;
}
void clusters::peq(ptr rhs) {
assert(rhs->size() == size());
for (unsigned i = 0; i < size(); i++)
this->means[i] += rhs->get(i);
for (unsigned idx = 0; idx < nclust; idx++)
num_members_peq(rhs->get_num_members(idx), idx);
}
void clusters::means_peq(const double* other) {
for (unsigned i = 0; i < size(); i++)
this->means[i] += other[i];
}
void clusters::num_members_v_peq(const size_t* other) {
for (unsigned i = 0; i < num_members_v.size(); i++)
this->num_members_v[i] += other[i];
}
// Begin Helpers //
const void clusters::print_means() const {
for (unsigned cl_idx = 0; cl_idx < get_nclust(); cl_idx++) {
#ifndef BIND
std::cout << "#memb = " << get_num_members(cl_idx) << " ";
#endif
print_arr<double>(&(means[cl_idx*ncol]), ncol);
}
#ifndef BIND
std::cout << "\n";
#endif
}
clusters::clusters(const unsigned nclust, const unsigned ncol) {
this->nclust = nclust;
this->ncol = ncol;
means.resize(ncol*nclust);
num_members_v.resize(nclust);
complete_v.assign(nclust, false);
}
clusters::clusters(const unsigned nclust, const unsigned ncol,
const double* means) {
this->nclust = nclust;
this->ncol = ncol;
set_mean(means);
num_members_v.resize(nclust);
complete_v.assign(nclust, true);
}
clusters::clusters(const unsigned nclust, const unsigned ncol,
const kmsvector& means) : clusters(nclust, ncol, &means[0]) {
}
const void clusters::print_membership_count() const {
std::string p = "[ ";
for (unsigned cl_idx = 0; cl_idx < get_nclust(); cl_idx++) {
p += std::to_string(get_num_members(cl_idx)) + " ";
}
p += "]\n";
#ifndef BIND
std::cout << p;
#endif
}
void clusters::scale_centroid(const double factor,
const unsigned idx, const double* member) {
assert(idx < nclust);
for (unsigned col = 0; col < ncol; col++) {
means[(ncol*idx)+col] = ((1-factor)*means[(idx*ncol)+col])
+ (factor*(member[col]));
}
}
// Pruning clusters //
void prune_clusters::reset_s_val_v() {
std::fill(s_val_v.begin(), s_val_v.end(),
std::numeric_limits<double>::max());
}
const void prune_clusters::print_prev_means_v() const {
for (unsigned cl_idx = 0; cl_idx < get_nclust(); cl_idx++) {
print_arr<double>(&(prev_means[cl_idx*ncol]), ncol);
}
#ifndef BIND
std::cout << "\n";
#endif
}
} } // End namespace knor, base
<commit_msg>clusters debugging<commit_after>/*
* Copyright 2016 neurodata (http://neurodata.io/)
* Written by Disa Mhembere (disa@jhu.edu)
*
* This file is part of knor
*
* 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 CURRENT_KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cassert>
#include "io.hpp"
#include "util.hpp"
#include "clusters.hpp"
namespace knor { namespace base {
void clusters::clear() {
std::fill(means.begin(), means.end(), 0);
std::fill(num_members_v.begin(), num_members_v.end(), 0);
std::fill(complete_v.begin(), complete_v.end(), false);
}
/** \param idx the cluster index.
*/
void clusters::set_mean(const kmsvector& mean, const int idx) {
if (idx == -1) { // Set all means
means = mean;
} else {
std::copy(mean.begin(), mean.end(),
this->means.begin()+(idx*ncol));
}
}
void clusters::set_mean(const double* mean, const int idx) {
if (idx == -1) { // Set all means
if (means.size() != (ncol*nclust))
means.resize(ncol*nclust);
std::copy(&(mean[0]), &(mean[ncol*nclust]), this->means.begin());
} else {
std::copy(&(mean[0]), &(mean[ncol]), this->means.begin()+(idx*ncol));
}
}
void clusters::finalize(const unsigned idx) {
if (is_complete(idx)) {
return;
}
if (num_members_v[idx] > 1) { // Less than 2 is the same result
for (unsigned i = 0; i < ncol; i++) {
means[(idx*ncol)+i] /= double(num_members_v[idx]);
}
}
complete_v[idx] = true;
}
void clusters::unfinalize(const unsigned idx) {
if (!is_complete(idx)) {
return;
}
complete_v[idx] = false;
for (unsigned col = 0; col < ncol; col++) {
this->means[(ncol*idx) + col] *= (double)num_members_v[idx];
}
}
void clusters::finalize_all() {
for (unsigned c = 0; c < get_nclust(); c++)
finalize(c);
}
void clusters::unfinalize_all() {
for (unsigned c = 0; c < get_nclust(); c++)
unfinalize(c);
}
void clusters::set_num_members_v(const size_t* arg) {
std::copy(&(arg[0]), &(arg[nclust]), num_members_v.begin());
}
clusters& clusters::operator=(clusters& other) {
this->means = other.get_means();
this->num_members_v = other.get_num_members_v();
this->ncol = other.get_ncol();
this->nclust = other.get_nclust();
return *this;
}
bool clusters::operator==(clusters& other) {
return (get_ncol() == other.get_ncol() &&
get_nclust() == other.get_nclust() &&
v_eq(get_num_members_v(), other.get_num_members_v()) &&
v_eq(get_means(), other.get_means())
);
}
clusters& clusters::operator+=(clusters& rhs) {
for (unsigned i = 0; i < size(); i++)
this->means[i] += rhs[i];
for (unsigned idx = 0; idx < nclust; idx++)
num_members_peq(rhs.get_num_members(idx), idx);
return *this;
}
void clusters::peq(ptr rhs) {
assert(rhs->size() == size());
for (unsigned i = 0; i < size(); i++)
this->means[i] += rhs->get(i);
for (unsigned idx = 0; idx < nclust; idx++)
num_members_peq(rhs->get_num_members(idx), idx);
}
void clusters::means_peq(const double* other) {
for (unsigned i = 0; i < size(); i++)
this->means[i] += other[i];
}
void clusters::num_members_v_peq(const size_t* other) {
for (unsigned i = 0; i < num_members_v.size(); i++)
this->num_members_v[i] += other[i];
}
// Begin Helpers //
const void clusters::print_means() const {
for (unsigned cl_idx = 0; cl_idx < get_nclust(); cl_idx++) {
#ifndef BIND
std::cout << "#memb = " << get_num_members(cl_idx) << " ";
#endif
print_arr<double>(&(means[cl_idx*ncol]), ncol);
}
}
const void h_clusters::print_means() const {
clusters::print_means();
#ifndef BIND
printf("Mean 0 ID: %u\n", zeroid);
printf("Mean 1 ID: %u\n", oneid);
#endif
}
clusters::clusters(const unsigned nclust, const unsigned ncol) {
this->nclust = nclust;
this->ncol = ncol;
means.resize(ncol*nclust);
num_members_v.resize(nclust);
complete_v.assign(nclust, false);
}
clusters::clusters(const unsigned nclust, const unsigned ncol,
const double* means) {
this->nclust = nclust;
this->ncol = ncol;
set_mean(means);
num_members_v.resize(nclust);
complete_v.assign(nclust, true);
}
clusters::clusters(const unsigned nclust, const unsigned ncol,
const kmsvector& means) : clusters(nclust, ncol, &means[0]) {
}
const void clusters::print_membership_count() const {
std::string p = "[ ";
for (unsigned cl_idx = 0; cl_idx < get_nclust(); cl_idx++) {
p += std::to_string(get_num_members(cl_idx)) + " ";
}
p += "]\n";
#ifndef BIND
std::cout << p;
#endif
}
void clusters::scale_centroid(const double factor,
const unsigned idx, const double* member) {
assert(idx < nclust);
for (unsigned col = 0; col < ncol; col++) {
means[(ncol*idx)+col] = ((1-factor)*means[(idx*ncol)+col])
+ (factor*(member[col]));
}
}
// Pruning clusters //
void prune_clusters::reset_s_val_v() {
std::fill(s_val_v.begin(), s_val_v.end(),
std::numeric_limits<double>::max());
}
const void prune_clusters::print_prev_means_v() const {
for (unsigned cl_idx = 0; cl_idx < get_nclust(); cl_idx++) {
print_arr<double>(&(prev_means[cl_idx*ncol]), ncol);
}
#ifndef BIND
std::cout << "\n";
#endif
}
} } // End namespace knor, base
<|endoftext|> |
<commit_before>// -*- mode: C++; c-file-style: "gnu" -*-
// kaddrbook.cpp
// Author: Stefan Taferner <taferner@kde.org>
// This code is under GPL
#include <config.h>
#include "kaddrbook.h"
#ifdef KDEPIM_NEW_DISTRLISTS
#include "distributionlist.h"
#else
#include <kabc/distributionlist.h>
#endif
#include <kapplication.h>
#include <kdebug.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdeversion.h>
#include <kabc/resource.h>
#include <kabc/stdaddressbook.h>
#include <kabc/vcardconverter.h>
#include <kresources/selectdialog.h>
#include <dcopref.h>
#include <dcopclient.h>
#include <qeventloop.h>
#include <qregexp.h>
#include <unistd.h>
//-----------------------------------------------------------------------------
void KAddrBookExternal::openEmail( const QString &addr, QWidget *parent ) {
QString email;
QString name;
KABC::Addressee::parseEmailAddress( addr, name, email );
KABC::AddressBook *ab = KABC::StdAddressBook::self( true );
// force a reload of the address book file so that changes that were made
// by other programs are loaded
ab->asyncLoad();
// if we have to reload the address book then we should also wait until
// it's completely reloaded
#if KDE_IS_VERSION(3,4,89)
// This ugly hack will be removed in 4.0
while ( !ab->loadingHasFinished() ) {
QApplication::eventLoop()->processEvents( QEventLoop::ExcludeUserInput );
// use sleep here to reduce cpu usage
usleep( 100 );
}
#endif
KABC::Addressee::List addressees = ab->findByEmail( email );
if ( addressees.count() > 0 ) {
if ( kapp->dcopClient()->isApplicationRegistered( "kaddressbook" ) ){
//make sure kaddressbook is loaded, otherwise showContactEditor
//won't work as desired, see bug #87233
DCOPRef call ( "kaddressbook", "kaddressbook" );
call.send( "newInstance()" );
} else {
kapp->startServiceByDesktopName( "kaddressbook" );
}
DCOPRef call( "kaddressbook", "KAddressBookIface" );
call.send( "showContactEditor(QString)", addressees.first().uid() );
} else {
//TODO: Enable the better message at the next string unfreeze
#if 0
QString text = i18n("<qt>The email address <b>%1</b> cannot be "
"found in your addressbook.</qt>").arg( email );
#else
QString text = email + " " + i18n( "is not in address book" );
#endif
KMessageBox::information( parent, text, QString::null, "notInAddressBook" );
}
}
//-----------------------------------------------------------------------------
void KAddrBookExternal::addEmail( const QString& addr, QWidget *parent) {
QString email;
QString name;
KABC::Addressee::parseEmailAddress( addr, name, email );
KABC::AddressBook *ab = KABC::StdAddressBook::self( true );
// force a reload of the address book file so that changes that were made
// by other programs are loaded
ab->asyncLoad();
// if we have to reload the address book then we should also wait until
// it's completely reloaded
#if KDE_IS_VERSION(3,4,89)
// This ugly hack will be removed in 4.0
while ( !ab->loadingHasFinished() ) {
QApplication::eventLoop()->processEvents( QEventLoop::ExcludeUserInput );
// use sleep here to reduce cpu usage
usleep( 100 );
}
#endif
KABC::Addressee::List addressees = ab->findByEmail( email );
if ( addressees.isEmpty() ) {
KABC::Addressee a;
a.setNameFromString( name );
a.insertEmail( email, true );
{
KConfig config( "kaddressbookrc" );
config.setGroup( "General" );
int type = config.readNumEntry( "FormattedNameType", 1 );
QString name;
switch ( type ) {
case 1:
name = a.givenName() + " " + a.familyName();
break;
case 2:
name = a.assembledName();
break;
case 3:
name = a.familyName() + ", " + a.givenName();
break;
case 4:
name = a.familyName() + " " + a.givenName();
break;
case 5:
name = a.organization();
break;
default:
name = "";
break;
}
name.simplifyWhiteSpace();
a.setFormattedName( name );
}
if ( !KAddrBookExternal::addAddressee( a ) ) {
KMessageBox::error( parent, i18n("Cannot save to addressbook.") );
} else {
QString text = i18n("<qt>The email address <b>%1</b> was added to your "
"addressbook; you can add more information to this "
"entry by opening the addressbook.</qt>").arg( addr );
KMessageBox::information( parent, text, QString::null, "addedtokabc" );
}
} else {
QString text = i18n("<qt>The email address <b>%1</b> is already in your "
"addressbook.</qt>").arg( addr );
KMessageBox::information( parent, text, QString::null,
"alreadyInAddressBook" );
}
}
void KAddrBookExternal::openAddressBook(QWidget *) {
kapp->startServiceByDesktopName( "kaddressbook" );
}
void KAddrBookExternal::addNewAddressee( QWidget* )
{
kapp->startServiceByDesktopName("kaddressbook");
DCOPRef call("kaddressbook", "KAddressBookIface");
call.send("newContact()");
}
bool KAddrBookExternal::addVCard( const KABC::Addressee& addressee, QWidget *parent )
{
KABC::AddressBook *ab = KABC::StdAddressBook::self( true );
bool inserted = false;
KABC::Addressee::List addressees =
ab->findByEmail( addressee.preferredEmail() );
if ( addressees.isEmpty() ) {
if ( !KAddrBookExternal::addAddressee( addressee ) ) {
KMessageBox::error( parent, i18n("Cannot save to addressbook.") );
inserted = false;
} else {
QString text = i18n("The VCard was added to your addressbook; "
"you can add more information to this "
"entry by opening the addressbook.");
KMessageBox::information( parent, text, QString::null, "addedtokabc" );
inserted = true;
}
} else {
QString text = i18n("The VCard's primary email address is already in "
"your addressbook; however, you may save the VCard "
"into a file and import it into the addressbook "
"manually.");
KMessageBox::information( parent, text );
inserted = true;
}
return inserted;
}
bool KAddrBookExternal::addAddressee( const KABC::Addressee& addr )
{
KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );
#if KDE_IS_VERSION(3,4,89)
// This ugly hack will be removed in 4.0
while ( !addressBook->loadingHasFinished() ) {
QApplication::eventLoop()->processEvents( QEventLoop::ExcludeUserInput );
// use sleep here to reduce cpu usage
usleep( 100 );
}
#endif
// Select a resource
QPtrList<KABC::Resource> kabcResources = addressBook->resources();
QPtrList<KRES::Resource> kresResources;
QPtrListIterator<KABC::Resource> resIt( kabcResources );
KABC::Resource *kabcResource;
while ( ( kabcResource = resIt.current() ) != 0 ) {
++resIt;
if ( !kabcResource->readOnly() ) {
KRES::Resource *res = static_cast<KRES::Resource*>( kabcResource );
if ( res )
kresResources.append( res );
}
}
kabcResource = static_cast<KABC::Resource*>( KRES::SelectDialog::getResource( kresResources, 0 ) );
KABC::Ticket *ticket = addressBook->requestSaveTicket( kabcResource );
bool saved = false;
if ( ticket ) {
KABC::Addressee addressee( addr );
addressee.setResource( kabcResource );
addressBook->insertAddressee( addressee );
saved = addressBook->save( ticket );
if ( !saved )
addressBook->releaseSaveTicket( ticket );
}
addressBook->emitAddressBookChanged();
return saved;
}
QString KAddrBookExternal::expandDistributionList( const QString& listName )
{
if ( listName.isEmpty() )
return QString::null;
const QString lowerListName = listName.lower();
KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );
#ifdef KDEPIM_NEW_DISTRLISTS
KPIM::DistributionList distrList = KPIM::DistributionList::findByName( addressBook, lowerListName, false );
if ( !distrList.isEmpty() ) {
return distrList.emails( addressBook ).join( ", " );
}
#else
KABC::DistributionListManager manager( addressBook );
manager.load();
const QStringList listNames = manager.listNames();
for ( QStringList::ConstIterator it = listNames.begin();
it != listNames.end(); ++it) {
if ( (*it).lower() == lowerListName ) {
const QStringList addressList = manager.list( *it )->emails();
return addressList.join( ", " );
}
}
#endif
return QString::null;
}
<commit_msg>fix use proper error handler to show kabc errors patch provided by Felix Berger. Thanks!<commit_after>// -*- mode: C++; c-file-style: "gnu" -*-
// kaddrbook.cpp
// Author: Stefan Taferner <taferner@kde.org>
// This code is under GPL
#include <config.h>
#include "kaddrbook.h"
#ifdef KDEPIM_NEW_DISTRLISTS
#include "distributionlist.h"
#else
#include <kabc/distributionlist.h>
#endif
#include <kapplication.h>
#include <kdebug.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdeversion.h>
#include <kabc/resource.h>
#include <kabc/stdaddressbook.h>
#include <kabc/vcardconverter.h>
#include <kabc/errorhandler.h>
#include <kresources/selectdialog.h>
#include <dcopref.h>
#include <dcopclient.h>
#include <qeventloop.h>
#include <qregexp.h>
#include <unistd.h>
//-----------------------------------------------------------------------------
void KAddrBookExternal::openEmail( const QString &addr, QWidget *parent ) {
QString email;
QString name;
KABC::Addressee::parseEmailAddress( addr, name, email );
KABC::AddressBook *ab = KABC::StdAddressBook::self( true );
// force a reload of the address book file so that changes that were made
// by other programs are loaded
ab->asyncLoad();
// if we have to reload the address book then we should also wait until
// it's completely reloaded
#if KDE_IS_VERSION(3,4,89)
// This ugly hack will be removed in 4.0
while ( !ab->loadingHasFinished() ) {
QApplication::eventLoop()->processEvents( QEventLoop::ExcludeUserInput );
// use sleep here to reduce cpu usage
usleep( 100 );
}
#endif
KABC::Addressee::List addressees = ab->findByEmail( email );
if ( addressees.count() > 0 ) {
if ( kapp->dcopClient()->isApplicationRegistered( "kaddressbook" ) ){
//make sure kaddressbook is loaded, otherwise showContactEditor
//won't work as desired, see bug #87233
DCOPRef call ( "kaddressbook", "kaddressbook" );
call.send( "newInstance()" );
} else {
kapp->startServiceByDesktopName( "kaddressbook" );
}
DCOPRef call( "kaddressbook", "KAddressBookIface" );
call.send( "showContactEditor(QString)", addressees.first().uid() );
} else {
//TODO: Enable the better message at the next string unfreeze
#if 0
QString text = i18n("<qt>The email address <b>%1</b> cannot be "
"found in your addressbook.</qt>").arg( email );
#else
QString text = email + " " + i18n( "is not in address book" );
#endif
KMessageBox::information( parent, text, QString::null, "notInAddressBook" );
}
}
//-----------------------------------------------------------------------------
void KAddrBookExternal::addEmail( const QString& addr, QWidget *parent) {
QString email;
QString name;
KABC::Addressee::parseEmailAddress( addr, name, email );
KABC::AddressBook *ab = KABC::StdAddressBook::self( true );
ab->setErrorHandler( new KABC::GuiErrorHandler( parent ) );
// force a reload of the address book file so that changes that were made
// by other programs are loaded
ab->asyncLoad();
// if we have to reload the address book then we should also wait until
// it's completely reloaded
#if KDE_IS_VERSION(3,4,89)
// This ugly hack will be removed in 4.0
while ( !ab->loadingHasFinished() ) {
QApplication::eventLoop()->processEvents( QEventLoop::ExcludeUserInput );
// use sleep here to reduce cpu usage
usleep( 100 );
}
#endif
KABC::Addressee::List addressees = ab->findByEmail( email );
if ( addressees.isEmpty() ) {
KABC::Addressee a;
a.setNameFromString( name );
a.insertEmail( email, true );
{
KConfig config( "kaddressbookrc" );
config.setGroup( "General" );
int type = config.readNumEntry( "FormattedNameType", 1 );
QString name;
switch ( type ) {
case 1:
name = a.givenName() + " " + a.familyName();
break;
case 2:
name = a.assembledName();
break;
case 3:
name = a.familyName() + ", " + a.givenName();
break;
case 4:
name = a.familyName() + " " + a.givenName();
break;
case 5:
name = a.organization();
break;
default:
name = "";
break;
}
name.simplifyWhiteSpace();
a.setFormattedName( name );
}
if ( KAddrBookExternal::addAddressee( a ) ) {
QString text = i18n("<qt>The email address <b>%1</b> was added to your "
"addressbook; you can add more information to this "
"entry by opening the addressbook.</qt>").arg( addr );
KMessageBox::information( parent, text, QString::null, "addedtokabc" );
}
} else {
QString text = i18n("<qt>The email address <b>%1</b> is already in your "
"addressbook.</qt>").arg( addr );
KMessageBox::information( parent, text, QString::null,
"alreadyInAddressBook" );
}
ab->setErrorHandler( 0 );
}
void KAddrBookExternal::openAddressBook(QWidget *) {
kapp->startServiceByDesktopName( "kaddressbook" );
}
void KAddrBookExternal::addNewAddressee( QWidget* )
{
kapp->startServiceByDesktopName("kaddressbook");
DCOPRef call("kaddressbook", "KAddressBookIface");
call.send("newContact()");
}
bool KAddrBookExternal::addVCard( const KABC::Addressee& addressee, QWidget *parent )
{
KABC::AddressBook *ab = KABC::StdAddressBook::self( true );
bool inserted = false;
ab->setErrorHandler( new KABC::GuiErrorHandler( parent ) );
KABC::Addressee::List addressees =
ab->findByEmail( addressee.preferredEmail() );
if ( addressees.isEmpty() ) {
if ( KAddrBookExternal::addAddressee( addressee ) ) {
QString text = i18n("The VCard was added to your addressbook; "
"you can add more information to this "
"entry by opening the addressbook.");
KMessageBox::information( parent, text, QString::null, "addedtokabc" );
inserted = true;
}
} else {
QString text = i18n("The VCard's primary email address is already in "
"your addressbook; however, you may save the VCard "
"into a file and import it into the addressbook "
"manually.");
KMessageBox::information( parent, text );
inserted = true;
}
ab->setErrorHandler( 0 );
return inserted;
}
bool KAddrBookExternal::addAddressee( const KABC::Addressee& addr )
{
KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );
#if KDE_IS_VERSION(3,4,89)
// This ugly hack will be removed in 4.0
while ( !addressBook->loadingHasFinished() ) {
QApplication::eventLoop()->processEvents( QEventLoop::ExcludeUserInput );
// use sleep here to reduce cpu usage
usleep( 100 );
}
#endif
// Select a resource
QPtrList<KABC::Resource> kabcResources = addressBook->resources();
QPtrList<KRES::Resource> kresResources;
QPtrListIterator<KABC::Resource> resIt( kabcResources );
KABC::Resource *kabcResource;
while ( ( kabcResource = resIt.current() ) != 0 ) {
++resIt;
if ( !kabcResource->readOnly() ) {
KRES::Resource *res = static_cast<KRES::Resource*>( kabcResource );
if ( res )
kresResources.append( res );
}
}
kabcResource = static_cast<KABC::Resource*>( KRES::SelectDialog::getResource( kresResources, 0 ) );
KABC::Ticket *ticket = addressBook->requestSaveTicket( kabcResource );
bool saved = false;
if ( ticket ) {
KABC::Addressee addressee( addr );
addressee.setResource( kabcResource );
addressBook->insertAddressee( addressee );
saved = addressBook->save( ticket );
if ( !saved )
addressBook->releaseSaveTicket( ticket );
}
addressBook->emitAddressBookChanged();
return saved;
}
QString KAddrBookExternal::expandDistributionList( const QString& listName )
{
if ( listName.isEmpty() )
return QString::null;
const QString lowerListName = listName.lower();
KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );
#ifdef KDEPIM_NEW_DISTRLISTS
KPIM::DistributionList distrList = KPIM::DistributionList::findByName( addressBook, lowerListName, false );
if ( !distrList.isEmpty() ) {
return distrList.emails( addressBook ).join( ", " );
}
#else
KABC::DistributionListManager manager( addressBook );
manager.load();
const QStringList listNames = manager.listNames();
for ( QStringList::ConstIterator it = listNames.begin();
it != listNames.end(); ++it) {
if ( (*it).lower() == lowerListName ) {
const QStringList addressList = manager.list( *it )->emails();
return addressList.join( ", " );
}
}
#endif
return QString::null;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <libport/asio.hh>
#include <urbi/uobject.hh>
using namespace urbi;
/** Subsumption object.
*
* Takes one output, and provides multiple inputs that conditionaly bounce to
* said output.
*/
class subsumption: public UObject
{
public:
subsumption(const std::string& n);
/// Set target for all write operations, create 'val' source at level 0.
int init(UVar& target);
/** Creates slot \b varName that writes at \b level, and sets this level for
* \b delay seconds.
*/
void createTimedOverride(const std::string& varName, int level, ufloat delay);
/// Create a new slot \b varName that writes at level \b level.
void createOverride(const std::string& varName, int level);
/// All write operations below this level will be ignored.
UVar level;
private:
class SUVar: public UVar
{
public:
SUVar(const std::string& obj, const std::string& var, int level,
ufloat delay = 0);
friend class subsumption;
private:
int level_;
ufloat timer_;
};
int onLevelChange(UVar& v);
int onWrite(UVar& v);
void resetLevel(int oldLevel, int writeCount);
UVar* target_;
int writeCount_;
};
subsumption::subsumption(const std::string& n)
: UObject(n)
, target_(0)
, writeCount_(0)
{
UBindFunction(subsumption, init);
}
int
subsumption::init(UVar& target)
{
std::string targetName = target.get_name();
UBindVar(subsumption, level);
UBindFunction(subsumption, createOverride);
UBindFunction(subsumption, createTimedOverride);
UNotifyChange(level, &subsumption::onLevelChange);
level = 0;
target_ = new UVar(targetName);
createOverride("val", 0);
return 0;
}
void
subsumption::createOverride(const std::string& name, int level)
{
UNotifyChange(*new SUVar(__name, name, level), &subsumption::onWrite);
}
void
subsumption::createTimedOverride(const std::string& name, int level,
ufloat timer)
{
UNotifyChange(*new SUVar(__name, name, level, timer), &subsumption::onWrite);
}
int
subsumption::onLevelChange(UVar&)
{
writeCount_++;
return 0;
}
int
subsumption::onWrite(UVar& v)
{
SUVar& sv = static_cast<SUVar&>(v);
if ((int)level <= sv.level_)
{
*target_ = sv.val();
if (sv.timer_)
{
int oldLevel = level;
level = sv.level_;
// Keep this line after the previous one.
libport::asyncCall(boost::bind(&subsumption::resetLevel, this,
oldLevel, writeCount_),
useconds_t(sv.timer_ * 1000000.0));
}
}
return 0;
}
subsumption::SUVar::SUVar(const std::string& obj, const std::string& var,
int level, ufloat delay)
: UVar(obj, var)
, level_(level)
, timer_(delay)
{
}
void
subsumption::resetLevel(int newLevel, int wc)
{
ctx_->lock();
// Only reset if level was not written on since first trigger.
if (writeCount_ == wc)
level = newLevel;
ctx_->unlock();
}
UStart(subsumption);
<commit_msg>Subsumption: Support variable read.<commit_after>/*
* Copyright (C) 2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <libport/asio.hh>
#include <urbi/uobject.hh>
using namespace urbi;
/** Subsumption object.
*
* Takes one output, and provides multiple inputs that conditionaly bounce to
* said output.
*/
class subsumption: public UObject
{
public:
subsumption(const std::string& n);
/// Set target for all write operations, create 'val' source at level 0.
int init(UVar& target);
/** Creates slot \b varName that writes at \b level, and sets this level for
* \b delay seconds.
*/
void createTimedOverride(const std::string& varName, int level, ufloat delay);
/// Create a new slot \b varName that writes at level \b level.
void createOverride(const std::string& varName, int level);
/// All write operations below this level will be ignored.
UVar level;
private:
class SUVar: public UVar
{
public:
SUVar(const std::string& obj, const std::string& var, int level,
ufloat delay = 0);
friend class subsumption;
private:
int level_;
ufloat timer_;
};
int onLevelChange(UVar& v);
int onWrite(UVar& v);
int onRead(UVar& v);
void resetLevel(int oldLevel, int writeCount);
UVar* target_;
int writeCount_;
};
subsumption::subsumption(const std::string& n)
: UObject(n)
, target_(0)
, writeCount_(0)
{
UBindFunction(subsumption, init);
}
int
subsumption::init(UVar& target)
{
std::string targetName = target.get_name();
UBindVar(subsumption, level);
UBindFunction(subsumption, createOverride);
UBindFunction(subsumption, createTimedOverride);
UNotifyChange(level, &subsumption::onLevelChange);
level = 0;
target_ = new UVar(targetName);
createOverride("val", 0);
return 0;
}
void
subsumption::createOverride(const std::string& name, int level)
{
createTimedOverride(name, level, 0);
}
void
subsumption::createTimedOverride(const std::string& name, int level,
ufloat timer)
{
SUVar* v = new SUVar(__name, name, level, timer);
v->setOwned();
UNotifyChange(*v, &subsumption::onWrite);
UNotifyAccess(*v, &subsumption::onRead);
}
int
subsumption::onLevelChange(UVar&)
{
writeCount_++;
return 0;
}
int
subsumption::onRead(UVar& v)
{
v = target_->val();
return 0;
}
int
subsumption::onWrite(UVar& v)
{
SUVar& sv = static_cast<SUVar&>(v);
if ((int)level <= sv.level_)
{
*target_ = sv.val();
if (sv.timer_)
{
int oldLevel = level;
level = sv.level_;
// Keep this line after the previous one.
libport::asyncCall(boost::bind(&subsumption::resetLevel, this,
oldLevel, writeCount_),
useconds_t(sv.timer_ * 1000000.0));
}
}
return 0;
}
subsumption::SUVar::SUVar(const std::string& obj, const std::string& var,
int level, ufloat delay)
: UVar(obj, var)
, level_(level)
, timer_(delay)
{
}
void
subsumption::resetLevel(int newLevel, int wc)
{
ctx_->lock();
// Only reset if level was not written on since first trigger.
if (writeCount_ == wc)
level = newLevel;
ctx_->unlock();
}
UStart(subsumption);
<|endoftext|> |
<commit_before>/*
Crystal Space Event Queue
Copyright (C) 1998-2004 by Jorrit Tyberghein
Written by Andrew Zabolotny <bit@eltech.ru>, Eric Sunshine, Jonathan Tarbox,
Frank Richter
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csutil/array.h"
#include "csutil/csevent.h"
#include "csutil/cseventq.h"
#include "csutil/memfile.h"
#include "csutil/util.h"
#include "csutil/sysfunc.h"
//---------------------------------------------------------------------------
SCF_IMPLEMENT_IBASE (csEvent)
SCF_IMPLEMENTS_INTERFACE (iEvent)
SCF_IMPLEMENTS_INTERFACE (csEvent)
SCF_IMPLEMENT_IBASE_END
CS_IMPLEMENT_STATIC_VAR(GetEventStrSet, csStringSet, ())
char const* csEvent::GetTypeName (csEventAttributeType t)
{
switch (t)
{
case csEventAttrInt: return "int";
case csEventAttrUInt: return "uint";
case csEventAttrFloat: return "double";
case csEventAttrDatabuffer: return "databuffer";
case csEventAttrEvent: return "event";
case csEventAttriBase: return "iBase";
default:
break;
}
return "unknown";
}
csStringID csEvent::GetKeyID (const char* key)
{
return GetEventStrSet()->Request (key);
}
const char* csEvent::GetKeyName (csStringID id)
{
return GetEventStrSet()->Request (id);
}
csEvent::csEvent ()
{
SCF_CONSTRUCT_IBASE (0);
count = 0;
}
csEvent::csEvent (csTicks iTime, int eType, int mx, int my,
int mButton, int mModifiers) : attributes (53)
{
SCF_CONSTRUCT_IBASE (0);
Time = iTime;
Type = eType;
Category = SubCategory = Flags = 0;
Mouse.x = mx;
Mouse.y = my;
Mouse.Button = mButton;
Mouse.Modifiers = mModifiers;
count = 0;
}
csEvent::csEvent (csTicks iTime, int eType, int jn, int jx, int jy,
int jButton, int jModifiers) : attributes (53)
{
SCF_CONSTRUCT_IBASE (0);
Time = iTime;
Type = eType;
Category = SubCategory = Flags = 0;
Joystick.number = jn;
Joystick.x = jx;
Joystick.y = jy;
Joystick.Button = jButton;
Joystick.Modifiers = jModifiers;
count = 0;
}
csEvent::csEvent (csTicks iTime, int eType, int cCode, intptr_t cInfo) :
attributes (53)
{
SCF_CONSTRUCT_IBASE (0);
Time = iTime;
Type = eType;
Category = SubCategory = Flags = 0;
Command.Code = cCode;
Command.Info = cInfo;
if (eType == csevBroadcast)
Flags = CSEF_BROADCAST;
count = 0;
}
csEvent::csEvent (csEvent const& e) : iEvent(), attributes (53)
{
SCF_CONSTRUCT_IBASE (0);
count = 0;
Type = e.Type;
Category = e.Category;
SubCategory = e.SubCategory;
Flags = e.Flags;
Time = e.Time;
attributes = e.attributes;
if ((Type & CSMASK_Mouse) != 0)
{
Mouse.x = e.Mouse.x;
Mouse.y = e.Mouse.y;
Mouse.Button = e.Mouse.Button;
Mouse.Modifiers = e.Mouse.Modifiers;
}
else if ((Type & CSMASK_Joystick) != 0)
{
Joystick.number = e.Joystick.number;
Joystick.x = e.Joystick.x;
Joystick.y = e.Joystick.y;
Joystick.Button = e.Joystick.Button;
Joystick.Modifiers = e.Joystick.Modifiers;
}
else
{
Command.Code = e.Command.Code;
Command.Info = e.Command.Info;
}
}
csEvent::~csEvent ()
{
RemoveAll();
SCF_DESTRUCT_IBASE ();
}
bool csEvent::Add (const char *name, float v)
{
if (attributes.In (GetKeyID (name))) return false;
attribute* object = new attribute (csEventAttrFloat);
object->doubleVal = v;
attributes.Put (GetKeyID (name), object);
count++;
return true;
}
bool csEvent::Add (const char *name, double v)
{
if (attributes.In (GetKeyID (name))) return false;
attribute* object = new attribute (csEventAttrFloat);
object->doubleVal = v;
attributes.Put (GetKeyID (name), object);
count++;
return true;
}
bool csEvent::Add (const char *name, bool v)
{
if (attributes.In (GetKeyID (name))) return false;
attribute* object = new attribute (csEventAttrInt);
object->intVal = v ? 1 : 0;
attributes.Put (GetKeyID (name), object);
count++;
return true;
}
bool csEvent::Add (const char *name, const char *v)
{
if (attributes.In (GetKeyID (name))) return false;
attribute* object = new attribute (csEventAttrDatabuffer);
object->dataSize = strlen(v);
object->bufferVal = csStrNew(v);
attributes.Put (GetKeyID (name), object);
count++;
return true;
}
bool csEvent::Add (const char *name, const void *v, size_t size)
{
if (attributes.In (GetKeyID (name))) return false;
attribute* object = new attribute (csEventAttrDatabuffer);
object->bufferVal = new char[size + 1];
memcpy (object->bufferVal, v, size);
object->bufferVal[size] = 0;
object->dataSize = size;
attributes.Put (GetKeyID (name), object);
count++;
return true;
}
bool csEvent::CheckForLoops (iEvent* current, iEvent* e)
{
csRef<iEventAttributeIterator> iter (current->GetAttributeIterator());
while (iter->HasNext())
{
const char* attr = iter->Next();
if (current->GetAttributeType (attr) == csEventAttrEvent)
{
csRef<iEvent> ev;
if (current->Retrieve (attr, ev) != csEventErrNone) continue;
if (ev == e)
return false;
return CheckForLoops(ev, e);
}
}
return true;
}
bool csEvent::Add (const char *name, iEvent *v)
{
if (attributes.In (GetKeyID (name))) return false;
if (this == v)
return false;
if (v && CheckForLoops(v, this))
{
attribute* object = new attribute (csEventAttrEvent);
(object->ibaseVal = (iBase*)v)->IncRef();
attributes.Put (GetKeyID (name), object);
count++;
return true;
}
return false;
}
bool csEvent::Add (const char *name, iBase* v)
{
if (attributes.In (GetKeyID (name))) return false;
if (v)
{
attribute* object = new attribute (csEventAttriBase);
(object->ibaseVal = v)->IncRef();
attributes.Put (GetKeyID (name), object);
count++;
return true;
}
return false;
}
csEventError csEvent::Retrieve (const char *name, float &v) const
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (!object) return csEventErrNotFound;
if (object->type == csEventAttrFloat)
{
v = object->doubleVal;
return csEventErrNone;
}
else
{
return InternalReportMismatch (object);
}
}
csEventError csEvent::Retrieve (const char *name, double &v) const
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (!object) return csEventErrNotFound;
if (object->type == csEventAttrFloat)
{
v = object->doubleVal;
return csEventErrNone;
}
else
{
return InternalReportMismatch (object);
}
}
csEventError csEvent::Retrieve (const char *name, const char *&v) const
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (!object) return csEventErrNotFound;
if (object->type == csEventAttrDatabuffer)
{
v = object->bufferVal;
return csEventErrNone;
}
else
{
return InternalReportMismatch (object);
}
}
csEventError csEvent::Retrieve (const char *name, void const *&v,
size_t &size) const
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (!object) return csEventErrNotFound;
if (object->type == csEventAttrDatabuffer)
{
v = object->bufferVal;
size = object->dataSize;
return csEventErrNone;
}
else
{
return InternalReportMismatch (object);
}
}
csEventError csEvent::Retrieve (const char *name, bool &v) const
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (!object) return csEventErrNotFound;
if (object->type == csEventAttrInt)
{
v = object->intVal != 0;
return csEventErrNone;
}
else
{
return InternalReportMismatch (object);
}
}
csEventError csEvent::Retrieve (const char *name, csRef<iEvent> &v) const
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (!object) return csEventErrNotFound;
if (object->type == csEventAttrEvent)
{
v = (iEvent*)object->ibaseVal;
return csEventErrNone;
}
else
{
return InternalReportMismatch (object);
}
}
csEventError csEvent::Retrieve (const char *name, csRef<iBase> &v) const
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (!object) return csEventErrNotFound;
if (object->type == csEventAttriBase)
{
v = object->ibaseVal;
return csEventErrNone;
}
else
{
return InternalReportMismatch (object);
}
}
bool csEvent::AttributeExists (const char* name)
{
return attributes.In (GetKeyID (name));
}
csEventAttributeType csEvent::GetAttributeType (const char* name)
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (object)
{
return object->type;
}
return csEventAttrUnknown;
}
bool csEvent::Remove(const char *name)
{
csStringID id = GetKeyID (name);
if (!attributes.In (id)) return false;
attribute* object = attributes.Get (id, 0);
bool result = attributes.Delete (id, object);
delete object;
return result;
}
bool csEvent::RemoveAll()
{
csHash<attribute*, csStringID>::GlobalIterator iter (
attributes.GetIterator ());
while (iter.HasNext())
{
csStringID name;
attribute* object = iter.Next (name);
delete object;
}
attributes.DeleteAll();
count = 0;
return true;
}
csRef<iEventAttributeIterator> csEvent::GetAttributeIterator()
{
csHash<csEvent::attribute*, csStringID>::GlobalIterator attrIter (
attributes.GetIterator());
return csPtr<iEventAttributeIterator> (new csEventAttributeIterator (
attrIter));
}
static void IndentLevel(int level)
{
for (int i = 0; i < level; i++)
csPrintf("\t");
}
bool csEvent::Print (int level)
{
csHash<attribute*, csStringID>::GlobalIterator iter (
attributes.GetIterator ());
while (iter.HasNext())
{
csStringID name;
attribute* object = iter.Next (name);
IndentLevel(level); csPrintf ("------\n");
IndentLevel(level); csPrintf ("Name: %s\n", GetKeyName (name));
IndentLevel(level); csPrintf (" Datatype: %s\n",
GetTypeName(object->type));
if (object->type == csEventAttrEvent)
{
IndentLevel(level); csPrintf(" Sub-Event Contents:\n");
csRef<csEvent> csev = SCF_QUERY_INTERFACE (object->ibaseVal, csEvent);
if (csev)
csev->Print(level+1);
else
{
IndentLevel(level+1); csPrintf(" (Not an event!):\n");
}
}
if (object->type == csEventAttrInt)
{
IndentLevel(level);
csPrintf (" Value: %lld\n", // Avoid Mingw/gcc borked PRId64.
object->intVal);
}
else if (object->type == csEventAttrUInt)
{
IndentLevel(level);
csPrintf (" Value: %llu\n", // Avoid Mingw/gcc borked PRIu64.
(ulonglong) object->intVal);
}
else if (object->type == csEventAttrFloat)
{
IndentLevel(level);
csPrintf (" Value: %f\n", object->doubleVal);
}
else if (object->type == csEventAttrDatabuffer)
{
IndentLevel(level); csPrintf(" Value: 0x%p\n", object->bufferVal);
IndentLevel(level); csPrintf(" Length: %zu\n", object->dataSize);
}
}
return true;
}
csRef<iEvent> csEvent::CreateEvent()
{
return csPtr<iEvent>(new csEvent());
}
//---------------------------------------------------------------------------
SCF_IMPLEMENT_IBASE (csEventAttributeIterator)
SCF_IMPLEMENTS_INTERFACE (iEventAttributeIterator)
SCF_IMPLEMENT_IBASE_END
const char* csEventAttributeIterator::Next()
{
csStringID key;
iterator.Next (key);
return csEvent::GetKeyName (key);
}
//*****************************************************************************
// csPoolEvent
//*****************************************************************************
csPoolEvent::csPoolEvent(csEventQueue *q)
{
pool = q;
next = 0;
}
void csPoolEvent::DecRef()
{
if (scfRefCount == 1)
{
if (!pool.IsValid())
return;
next = pool->EventPool;
pool->EventPool = this;
RemoveAll();
Type = 0;
Category = 0;
Flags = 0;
Time = 0;
SubCategory = 0;
Command.Code = 0;
Command.Info = 0;
}
else
{
scfRefCount--;
}
}
csRef<iEvent> csPoolEvent::CreateEvent()
{
if (pool.IsValid())
return pool->CreateEvent(0);
return superclass::CreateEvent();
}
<commit_msg>More ugly 64-bit printf() format directive hackiness.<commit_after>/*
Crystal Space Event Queue
Copyright (C) 1998-2004 by Jorrit Tyberghein
Written by Andrew Zabolotny <bit@eltech.ru>, Eric Sunshine, Jonathan Tarbox,
Frank Richter
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csutil/array.h"
#include "csutil/csevent.h"
#include "csutil/cseventq.h"
#include "csutil/memfile.h"
#include "csutil/util.h"
#include "csutil/sysfunc.h"
// Ugly work-around for Mingw/gcc borked PRId64.
#ifndef __CS_PRI64_PREFIX
#if CS_PROCESSOR_SIZE == 64
#define __CS_PRI64_PREFIX "l"
#else
#define __CS_PRI64_PREFIX "ll"
#endif
#endif
//---------------------------------------------------------------------------
SCF_IMPLEMENT_IBASE (csEvent)
SCF_IMPLEMENTS_INTERFACE (iEvent)
SCF_IMPLEMENTS_INTERFACE (csEvent)
SCF_IMPLEMENT_IBASE_END
CS_IMPLEMENT_STATIC_VAR(GetEventStrSet, csStringSet, ())
char const* csEvent::GetTypeName (csEventAttributeType t)
{
switch (t)
{
case csEventAttrInt: return "int";
case csEventAttrUInt: return "uint";
case csEventAttrFloat: return "double";
case csEventAttrDatabuffer: return "databuffer";
case csEventAttrEvent: return "event";
case csEventAttriBase: return "iBase";
default:
break;
}
return "unknown";
}
csStringID csEvent::GetKeyID (const char* key)
{
return GetEventStrSet()->Request (key);
}
const char* csEvent::GetKeyName (csStringID id)
{
return GetEventStrSet()->Request (id);
}
csEvent::csEvent ()
{
SCF_CONSTRUCT_IBASE (0);
count = 0;
}
csEvent::csEvent (csTicks iTime, int eType, int mx, int my,
int mButton, int mModifiers) : attributes (53)
{
SCF_CONSTRUCT_IBASE (0);
Time = iTime;
Type = eType;
Category = SubCategory = Flags = 0;
Mouse.x = mx;
Mouse.y = my;
Mouse.Button = mButton;
Mouse.Modifiers = mModifiers;
count = 0;
}
csEvent::csEvent (csTicks iTime, int eType, int jn, int jx, int jy,
int jButton, int jModifiers) : attributes (53)
{
SCF_CONSTRUCT_IBASE (0);
Time = iTime;
Type = eType;
Category = SubCategory = Flags = 0;
Joystick.number = jn;
Joystick.x = jx;
Joystick.y = jy;
Joystick.Button = jButton;
Joystick.Modifiers = jModifiers;
count = 0;
}
csEvent::csEvent (csTicks iTime, int eType, int cCode, intptr_t cInfo) :
attributes (53)
{
SCF_CONSTRUCT_IBASE (0);
Time = iTime;
Type = eType;
Category = SubCategory = Flags = 0;
Command.Code = cCode;
Command.Info = cInfo;
if (eType == csevBroadcast)
Flags = CSEF_BROADCAST;
count = 0;
}
csEvent::csEvent (csEvent const& e) : iEvent(), attributes (53)
{
SCF_CONSTRUCT_IBASE (0);
count = 0;
Type = e.Type;
Category = e.Category;
SubCategory = e.SubCategory;
Flags = e.Flags;
Time = e.Time;
attributes = e.attributes;
if ((Type & CSMASK_Mouse) != 0)
{
Mouse.x = e.Mouse.x;
Mouse.y = e.Mouse.y;
Mouse.Button = e.Mouse.Button;
Mouse.Modifiers = e.Mouse.Modifiers;
}
else if ((Type & CSMASK_Joystick) != 0)
{
Joystick.number = e.Joystick.number;
Joystick.x = e.Joystick.x;
Joystick.y = e.Joystick.y;
Joystick.Button = e.Joystick.Button;
Joystick.Modifiers = e.Joystick.Modifiers;
}
else
{
Command.Code = e.Command.Code;
Command.Info = e.Command.Info;
}
}
csEvent::~csEvent ()
{
RemoveAll();
SCF_DESTRUCT_IBASE ();
}
bool csEvent::Add (const char *name, float v)
{
if (attributes.In (GetKeyID (name))) return false;
attribute* object = new attribute (csEventAttrFloat);
object->doubleVal = v;
attributes.Put (GetKeyID (name), object);
count++;
return true;
}
bool csEvent::Add (const char *name, double v)
{
if (attributes.In (GetKeyID (name))) return false;
attribute* object = new attribute (csEventAttrFloat);
object->doubleVal = v;
attributes.Put (GetKeyID (name), object);
count++;
return true;
}
bool csEvent::Add (const char *name, bool v)
{
if (attributes.In (GetKeyID (name))) return false;
attribute* object = new attribute (csEventAttrInt);
object->intVal = v ? 1 : 0;
attributes.Put (GetKeyID (name), object);
count++;
return true;
}
bool csEvent::Add (const char *name, const char *v)
{
if (attributes.In (GetKeyID (name))) return false;
attribute* object = new attribute (csEventAttrDatabuffer);
object->dataSize = strlen(v);
object->bufferVal = csStrNew(v);
attributes.Put (GetKeyID (name), object);
count++;
return true;
}
bool csEvent::Add (const char *name, const void *v, size_t size)
{
if (attributes.In (GetKeyID (name))) return false;
attribute* object = new attribute (csEventAttrDatabuffer);
object->bufferVal = new char[size + 1];
memcpy (object->bufferVal, v, size);
object->bufferVal[size] = 0;
object->dataSize = size;
attributes.Put (GetKeyID (name), object);
count++;
return true;
}
bool csEvent::CheckForLoops (iEvent* current, iEvent* e)
{
csRef<iEventAttributeIterator> iter (current->GetAttributeIterator());
while (iter->HasNext())
{
const char* attr = iter->Next();
if (current->GetAttributeType (attr) == csEventAttrEvent)
{
csRef<iEvent> ev;
if (current->Retrieve (attr, ev) != csEventErrNone) continue;
if (ev == e)
return false;
return CheckForLoops(ev, e);
}
}
return true;
}
bool csEvent::Add (const char *name, iEvent *v)
{
if (attributes.In (GetKeyID (name))) return false;
if (this == v)
return false;
if (v && CheckForLoops(v, this))
{
attribute* object = new attribute (csEventAttrEvent);
(object->ibaseVal = (iBase*)v)->IncRef();
attributes.Put (GetKeyID (name), object);
count++;
return true;
}
return false;
}
bool csEvent::Add (const char *name, iBase* v)
{
if (attributes.In (GetKeyID (name))) return false;
if (v)
{
attribute* object = new attribute (csEventAttriBase);
(object->ibaseVal = v)->IncRef();
attributes.Put (GetKeyID (name), object);
count++;
return true;
}
return false;
}
csEventError csEvent::Retrieve (const char *name, float &v) const
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (!object) return csEventErrNotFound;
if (object->type == csEventAttrFloat)
{
v = object->doubleVal;
return csEventErrNone;
}
else
{
return InternalReportMismatch (object);
}
}
csEventError csEvent::Retrieve (const char *name, double &v) const
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (!object) return csEventErrNotFound;
if (object->type == csEventAttrFloat)
{
v = object->doubleVal;
return csEventErrNone;
}
else
{
return InternalReportMismatch (object);
}
}
csEventError csEvent::Retrieve (const char *name, const char *&v) const
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (!object) return csEventErrNotFound;
if (object->type == csEventAttrDatabuffer)
{
v = object->bufferVal;
return csEventErrNone;
}
else
{
return InternalReportMismatch (object);
}
}
csEventError csEvent::Retrieve (const char *name, void const *&v,
size_t &size) const
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (!object) return csEventErrNotFound;
if (object->type == csEventAttrDatabuffer)
{
v = object->bufferVal;
size = object->dataSize;
return csEventErrNone;
}
else
{
return InternalReportMismatch (object);
}
}
csEventError csEvent::Retrieve (const char *name, bool &v) const
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (!object) return csEventErrNotFound;
if (object->type == csEventAttrInt)
{
v = object->intVal != 0;
return csEventErrNone;
}
else
{
return InternalReportMismatch (object);
}
}
csEventError csEvent::Retrieve (const char *name, csRef<iEvent> &v) const
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (!object) return csEventErrNotFound;
if (object->type == csEventAttrEvent)
{
v = (iEvent*)object->ibaseVal;
return csEventErrNone;
}
else
{
return InternalReportMismatch (object);
}
}
csEventError csEvent::Retrieve (const char *name, csRef<iBase> &v) const
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (!object) return csEventErrNotFound;
if (object->type == csEventAttriBase)
{
v = object->ibaseVal;
return csEventErrNone;
}
else
{
return InternalReportMismatch (object);
}
}
bool csEvent::AttributeExists (const char* name)
{
return attributes.In (GetKeyID (name));
}
csEventAttributeType csEvent::GetAttributeType (const char* name)
{
attribute* object = attributes.Get (GetKeyID (name), 0);
if (object)
{
return object->type;
}
return csEventAttrUnknown;
}
bool csEvent::Remove(const char *name)
{
csStringID id = GetKeyID (name);
if (!attributes.In (id)) return false;
attribute* object = attributes.Get (id, 0);
bool result = attributes.Delete (id, object);
delete object;
return result;
}
bool csEvent::RemoveAll()
{
csHash<attribute*, csStringID>::GlobalIterator iter (
attributes.GetIterator ());
while (iter.HasNext())
{
csStringID name;
attribute* object = iter.Next (name);
delete object;
}
attributes.DeleteAll();
count = 0;
return true;
}
csRef<iEventAttributeIterator> csEvent::GetAttributeIterator()
{
csHash<csEvent::attribute*, csStringID>::GlobalIterator attrIter (
attributes.GetIterator());
return csPtr<iEventAttributeIterator> (new csEventAttributeIterator (
attrIter));
}
static void IndentLevel(int level)
{
for (int i = 0; i < level; i++)
csPrintf("\t");
}
bool csEvent::Print (int level)
{
csHash<attribute*, csStringID>::GlobalIterator iter (
attributes.GetIterator ());
while (iter.HasNext())
{
csStringID name;
attribute* object = iter.Next (name);
IndentLevel(level); csPrintf ("------\n");
IndentLevel(level); csPrintf ("Name: %s\n", GetKeyName (name));
IndentLevel(level); csPrintf (" Datatype: %s\n",
GetTypeName(object->type));
if (object->type == csEventAttrEvent)
{
IndentLevel(level); csPrintf(" Sub-Event Contents:\n");
csRef<csEvent> csev = SCF_QUERY_INTERFACE (object->ibaseVal, csEvent);
if (csev)
csev->Print(level+1);
else
{
IndentLevel(level+1); csPrintf(" (Not an event!):\n");
}
}
if (object->type == csEventAttrInt)
{
IndentLevel(level);
csPrintf(" Value: %" __CS_PRI64_PREFIX "d\n", object->intVal);
}
else if (object->type == csEventAttrUInt)
{
IndentLevel(level);
csPrintf(" Value: %" __CS_PRI64_PREFIX "u\n", object->intVal);
}
else if (object->type == csEventAttrFloat)
{
IndentLevel(level);
csPrintf (" Value: %f\n", object->doubleVal);
}
else if (object->type == csEventAttrDatabuffer)
{
IndentLevel(level); csPrintf(" Value: 0x%p\n", object->bufferVal);
IndentLevel(level); csPrintf(" Length: %zu\n", object->dataSize);
}
}
return true;
}
csRef<iEvent> csEvent::CreateEvent()
{
return csPtr<iEvent>(new csEvent());
}
//---------------------------------------------------------------------------
SCF_IMPLEMENT_IBASE (csEventAttributeIterator)
SCF_IMPLEMENTS_INTERFACE (iEventAttributeIterator)
SCF_IMPLEMENT_IBASE_END
const char* csEventAttributeIterator::Next()
{
csStringID key;
iterator.Next (key);
return csEvent::GetKeyName (key);
}
//*****************************************************************************
// csPoolEvent
//*****************************************************************************
csPoolEvent::csPoolEvent(csEventQueue *q)
{
pool = q;
next = 0;
}
void csPoolEvent::DecRef()
{
if (scfRefCount == 1)
{
if (!pool.IsValid())
return;
next = pool->EventPool;
pool->EventPool = this;
RemoveAll();
Type = 0;
Category = 0;
Flags = 0;
Time = 0;
SubCategory = 0;
Command.Code = 0;
Command.Info = 0;
}
else
{
scfRefCount--;
}
}
csRef<iEvent> csPoolEvent::CreateEvent()
{
if (pool.IsValid())
return pool->CreateEvent(0);
return superclass::CreateEvent();
}
<|endoftext|> |
<commit_before><commit_msg>fix 'dark image' bug in imwri<commit_after><|endoftext|> |
<commit_before>/*
OFX NoOp plugin.
Does nothing.
Copyright (C) 2014 INRIA
Author: Frederic Devernay <frederic.devernay@inria.fr>
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 {organization} 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.
INRIA
Domaine de Voluceau
Rocquencourt - B.P. 105
78153 Le Chesnay Cedex - France
*/
#include "NoOp.h"
#ifdef _WINDOWS
#include <windows.h>
#endif
#include "ofxsProcessing.H"
#define kPluginName "NoOpOFX"
#define kPluginGrouping "Other"
#define kPluginDescription "Copies the input to the ouput."
#define kPluginIdentifier "net.sf.openfx:NoOpPlugin"
#define kPluginVersionMajor 1 // Incrementing this number means that you have broken backwards compatibility of the plug-in.
#define kPluginVersionMinor 0 // Increment this when you have fixed a bug or made it faster.
#define kForceCopyParamName "forceCopy"
#define kForceCopyParamLabel "Force Copy"
#define kForceCopyParamHint "Force copy from input to output"
// Base class for the RGBA and the Alpha processor
class CopierBase : public OFX::ImageProcessor
{
protected:
OFX::Image *_srcImg;
public:
/** @brief no arg ctor */
CopierBase(OFX::ImageEffect &instance)
: OFX::ImageProcessor(instance)
, _srcImg(0)
{
}
/** @brief set the src image */
void setSrcImg(OFX::Image *v) {_srcImg = v;}
};
// template to do the RGBA processing
template <class PIX, int nComponents>
class ImageCopier : public CopierBase
{
public:
// ctor
ImageCopier(OFX::ImageEffect &instance)
: CopierBase(instance)
{}
private:
// and do some processing
void multiThreadProcessImages(OfxRectI procWindow)
{
for (int y = procWindow.y1; y < procWindow.y2; y++) {
if (_effect.abort()) break;
PIX *dstPix = (PIX *) _dstImg->getPixelAddress(procWindow.x1, y);
for (int x = procWindow.x1; x < procWindow.x2; x++) {
PIX *srcPix = (PIX *) (_srcImg ? _srcImg->getPixelAddress(x, y) : 0);
// do we have a source image to scale up
if (srcPix) {
for (int c = 0; c < nComponents; c++) {
dstPix[c] = srcPix[c];
}
}
else {
// no src pixel here, be black and transparent
for (int c = 0; c < nComponents; c++) {
dstPix[c] = 0;
}
}
// increment the dst pixel
dstPix += nComponents;
}
}
}
};
using namespace OFX;
////////////////////////////////////////////////////////////////////////////////
/** @brief The plugin that does our work */
class NoOpPlugin : public OFX::ImageEffect
{
public:
/** @brief ctor */
NoOpPlugin(OfxImageEffectHandle handle)
: ImageEffect(handle)
, dstClip_(0)
, srcClip_(0)
, forceCopy_(0)
{
dstClip_ = fetchClip(kOfxImageEffectOutputClipName);
assert(dstClip_ && (dstClip_->getPixelComponents() == ePixelComponentAlpha || dstClip_->getPixelComponents() == ePixelComponentRGB || dstClip_->getPixelComponents() == ePixelComponentRGBA));
srcClip_ = fetchClip(kOfxImageEffectSimpleSourceClipName);
assert(srcClip_ && (srcClip_->getPixelComponents() == ePixelComponentAlpha || srcClip_->getPixelComponents() == ePixelComponentRGB || srcClip_->getPixelComponents() == ePixelComponentRGBA));
forceCopy_ = fetchBooleanParam(kForceCopyParamName);
assert(forceCopy_);
}
private:
/* Override the render */
virtual void render(const OFX::RenderArguments &args);
/* set up and run a processor */
void setupAndProcess(CopierBase &, const OFX::RenderArguments &args);
virtual bool isIdentity(const RenderArguments &args, Clip * &identityClip, double &identityTime) /*OVERRIDE FINAL*/;
private:
// do not need to delete these, the ImageEffect is managing them for us
OFX::Clip *dstClip_;
OFX::Clip *srcClip_;
OFX::BooleanParam *forceCopy_;
};
////////////////////////////////////////////////////////////////////////////////
/** @brief render for the filter */
////////////////////////////////////////////////////////////////////////////////
// basic plugin render function, just a skelington to instantiate templates from
/* set up and run a processor */
void
NoOpPlugin::setupAndProcess(CopierBase &processor, const OFX::RenderArguments &args)
{
// get a dst image
std::auto_ptr<OFX::Image> dst(dstClip_->fetchImage(args.time));
if (!dst.get()) {
OFX::throwSuiteStatusException(kOfxStatFailed);
}
if (dst->getRenderScale().x != args.renderScale.x ||
dst->getRenderScale().y != args.renderScale.y ||
dst->getField() != args.fieldToRender) {
setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties");
OFX::throwSuiteStatusException(kOfxStatFailed);
}
OFX::BitDepthEnum dstBitDepth = dst->getPixelDepth();
OFX::PixelComponentEnum dstComponents = dst->getPixelComponents();
// fetch main input image
std::auto_ptr<OFX::Image> src(srcClip_->fetchImage(args.time));
// make sure bit depths are sane
if (src.get()) {
OFX::BitDepthEnum srcBitDepth = src->getPixelDepth();
OFX::PixelComponentEnum srcComponents = src->getPixelComponents();
// see if they have the same depths and bytes and all
if (srcBitDepth != dstBitDepth || srcComponents != dstComponents)
OFX::throwSuiteStatusException(kOfxStatErrImageFormat);
}
// set the images
processor.setDstImg(dst.get());
processor.setSrcImg(src.get());
// set the render window
processor.setRenderWindow(args.renderWindow);
// Call the base class process member, this will call the derived templated process code
processor.process();
}
// the overridden render function
void
NoOpPlugin::render(const OFX::RenderArguments &args)
{
bool forceCopy;
forceCopy_->getValue(forceCopy);
if (!forceCopy) {
setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host should not render");
throwSuiteStatusException(kOfxStatFailed);
}
// instantiate the render code based on the pixel depth of the dst clip
OFX::BitDepthEnum dstBitDepth = dstClip_->getPixelDepth();
OFX::PixelComponentEnum dstComponents = dstClip_->getPixelComponents();
// do the rendering
if (dstComponents == OFX::ePixelComponentRGBA) {
switch(dstBitDepth) {
case OFX::eBitDepthUByte : {
ImageCopier<unsigned char, 4> fred(*this);
setupAndProcess(fred, args);
}
break;
case OFX::eBitDepthUShort : {
ImageCopier<unsigned short, 4> fred(*this);
setupAndProcess(fred, args);
}
break;
case OFX::eBitDepthFloat : {
ImageCopier<float, 4> fred(*this);
setupAndProcess(fred, args);
}
break;
default :
OFX::throwSuiteStatusException(kOfxStatErrUnsupported);
}
} else if (dstComponents == OFX::ePixelComponentRGB) {
switch(dstBitDepth) {
case OFX::eBitDepthUByte : {
ImageCopier<unsigned char, 3> fred(*this);
setupAndProcess(fred, args);
}
break;
case OFX::eBitDepthUShort : {
ImageCopier<unsigned short, 3> fred(*this);
setupAndProcess(fred, args);
}
break;
case OFX::eBitDepthFloat : {
ImageCopier<float, 3> fred(*this);
setupAndProcess(fred, args);
}
break;
default :
OFX::throwSuiteStatusException(kOfxStatErrUnsupported);
}
} else {
assert(dstComponents == OFX::ePixelComponentAlpha);
switch(dstBitDepth) {
case OFX::eBitDepthUByte : {
ImageCopier<unsigned char, 1> fred(*this);
setupAndProcess(fred, args);
}
break;
case OFX::eBitDepthUShort : {
ImageCopier<unsigned short, 1> fred(*this);
setupAndProcess(fred, args);
}
break;
case OFX::eBitDepthFloat : {
ImageCopier<float, 1> fred(*this);
setupAndProcess(fred, args);
}
break;
default :
OFX::throwSuiteStatusException(kOfxStatErrUnsupported);
}
}
}
bool
NoOpPlugin::isIdentity(const RenderArguments &args, Clip * &identityClip, double &identityTime)
{
bool forceCopy;
forceCopy_->getValue(forceCopy);
return !forceCopy;
}
using namespace OFX;
mDeclarePluginFactory(NoOpPluginFactory, {}, {});
void NoOpPluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
// basic labels
desc.setLabels(kPluginName, kPluginName, kPluginName);
desc.setPluginGrouping(kPluginGrouping);
desc.setPluginDescription(kPluginDescription);
// add the supported contexts, only filter at the moment
desc.addSupportedContext(eContextFilter);
// add supported pixel depths
desc.addSupportedBitDepth(eBitDepthUByte);
desc.addSupportedBitDepth(eBitDepthUShort);
desc.addSupportedBitDepth(eBitDepthFloat);
// set a few flags
desc.setSingleInstance(false);
desc.setHostFrameThreading(false);
desc.setSupportsMultiResolution(true);
desc.setSupportsTiles(true);
desc.setTemporalClipAccess(false);
desc.setRenderTwiceAlways(false);
desc.setSupportsMultipleClipPARs(false);
}
void NoOpPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, OFX::ContextEnum context)
{
if (!OFX::fetchSuite(kOfxVegasStereoscopicImageEffectSuite, 1, true)) {
throwHostMissingSuiteException(kOfxVegasStereoscopicImageEffectSuite);
}
// Source clip only in the filter context
// create the mandated source clip
ClipDescriptor *srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName);
srcClip->addSupportedComponent(ePixelComponentRGB);
srcClip->addSupportedComponent(ePixelComponentRGBA);
srcClip->addSupportedComponent(ePixelComponentAlpha);
srcClip->setTemporalClipAccess(false);
srcClip->setSupportsTiles(true);
srcClip->setIsMask(false);
// create the mandated output clip
ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName);
dstClip->addSupportedComponent(ePixelComponentRGB);
dstClip->addSupportedComponent(ePixelComponentRGBA);
dstClip->addSupportedComponent(ePixelComponentAlpha);
dstClip->setSupportsTiles(true);
// make some pages and to things in
PageParamDescriptor *page = desc.definePageParam("Controls");
BooleanParamDescriptor *forceCopy = desc.defineBooleanParam(kForceCopyParamName);
forceCopy->setLabels(kForceCopyParamLabel, kForceCopyParamLabel, kForceCopyParamLabel);
forceCopy->setHint(kForceCopyParamHint);
forceCopy->setDefault(false);
forceCopy->setAnimates(false);
page->addChild(*forceCopy);
}
OFX::ImageEffect* NoOpPluginFactory::createInstance(OfxImageEffectHandle handle, OFX::ContextEnum context)
{
return new NoOpPlugin(handle);
}
void getNoOpPluginID(OFX::PluginFactoryArray &ids)
{
static NoOpPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);
ids.push_back(&p);
}
<commit_msg>NoOp: add Clip Info button<commit_after>/*
OFX NoOp plugin.
Does nothing.
Copyright (C) 2014 INRIA
Author: Frederic Devernay <frederic.devernay@inria.fr>
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 {organization} 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.
INRIA
Domaine de Voluceau
Rocquencourt - B.P. 105
78153 Le Chesnay Cedex - France
*/
#include "NoOp.h"
#ifdef _WINDOWS
#include <windows.h>
#endif
#include "ofxsProcessing.H"
#define kPluginName "NoOpOFX"
#define kPluginGrouping "Other"
#define kPluginDescription "Copies the input to the ouput."
#define kPluginIdentifier "net.sf.openfx:NoOpPlugin"
#define kPluginVersionMajor 1 // Incrementing this number means that you have broken backwards compatibility of the plug-in.
#define kPluginVersionMinor 0 // Increment this when you have fixed a bug or made it faster.
#define kClipInfoParamName "clipInfo"
#define kClipInfoParamLabel "Clip Info..."
#define kClipInfoParamHint "Display information about the inputs"
#define kForceCopyParamName "forceCopy"
#define kForceCopyParamLabel "Force Copy"
#define kForceCopyParamHint "Force copy from input to output"
// Base class for the RGBA and the Alpha processor
class CopierBase : public OFX::ImageProcessor
{
protected:
OFX::Image *_srcImg;
public:
/** @brief no arg ctor */
CopierBase(OFX::ImageEffect &instance)
: OFX::ImageProcessor(instance)
, _srcImg(0)
{
}
/** @brief set the src image */
void setSrcImg(OFX::Image *v) {_srcImg = v;}
};
// template to do the RGBA processing
template <class PIX, int nComponents>
class ImageCopier : public CopierBase
{
public:
// ctor
ImageCopier(OFX::ImageEffect &instance)
: CopierBase(instance)
{}
private:
// and do some processing
void multiThreadProcessImages(OfxRectI procWindow)
{
for (int y = procWindow.y1; y < procWindow.y2; y++) {
if (_effect.abort()) break;
PIX *dstPix = (PIX *) _dstImg->getPixelAddress(procWindow.x1, y);
for (int x = procWindow.x1; x < procWindow.x2; x++) {
PIX *srcPix = (PIX *) (_srcImg ? _srcImg->getPixelAddress(x, y) : 0);
// do we have a source image to scale up
if (srcPix) {
for (int c = 0; c < nComponents; c++) {
dstPix[c] = srcPix[c];
}
}
else {
// no src pixel here, be black and transparent
for (int c = 0; c < nComponents; c++) {
dstPix[c] = 0;
}
}
// increment the dst pixel
dstPix += nComponents;
}
}
}
};
using namespace OFX;
////////////////////////////////////////////////////////////////////////////////
/** @brief The plugin that does our work */
class NoOpPlugin : public OFX::ImageEffect
{
public:
/** @brief ctor */
NoOpPlugin(OfxImageEffectHandle handle)
: ImageEffect(handle)
, dstClip_(0)
, srcClip_(0)
, forceCopy_(0)
{
dstClip_ = fetchClip(kOfxImageEffectOutputClipName);
assert(dstClip_ && (dstClip_->getPixelComponents() == ePixelComponentAlpha || dstClip_->getPixelComponents() == ePixelComponentRGB || dstClip_->getPixelComponents() == ePixelComponentRGBA));
srcClip_ = fetchClip(kOfxImageEffectSimpleSourceClipName);
assert(srcClip_ && (srcClip_->getPixelComponents() == ePixelComponentAlpha || srcClip_->getPixelComponents() == ePixelComponentRGB || srcClip_->getPixelComponents() == ePixelComponentRGBA));
forceCopy_ = fetchBooleanParam(kForceCopyParamName);
assert(forceCopy_);
}
private:
/* Override the render */
virtual void render(const OFX::RenderArguments &args);
/* set up and run a processor */
void setupAndProcess(CopierBase &, const OFX::RenderArguments &args);
virtual bool isIdentity(const RenderArguments &args, Clip * &identityClip, double &identityTime) /*OVERRIDE FINAL*/;
virtual void changedParam(const OFX::InstanceChangedArgs &args, const std::string ¶mName);
private:
// do not need to delete these, the ImageEffect is managing them for us
OFX::Clip *dstClip_;
OFX::Clip *srcClip_;
OFX::BooleanParam *forceCopy_;
};
////////////////////////////////////////////////////////////////////////////////
/** @brief render for the filter */
////////////////////////////////////////////////////////////////////////////////
// basic plugin render function, just a skelington to instantiate templates from
/* set up and run a processor */
void
NoOpPlugin::setupAndProcess(CopierBase &processor, const OFX::RenderArguments &args)
{
// get a dst image
std::auto_ptr<OFX::Image> dst(dstClip_->fetchImage(args.time));
if (!dst.get()) {
OFX::throwSuiteStatusException(kOfxStatFailed);
}
if (dst->getRenderScale().x != args.renderScale.x ||
dst->getRenderScale().y != args.renderScale.y ||
dst->getField() != args.fieldToRender) {
setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties");
OFX::throwSuiteStatusException(kOfxStatFailed);
}
OFX::BitDepthEnum dstBitDepth = dst->getPixelDepth();
OFX::PixelComponentEnum dstComponents = dst->getPixelComponents();
// fetch main input image
std::auto_ptr<OFX::Image> src(srcClip_->fetchImage(args.time));
// make sure bit depths are sane
if (src.get()) {
OFX::BitDepthEnum srcBitDepth = src->getPixelDepth();
OFX::PixelComponentEnum srcComponents = src->getPixelComponents();
// see if they have the same depths and bytes and all
if (srcBitDepth != dstBitDepth || srcComponents != dstComponents)
OFX::throwSuiteStatusException(kOfxStatErrImageFormat);
}
// set the images
processor.setDstImg(dst.get());
processor.setSrcImg(src.get());
// set the render window
processor.setRenderWindow(args.renderWindow);
// Call the base class process member, this will call the derived templated process code
processor.process();
}
// the overridden render function
void
NoOpPlugin::render(const OFX::RenderArguments &args)
{
bool forceCopy;
forceCopy_->getValue(forceCopy);
if (!forceCopy) {
setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host should not render");
throwSuiteStatusException(kOfxStatFailed);
}
// instantiate the render code based on the pixel depth of the dst clip
OFX::BitDepthEnum dstBitDepth = dstClip_->getPixelDepth();
OFX::PixelComponentEnum dstComponents = dstClip_->getPixelComponents();
// do the rendering
if (dstComponents == OFX::ePixelComponentRGBA) {
switch(dstBitDepth) {
case OFX::eBitDepthUByte : {
ImageCopier<unsigned char, 4> fred(*this);
setupAndProcess(fred, args);
}
break;
case OFX::eBitDepthUShort : {
ImageCopier<unsigned short, 4> fred(*this);
setupAndProcess(fred, args);
}
break;
case OFX::eBitDepthFloat : {
ImageCopier<float, 4> fred(*this);
setupAndProcess(fred, args);
}
break;
default :
OFX::throwSuiteStatusException(kOfxStatErrUnsupported);
}
} else if (dstComponents == OFX::ePixelComponentRGB) {
switch(dstBitDepth) {
case OFX::eBitDepthUByte : {
ImageCopier<unsigned char, 3> fred(*this);
setupAndProcess(fred, args);
}
break;
case OFX::eBitDepthUShort : {
ImageCopier<unsigned short, 3> fred(*this);
setupAndProcess(fred, args);
}
break;
case OFX::eBitDepthFloat : {
ImageCopier<float, 3> fred(*this);
setupAndProcess(fred, args);
}
break;
default :
OFX::throwSuiteStatusException(kOfxStatErrUnsupported);
}
} else if (dstComponents == OFX::ePixelComponentAlpha) {
switch(dstBitDepth) {
case OFX::eBitDepthUByte : {
ImageCopier<unsigned char, 1> fred(*this);
setupAndProcess(fred, args);
}
break;
case OFX::eBitDepthUShort : {
ImageCopier<unsigned short, 1> fred(*this);
setupAndProcess(fred, args);
}
break;
case OFX::eBitDepthFloat : {
ImageCopier<float, 1> fred(*this);
setupAndProcess(fred, args);
}
break;
default :
OFX::throwSuiteStatusException(kOfxStatErrUnsupported);
}
} else {
OFX::throwSuiteStatusException(kOfxStatErrUnsupported);
}
}
bool
NoOpPlugin::isIdentity(const RenderArguments &args, Clip * &identityClip, double &identityTime)
{
bool forceCopy;
forceCopy_->getValue(forceCopy);
return !forceCopy;
}
static const char*
bitDepthString(BitDepthEnum bitDepth)
{
switch (bitDepth) {
case OFX::eBitDepthUByte:
return "8u";
case OFX::eBitDepthUShort:
return "16u";
case OFX::eBitDepthHalf:
return "16f";
case OFX::eBitDepthFloat:
return "32f";
case OFX::eBitDepthCustom:
return "x";
case OFX::eBitDepthNone:
return "0";
#ifdef OFX_EXTENSIONS_VEGAS
case eBitDepthUByteBGRA:
return "8uBGRA";
case eBitDepthUShortBGRA:
return "16uBGRA";
case eBitDepthFloatBGRA:
return "32fBGRA";
#endif
default:
return "[unknown bit depth]";
}
}
static std::string
pixelComponentString(const std::string& p)
{
const std::string prefix = "OfxImageComponent";
std::string s = p;
return s.replace(s.find(prefix),prefix.length(),"");
}
static const char* premultString(PreMultiplicationEnum e)
{
switch (e) {
case eImageOpaque:
return "Opaque";
case eImagePreMultiplied:
return "PreMultiplied";
case eImageUnPreMultiplied:
return "UnPreMultiplied";
default:
return "[unknown premult]";
}
}
static const char* fieldOrderString(FieldEnum e)
{
switch (e) {
case eFieldBoth:
return "Both";
case eFieldLower:
return "Lower";
case eFieldUpper:
return "Upper";
case eFieldSingle:
return "Single";
case eFieldDoubled:
return "Doubled";
default:
return "[unknown field order]";
}
}
void
NoOpPlugin::changedParam(const OFX::InstanceChangedArgs &args, const std::string ¶mName)
{
if (paramName == kClipInfoParamName) {
std::ostringstream oss;
oss << "Clip Info:\n\n";
oss << "Input: ";
if (!srcClip_) {
oss << "N/A";
} else {
OFX::Clip &c = *srcClip_;
oss << pixelComponentString(c.getPixelComponentsProperty());
oss << bitDepthString(c.getPixelDepth());
oss << "(unmapped: ";
oss << pixelComponentString(c.getUnmappedPixelComponentsProperty());
oss << bitDepthString(c.getUnmappedPixelDepth());
oss << ")\npremultiplication: ";
oss << premultString(c.getPreMultiplication());
oss << "\nfield order: ";
oss << fieldOrderString(c.getFieldOrder());
oss << "\n";
oss << (c.isConnected() ? "connected" : "not connected");
oss << "\n";
oss << (c.hasContinuousSamples() ? "continuous samples" : "discontinuous samples");
oss << "\npixel aspect ratio: ";
oss << c.getPixelAspectRatio();
oss << "\nframe rate: ";
oss << c.getFrameRate();
oss << " (unmapped: ";
oss << c.getUnmappedFrameRate();
oss << ")";
OfxRangeD range = c.getFrameRange();
oss << "\nframe range: ";
oss << range.min << "..." << range.max;
oss << " (unmapped: ";
range = c.getUnmappedFrameRange();
oss << range.min << "..." << range.max;
oss << ")";
oss << "\nregion of definition: ";
OfxRectD rod = c.getRegionOfDefinition(args.time);
oss << rod.x1 << ' ' << rod.y1 << ' ' << rod.x2 << ' ' << rod.y2;
}
oss << "\n\n";
oss << "Output: ";
if (!dstClip_) {
oss << "N/A";
} else {
OFX::Clip &c = *dstClip_;
oss << pixelComponentString(c.getPixelComponentsProperty());
oss << bitDepthString(c.getPixelDepth());
oss << "(unmapped: ";
oss << pixelComponentString(c.getUnmappedPixelComponentsProperty());
oss << bitDepthString(c.getUnmappedPixelDepth());
oss << ")\npremultiplication: ";
oss << premultString(c.getPreMultiplication());
oss << "\nfield order: ";
oss << fieldOrderString(c.getFieldOrder());
oss << "\n";
oss << (c.isConnected() ? "connected" : "not connected");
oss << "\n";
oss << (c.hasContinuousSamples() ? "continuous samples" : "discontinuous samples");
oss << "\npixel aspect ratio: ";
oss << c.getPixelAspectRatio();
oss << "\nframe rate: ";
oss << c.getFrameRate();
oss << " (unmapped: ";
oss << c.getUnmappedFrameRate();
oss << ")";
OfxRangeD range = c.getFrameRange();
oss << "\nframe range: ";
oss << range.min << "..." << range.max;
oss << " (unmapped: ";
range = c.getUnmappedFrameRange();
oss << range.min << "..." << range.max;
oss << ")";
oss << "\nregion of definition: ";
OfxRectD rod = c.getRegionOfDefinition(args.time);
oss << rod.x1 << ' ' << rod.y1 << ' ' << rod.x2 << ' ' << rod.y2;
}
oss << "\n\n";
oss << "time: " << args.time << ", renderscale: " << args.renderScale.x << 'x' << args.renderScale.y << '\n';
sendMessage(OFX::Message::eMessageMessage, "", oss.str());
}
}
using namespace OFX;
mDeclarePluginFactory(NoOpPluginFactory, {}, {});
void NoOpPluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
// basic labels
desc.setLabels(kPluginName, kPluginName, kPluginName);
desc.setPluginGrouping(kPluginGrouping);
desc.setPluginDescription(kPluginDescription);
// add the supported contexts, only filter at the moment
desc.addSupportedContext(eContextFilter);
// add supported pixel depths
desc.addSupportedBitDepth(eBitDepthNone);
desc.addSupportedBitDepth(eBitDepthUByte);
desc.addSupportedBitDepth(eBitDepthUShort);
desc.addSupportedBitDepth(eBitDepthHalf);
desc.addSupportedBitDepth(eBitDepthFloat);
desc.addSupportedBitDepth(eBitDepthCustom);
#ifdef OFX_EXTENSIONS_VEGAS
desc.addSupportedBitDepth(eBitDepthUByteBGRA);
desc.addSupportedBitDepth(eBitDepthUShortBGRA);
desc.addSupportedBitDepth(eBitDepthFloatBGRA);
#endif
// set a few flags
desc.setSingleInstance(false);
desc.setHostFrameThreading(false);
desc.setSupportsMultiResolution(true);
desc.setSupportsTiles(true);
desc.setTemporalClipAccess(false);
desc.setRenderTwiceAlways(false);
desc.setSupportsMultipleClipPARs(false);
}
void NoOpPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, OFX::ContextEnum context)
{
// Source clip only in the filter context
// create the mandated source clip
ClipDescriptor *srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName);
srcClip->addSupportedComponent(ePixelComponentNone);
srcClip->addSupportedComponent(ePixelComponentRGBA);
srcClip->addSupportedComponent(ePixelComponentRGB);
srcClip->addSupportedComponent(ePixelComponentAlpha);
#ifdef OFX_EXTENSIONS_NUKE
srcClip->addSupportedComponent(ePixelComponentMotionVectors);
srcClip->addSupportedComponent(ePixelComponentStereoDisparity);
#endif
srcClip->addSupportedComponent(ePixelComponentCustom);
srcClip->setTemporalClipAccess(false);
srcClip->setSupportsTiles(true);
srcClip->setIsMask(false);
// create the mandated output clip
ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName);
dstClip->addSupportedComponent(ePixelComponentNone);
dstClip->addSupportedComponent(ePixelComponentRGBA);
dstClip->addSupportedComponent(ePixelComponentRGB);
dstClip->addSupportedComponent(ePixelComponentAlpha);
#ifdef OFX_EXTENSIONS_NUKE
dstClip->addSupportedComponent(ePixelComponentMotionVectors);
dstClip->addSupportedComponent(ePixelComponentStereoDisparity);
#endif
dstClip->addSupportedComponent(ePixelComponentCustom);
dstClip->setSupportsTiles(true);
// make some pages and to things in
PageParamDescriptor *page = desc.definePageParam("Controls");
BooleanParamDescriptor *forceCopy = desc.defineBooleanParam(kForceCopyParamName);
forceCopy->setLabels(kForceCopyParamLabel, kForceCopyParamLabel, kForceCopyParamLabel);
forceCopy->setHint(kForceCopyParamHint);
forceCopy->setDefault(false);
forceCopy->setAnimates(false);
page->addChild(*forceCopy);
PushButtonParamDescriptor *clipInfo = desc.definePushButtonParam(kClipInfoParamName);
clipInfo->setLabels(kClipInfoParamLabel, kClipInfoParamLabel, kClipInfoParamLabel);
clipInfo->setHint(kClipInfoParamHint);
page->addChild(*clipInfo);
}
OFX::ImageEffect* NoOpPluginFactory::createInstance(OfxImageEffectHandle handle, OFX::ContextEnum context)
{
return new NoOpPlugin(handle);
}
void getNoOpPluginID(OFX::PluginFactoryArray &ids)
{
static NoOpPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);
ids.push_back(&p);
}
<|endoftext|> |
<commit_before>#ifndef GENERIC_FORWARDER_HPP
# define GENERIC_FORWARDER_HPP
# pragma once
#include <cassert>
// ::std::size_t
#include <cstddef>
#include <type_traits>
#include <utility>
namespace generic
{
namespace detail
{
namespace forwarder
{
template <typename ...A>
struct argument_types
{
};
template <typename A>
struct argument_types<A>
{
using argument_type = A;
};
template <typename A, typename B>
struct argument_types<A, B>
{
using first_argument_type = A;
using second_argument_type = B;
};
}
}
template<typename F, ::std::size_t N = 4 * sizeof(void*)>
class forwarder;
template<typename R, typename ...A, ::std::size_t N>
class forwarder<R (A...), N> : public detail::forwarder::argument_types<A...>
{
R (*stub_)(void const*, A&&...){};
typename ::std::aligned_storage<N>::type store_;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator==(forwarder<T (U...), M> const&,
::std::nullptr_t) noexcept;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator==(::std::nullptr_t,
forwarder<T (U...), M> const&) noexcept;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator!=(forwarder<T (U...), M> const&,
::std::nullptr_t) noexcept;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator!=(::std::nullptr_t,
forwarder<T (U...), M> const&) noexcept;
public:
using result_type = R;
public:
forwarder() = default;
forwarder(forwarder const&) = default;
template<typename T,
typename = typename ::std::enable_if<
!::std::is_same<forwarder, typename ::std::decay<T>::type>{}
>::type
>
forwarder(T&& f) noexcept
{
assign(::std::forward<T>(f));
}
forwarder& operator=(forwarder const&) = default;
forwarder& operator=(forwarder&&) = default;
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<forwarder, typename ::std::decay<T>::type>{}
>::type
>
forwarder& operator=(T&& f) noexcept
{
assign(::std::forward<T>(f));
return *this;
}
explicit operator bool() const noexcept { return stub_; }
R operator()(A... args) const
noexcept(noexcept(stub_(&store_, ::std::forward<A>(args)...)))
{
//assert(stub_);
return stub_(&store_, ::std::forward<A>(args)...);
}
template <typename T>
void assign(T&& f) noexcept
{
using functor_type = typename ::std::decay<T>::type;
static_assert(sizeof(functor_type) <= sizeof(store_),
"functor too large");
static_assert(::std::is_trivially_copyable<T>{},
"functor not trivially copyable");
::new (static_cast<void*>(&store_)) functor_type(::std::forward<T>(f));
stub_ = [](void const* const ptr, A&&... args) noexcept(noexcept(
(*static_cast<functor_type const*>(ptr))(::std::forward<A>(args)...))
) -> R
{
return (*static_cast<functor_type const*>(ptr))(
::std::forward<A>(args)...
);
};
}
void reset() noexcept { stub_ = nullptr; }
void swap(forwarder& other) noexcept { ::std::swap(*this, other); }
template <typename T>
T* target() noexcept
{
return reinterpret_cast<T*>(&store_);
}
template <typename T>
T const* target() const noexcept
{
return reinterpret_cast<T const*>(&store_);
}
};
template<typename R, typename ...A, ::std::size_t N>
bool operator==(forwarder<R (A...), N> const& f,
::std::nullptr_t const) noexcept
{
return f.stub_ == nullptr;
}
template<typename R, typename ...A, ::std::size_t N>
bool operator==(::std::nullptr_t const,
forwarder<R (A...), N> const& f) noexcept
{
return f.stub_ == nullptr;
}
template<typename R, typename ...A, ::std::size_t N>
bool operator!=(forwarder<R (A...), N> const& f,
::std::nullptr_t const) noexcept
{
return !operator==(f, nullptr);
}
template<typename R, typename ...A, ::std::size_t N>
bool operator!=(::std::nullptr_t const,
forwarder<R (A...), N> const& f) noexcept
{
return !operator==(f, nullptr);
}
}
#endif // GENERIC_FORWARDER_HPP
<commit_msg>some fixes<commit_after>#ifndef GENERIC_FORWARDER_HPP
# define GENERIC_FORWARDER_HPP
# pragma once
#include <cassert>
// ::std::size_t
#include <cstddef>
#include <type_traits>
#include <utility>
namespace generic
{
namespace detail
{
namespace forwarder
{
template <typename ...A>
struct argument_types
{
};
template <typename A>
struct argument_types<A>
{
using argument_type = A;
};
template <typename A, typename B>
struct argument_types<A, B>
{
using first_argument_type = A;
using second_argument_type = B;
};
}
}
template<typename F, ::std::size_t N = 4 * sizeof(void*)>
class forwarder;
template<typename R, typename ...A, ::std::size_t N>
class forwarder<R (A...), N> : public detail::forwarder::argument_types<A...>
{
R (*stub_)(void const*, A&&...){};
typename ::std::aligned_storage<N>::type store_;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator==(forwarder<T (U...), M> const&,
::std::nullptr_t) noexcept;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator==(::std::nullptr_t,
forwarder<T (U...), M> const&) noexcept;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator!=(forwarder<T (U...), M> const&,
::std::nullptr_t) noexcept;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator!=(::std::nullptr_t,
forwarder<T (U...), M> const&) noexcept;
public:
using result_type = R;
public:
forwarder() = default;
forwarder(forwarder const&) = default;
template<typename T, typename ...U,
typename = typename ::std::enable_if<
!::std::is_same<forwarder, typename ::std::decay<T>::type>{}
>::type
>
forwarder(T&& t, U&& ...u) noexcept
{
assign(::std::forward<T>(t), ::std::forward<U>(u)...);
}
forwarder& operator=(forwarder const&) = default;
forwarder& operator=(forwarder&&) = default;
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<forwarder, typename ::std::decay<T>::type>{}
>::type
>
forwarder& operator=(T&& f) noexcept
{
assign(::std::forward<T>(f));
return *this;
}
explicit operator bool() const noexcept { return stub_; }
R operator()(A... args) const
noexcept(noexcept(stub_(&store_, ::std::forward<A>(args)...)))
{
//assert(stub_);
return stub_(&store_, ::std::forward<A>(args)...);
}
template <typename T>
void assign(T&& f) noexcept
{
using functor_type = typename ::std::decay<T>::type;
static_assert(sizeof(functor_type) <= sizeof(store_),
"functor too large");
static_assert(::std::is_trivially_copyable<T>{},
"functor not trivially copyable");
::new (static_cast<void*>(&store_)) functor_type(::std::forward<T>(f));
stub_ = [](void const* const ptr, A&&... args) noexcept(noexcept(
(*static_cast<functor_type const*>(ptr))(::std::forward<A>(args)...))
) -> R
{
return (*static_cast<functor_type const*>(ptr))(
::std::forward<A>(args)...
);
};
}
template <class C>
void assign(C* const object_ptr,
R (C::* const method_ptr)(A...)) noexcept
{
assign([object_ptr, method_ptr](A&&... args) noexcept(
(object_ptr->*method_ptr)(::std::declval<A>()...)) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...);
}
);
}
template <class C>
void assign(C* const object_ptr,
R (C::* const method_ptr)(A...) const) noexcept
{
assign([object_ptr, method_ptr](A&&... args) noexcept(
(object_ptr->*method_ptr)(::std::declval<A>()...)) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...);
}
);
}
template <class C>
void assign(C& object,
R (C::* const method_ptr)(A...)) noexcept
{
assign([&object, method_ptr](A&&... args) noexcept(
(object.*method_ptr)(::std::declval<A>()...)) {
return (object.*method_ptr)(::std::forward<A>(args)...);
}
);
}
template <class C>
void assign(C const& object,
R (C::* const method_ptr)(A...) const) noexcept
{
assign([&object, method_ptr](A&&... args) noexcept(
(object.*method_ptr)(::std::declval<A>()...)) {
return (object.*method_ptr)(::std::forward<A>(args)...);
}
);
}
void reset() noexcept { stub_ = nullptr; }
void swap(forwarder& other) noexcept { ::std::swap(*this, other); }
template <typename T>
T* target() noexcept
{
return reinterpret_cast<T*>(&store_);
}
template <typename T>
T const* target() const noexcept
{
return reinterpret_cast<T const*>(&store_);
}
};
template<typename R, typename ...A, ::std::size_t N>
bool operator==(forwarder<R (A...), N> const& f,
::std::nullptr_t const) noexcept
{
return f.stub_ == nullptr;
}
template<typename R, typename ...A, ::std::size_t N>
bool operator==(::std::nullptr_t const,
forwarder<R (A...), N> const& f) noexcept
{
return f.stub_ == nullptr;
}
template<typename R, typename ...A, ::std::size_t N>
bool operator!=(forwarder<R (A...), N> const& f,
::std::nullptr_t const) noexcept
{
return !operator==(f, nullptr);
}
template<typename R, typename ...A, ::std::size_t N>
bool operator!=(::std::nullptr_t const,
forwarder<R (A...), N> const& f) noexcept
{
return !operator==(f, nullptr);
}
}
#endif // GENERIC_FORWARDER_HPP
<|endoftext|> |
<commit_before>#ifndef GENERIC_FORWARDER_HPP
# define GENERIC_FORWARDER_HPP
# pragma once
#include <cassert>
// ::std::size_t
#include <cstddef>
#include <type_traits>
#include <utility>
namespace generic
{
template<typename F, ::std::size_t N = 4 * sizeof(void*)>
class forwarder;
template<typename R, typename ...A, ::std::size_t N>
class forwarder<R (A...), N>
{
R (*stub_)(void const*, A&&...){};
typename ::std::aligned_storage<N>::type store_;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator==(forwarder<T (U...), M> const&,
::std::nullptr_t) noexcept;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator==(::std::nullptr_t,
forwarder<T (U...), M> const&) noexcept;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator!=(forwarder<T (U...), M> const&,
::std::nullptr_t) noexcept;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator!=(::std::nullptr_t,
forwarder<T (U...), M> const&) noexcept;
public:
using result_type = R;
public:
forwarder() = default;
forwarder(forwarder const&) = default;
template<typename T>
forwarder(T&& f) noexcept
{
operator=(::std::forward<T>(f));
}
forwarder& operator=(forwarder const&) = default;
forwarder& operator=(forwarder&&) = default;
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<forwarder, typename ::std::decay<T>::type>{}
>::type
>
forwarder& operator=(T&& f) noexcept
{
using functor_type = typename ::std::decay<T>::type;
static_assert(sizeof(functor_type) <= sizeof(store_),
"functor too large");
static_assert(::std::is_trivially_copyable<T>{},
"functor not trivially copyable");
::new (static_cast<void*>(&store_)) functor_type(::std::forward<T>(f));
stub_ = [](void const* const ptr, A&&... args) noexcept(noexcept(
(*static_cast<functor_type const*>(ptr))(::std::forward<A>(args)...))
) -> R
{
return (*static_cast<functor_type const*>(ptr))(
::std::forward<A>(args)...
);
};
return *this;
}
explicit operator bool() const noexcept { return stub_; }
R operator()(A... args) const
noexcept(noexcept(stub_(&store_, ::std::forward<A>(args)...)))
{
//assert(stub_);
return stub_(&store_, ::std::forward<A>(args)...);
}
template <typename T>
void assign(T&& f) noexcept(noexcept(operator=(::std::forward<T>(f))))
{
operator=(::std::forward<T>(f));
}
void reset() noexcept { stub_ = nullptr; }
void swap(forwarder& other) noexcept { ::std::swap(*this, other); }
template <typename T>
T* target() noexcept
{
return reinterpret_cast<T*>(&store_);
}
template <typename T>
T const* target() const noexcept
{
return reinterpret_cast<T const*>(&store_);
}
};
template<typename R, typename ...A, ::std::size_t N>
bool operator==(forwarder<R (A...), N> const& f,
::std::nullptr_t const) noexcept
{
return f.stub_ == nullptr;
}
template<typename R, typename ...A, ::std::size_t N>
bool operator==(::std::nullptr_t const,
forwarder<R (A...), N> const& f) noexcept
{
return f.stub_ == nullptr;
}
template<typename R, typename ...A, ::std::size_t N>
bool operator!=(forwarder<R (A...), N> const& f,
::std::nullptr_t const) noexcept
{
return !operator==(f, nullptr);
}
template<typename R, typename ...A, ::std::size_t N>
bool operator!=(::std::nullptr_t const,
forwarder<R (A...), N> const& f) noexcept
{
return !operator==(f, nullptr);
}
}
#endif // GENERIC_FORWARDER_HPP
<commit_msg>some fixes<commit_after>#ifndef GENERIC_FORWARDER_HPP
# define GENERIC_FORWARDER_HPP
# pragma once
#include <cassert>
// ::std::size_t
#include <cstddef>
#include <type_traits>
#include <utility>
namespace generic
{
template <typename ...A>
struct forwarder_argument_types
{
};
template <typename A>
struct forwarder_argument_types<A>
{
using argument_type = A;
};
template <typename A, typename B>
struct forwarder_argument_types<A, B>
{
using first_argument_type = A;
using second_argument_type = B;
};
template<typename F, ::std::size_t N = 4 * sizeof(void*)>
class forwarder;
template<typename R, typename ...A, ::std::size_t N>
class forwarder<R (A...), N> : public forwarder_argument_types<A...>
{
R (*stub_)(void const*, A&&...){};
typename ::std::aligned_storage<N>::type store_;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator==(forwarder<T (U...), M> const&,
::std::nullptr_t) noexcept;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator==(::std::nullptr_t,
forwarder<T (U...), M> const&) noexcept;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator!=(forwarder<T (U...), M> const&,
::std::nullptr_t) noexcept;
template<typename T, typename ...U, ::std::size_t M>
friend bool operator!=(::std::nullptr_t,
forwarder<T (U...), M> const&) noexcept;
public:
using result_type = R;
public:
forwarder() = default;
forwarder(forwarder const&) = default;
template<typename T>
forwarder(T&& f) noexcept
{
operator=(::std::forward<T>(f));
}
forwarder& operator=(forwarder const&) = default;
forwarder& operator=(forwarder&&) = default;
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<forwarder, typename ::std::decay<T>::type>{}
>::type
>
forwarder& operator=(T&& f) noexcept
{
using functor_type = typename ::std::decay<T>::type;
static_assert(sizeof(functor_type) <= sizeof(store_),
"functor too large");
static_assert(::std::is_trivially_copyable<T>{},
"functor not trivially copyable");
::new (static_cast<void*>(&store_)) functor_type(::std::forward<T>(f));
stub_ = [](void const* const ptr, A&&... args) noexcept(noexcept(
(*static_cast<functor_type const*>(ptr))(::std::forward<A>(args)...))
) -> R
{
return (*static_cast<functor_type const*>(ptr))(
::std::forward<A>(args)...
);
};
return *this;
}
explicit operator bool() const noexcept { return stub_; }
R operator()(A... args) const
noexcept(noexcept(stub_(&store_, ::std::forward<A>(args)...)))
{
//assert(stub_);
return stub_(&store_, ::std::forward<A>(args)...);
}
template <typename T>
void assign(T&& f) noexcept(noexcept(operator=(::std::forward<T>(f))))
{
operator=(::std::forward<T>(f));
}
void reset() noexcept { stub_ = nullptr; }
void swap(forwarder& other) noexcept { ::std::swap(*this, other); }
template <typename T>
T* target() noexcept
{
return reinterpret_cast<T*>(&store_);
}
template <typename T>
T const* target() const noexcept
{
return reinterpret_cast<T const*>(&store_);
}
};
template<typename R, typename ...A, ::std::size_t N>
bool operator==(forwarder<R (A...), N> const& f,
::std::nullptr_t const) noexcept
{
return f.stub_ == nullptr;
}
template<typename R, typename ...A, ::std::size_t N>
bool operator==(::std::nullptr_t const,
forwarder<R (A...), N> const& f) noexcept
{
return f.stub_ == nullptr;
}
template<typename R, typename ...A, ::std::size_t N>
bool operator!=(forwarder<R (A...), N> const& f,
::std::nullptr_t const) noexcept
{
return !operator==(f, nullptr);
}
template<typename R, typename ...A, ::std::size_t N>
bool operator!=(::std::nullptr_t const,
forwarder<R (A...), N> const& f) noexcept
{
return !operator==(f, nullptr);
}
}
#endif // GENERIC_FORWARDER_HPP
<|endoftext|> |
<commit_before>/*=========================================================================
Program: OpenIGTLink Library
Language: C++
Date: $Date: 2016/01/25 19:53:38 $
Copyright (c) Insight Software Consortium. All rights reserved.
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 <igtlMessageBase.h>
#include <igtlMessageHeader.h>
#include "gtest/gtest.h"
#include "igtlutil/igtl_test_data_image.h"
#include "igtl_util.h"
TEST(MessageBaseTest, InitializationTest)
{
igtl::MessageBase::Pointer messageBaseTest = igtl::MessageBase::New();
messageBaseTest->SetDeviceName("DeviceTest");
EXPECT_STREQ(messageBaseTest->GetDeviceName(), "DeviceTest");
messageBaseTest->InitPack();
EXPECT_STREQ(messageBaseTest->GetDeviceName(),"");
}
TEST(MessageBaseTest, SetDeviceNameTest)
{
igtl::MessageBase::Pointer messageBaseTest = igtl::MessageBase::New();
messageBaseTest->InitPack();
EXPECT_STREQ(messageBaseTest->GetDeviceName(), "");
messageBaseTest->SetDeviceName("DeviceTest");
EXPECT_STREQ(messageBaseTest->GetDeviceName(), "DeviceTest");
}
TEST(MessageBaseTest, GetDeviceNameTest)
{
igtl::MessageBase::Pointer messageBaseTest = igtl::MessageBase::New();
messageBaseTest->SetDeviceName("DeviceTest");
EXPECT_STREQ(messageBaseTest->GetDeviceName(), "DeviceTest");
}
TEST(MessageBaseTest, TimeStampTest)
{
igtl::MessageBase::Pointer messageBaseTest = igtl::MessageBase::New();
messageBaseTest->SetTimeStamp(1,2);
unsigned int sec=0, nanosec=0;
messageBaseTest->GetTimeStamp(&sec,&nanosec);
EXPECT_EQ(sec, 1);
EXPECT_EQ(nanosec, 2);
igtl::TimeStamp::Pointer ts_input = igtl::TimeStamp::New();
ts_input->SetTime(123,500000000); //nanosecond can not be larger or equal to 1e9.
//5e8 nanosecond equals 2147483647 frac second.
messageBaseTest->SetTimeStamp(ts_input);
messageBaseTest->GetTimeStamp(&sec,&nanosec);
EXPECT_EQ(sec, 123);
EXPECT_EQ(nanosec, 2147483647);
}
TEST(MessageBaseTest, UNPACKTEST)
{
igtl::MessageBase::Pointer messageBaseTest = igtl::MessageBase::New();
int status = messageBaseTest->Unpack(); // The m_packSize cannot be set, so the unpack cannot be tested
EXPECT_EQ(status, messageBaseTest->UNPACK_UNDEF);
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>resolve the warning from EXPECT_EQ(int, enum)<commit_after>/*=========================================================================
Program: OpenIGTLink Library
Language: C++
Date: $Date: 2016/01/25 19:53:38 $
Copyright (c) Insight Software Consortium. All rights reserved.
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 <igtlMessageBase.h>
#include <igtlMessageHeader.h>
#include "gtest/gtest.h"
#include "igtlutil/igtl_test_data_image.h"
#include "igtl_util.h"
TEST(MessageBaseTest, InitializationTest)
{
igtl::MessageBase::Pointer messageBaseTest = igtl::MessageBase::New();
messageBaseTest->SetDeviceName("DeviceTest");
EXPECT_STREQ(messageBaseTest->GetDeviceName(), "DeviceTest");
messageBaseTest->InitPack();
EXPECT_STREQ(messageBaseTest->GetDeviceName(),"");
}
TEST(MessageBaseTest, SetDeviceNameTest)
{
igtl::MessageBase::Pointer messageBaseTest = igtl::MessageBase::New();
messageBaseTest->InitPack();
EXPECT_STREQ(messageBaseTest->GetDeviceName(), "");
messageBaseTest->SetDeviceName("DeviceTest");
EXPECT_STREQ(messageBaseTest->GetDeviceName(), "DeviceTest");
}
TEST(MessageBaseTest, GetDeviceNameTest)
{
igtl::MessageBase::Pointer messageBaseTest = igtl::MessageBase::New();
messageBaseTest->SetDeviceName("DeviceTest");
EXPECT_STREQ(messageBaseTest->GetDeviceName(), "DeviceTest");
}
TEST(MessageBaseTest, TimeStampTest)
{
igtl::MessageBase::Pointer messageBaseTest = igtl::MessageBase::New();
messageBaseTest->SetTimeStamp(1,2);
unsigned int sec=0, nanosec=0;
messageBaseTest->GetTimeStamp(&sec,&nanosec);
EXPECT_EQ(sec, 1);
EXPECT_EQ(nanosec, 2);
igtl::TimeStamp::Pointer ts_input = igtl::TimeStamp::New();
ts_input->SetTime(123,500000000); //nanosecond can not be larger or equal to 1e9.
//5e8 nanosecond equals 2147483647 frac second.
messageBaseTest->SetTimeStamp(ts_input);
messageBaseTest->GetTimeStamp(&sec,&nanosec);
EXPECT_EQ(sec, 123);
EXPECT_EQ(nanosec, 2147483647);
}
TEST(MessageBaseTest, UNPACKTEST)
{
igtl::MessageBase::Pointer messageBaseTest = igtl::MessageBase::New();
int status = messageBaseTest->Unpack(); // The m_packSize cannot be set, so the unpack cannot be tested
EXPECT_EQ(status, static_cast<int>(messageBaseTest->UNPACK_UNDEF));
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>#pragma once
#include <array>
#include <string>
#include <memory>
#include <typeinfo>
#include <typeindex>
namespace darwin {
enum class status {
null,ready,busy,leisure,error
};
enum class results {
null,success,failure
};
enum class colors {
white,black,red,green,blue,pink,yellow,cyan
};
enum class attris {
bright,underline
};
enum class commands {
echo_on,echo_off,reset_cursor,reset_attri,clrscr
};
class pixel final {
char mChar=' ';
std::array<bool,2> mAttris= {{false,false}};
std::array<colors,2> mColors= {{colors::white,colors::black}};
public:
pixel()=default;
pixel(const pixel&)=default;
pixel(char ch,const std::array<bool,2>& a,const std::array<colors,2>& c):mChar(ch),mAttris(a),mColors(c) {}
~pixel()=default;
void set_char(char c)
{
mChar=c;
}
char get_char() const
{
return mChar;
}
void set_front_color(colors c)
{
mColors[0]=c;
}
colors get_front_color() const
{
return mColors[0];
}
void set_back_color(colors c)
{
mColors[1]=c;
}
colors get_back_color() const
{
return mColors[1];
}
void set_colors(const std::array<colors,2>& c)
{
mColors=c;
}
const std::array<colors,2>& get_colors() const
{
return mColors;
}
void set_bright(bool value)
{
mAttris[0]=value;
}
bool is_bright() const
{
return mAttris[0];
}
void set_underline(bool value)
{
mAttris[1]=value;
}
bool is_underline() const
{
return mAttris[1];
}
void set_attris(const std::array<bool,2>& a)
{
mAttris=a;
}
const std::array<bool,2>& get_attris() const
{
return mAttris;
}
};
class drawable {
public:
drawable()=default;
drawable(const drawable&)=default;
virtual ~drawable()=default;
virtual std::type_index get_type() const final
{
return typeid(*this);
}
virtual std::shared_ptr<drawable> clone() noexcept
{
return nullptr;
}
virtual bool usable() const noexcept=0;
virtual void clear()=0;
virtual void fill(const pixel&)=0;
virtual void resize(std::size_t,std::size_t)=0;
virtual std::size_t get_width() const=0;
virtual std::size_t get_height() const=0;
virtual const pixel& get_pixel(const std::array<std::size_t,2>&) const=0;
virtual void draw_pixel(const std::array<std::size_t,2>&,const pixel&)=0;
virtual void draw_picture(const std::array<std::size_t,2>& posit,const drawable& img)
{
std::size_t col(posit[0]),row(posit[1]);
if(!this->usable())
throw std::logic_error(__func__);
if(col>this->get_width()-1||row>this->get_height()-1)
throw std::out_of_range(__func__);
for(std::size_t r=row; r<this->get_height()&&r-row<img.get_height(); ++r)
for(std::size_t c=col; c<this->get_width()&&c-col<img.get_width(); ++c)
this->draw_pixel({r,c},img.get_pixel({r-row,c-col}));
}
};
}<commit_msg>Signed-off-by: Mike Lee <mikecovlee@163.com><commit_after>#pragma once
#include <array>
#include <cmath>
#include <string>
#include <memory>
#include <typeinfo>
#include <typeindex>
namespace darwin {
enum class status {
null,ready,busy,leisure,error
};
enum class results {
null,success,failure
};
enum class colors {
white,black,red,green,blue,pink,yellow,cyan
};
enum class attris {
bright,underline
};
enum class commands {
echo_on,echo_off,reset_cursor,reset_attri,clrscr
};
class pixel final {
char mChar=' ';
std::array<bool,2> mAttris= {{false,false}};
std::array<colors,2> mColors= {{colors::white,colors::black}};
public:
pixel()=default;
pixel(const pixel&)=default;
pixel(char ch,const std::array<bool,2>& a,const std::array<colors,2>& c):mChar(ch),mAttris(a),mColors(c) {}
~pixel()=default;
void set_char(char c)
{
mChar=c;
}
char get_char() const
{
return mChar;
}
void set_front_color(colors c)
{
mColors[0]=c;
}
colors get_front_color() const
{
return mColors[0];
}
void set_back_color(colors c)
{
mColors[1]=c;
}
colors get_back_color() const
{
return mColors[1];
}
void set_colors(const std::array<colors,2>& c)
{
mColors=c;
}
const std::array<colors,2>& get_colors() const
{
return mColors;
}
void set_bright(bool value)
{
mAttris[0]=value;
}
bool is_bright() const
{
return mAttris[0];
}
void set_underline(bool value)
{
mAttris[1]=value;
}
bool is_underline() const
{
return mAttris[1];
}
void set_attris(const std::array<bool,2>& a)
{
mAttris=a;
}
const std::array<bool,2>& get_attris() const
{
return mAttris;
}
};
class drawable {
public:
drawable()=default;
drawable(const drawable&)=default;
virtual ~drawable()=default;
virtual std::type_index get_type() const final
{
return typeid(*this);
}
virtual std::shared_ptr<drawable> clone() noexcept
{
return nullptr;
}
virtual bool usable() const noexcept=0;
virtual void clear()=0;
virtual void fill(const pixel&)=0;
virtual void resize(std::size_t,std::size_t)=0;
virtual std::size_t get_width() const=0;
virtual std::size_t get_height() const=0;
virtual const pixel& get_pixel(const std::array<std::size_t,2>&) const=0;
virtual void draw_pixel(const std::array<std::size_t,2>&,const pixel&)=0;
virtual void draw_line(const std::array<std::size_t,2>& p0,const std::array<std::size_t,2>& p1,const pixel& pix)
{
if(p0==p1) return;
if(p0[0]>this->get_width()-1||p0[1]>this->get_height()-1||p1[0]>this->get_width()-1||p1[1]>this->get_height()-1)
throw std::out_of_range(__func__);
long w(p0[0]-p1[0]),h(p0[1]-p1[1]);
double distance(std::sqrt(std::pow(w,2)+std::pow(h,2)));
for(double c=0;c<=1;c+=1.0/distance)
this->draw_pixel({p0[0]+w*c,p0[1]+h*c},pix);
}
virtual void draw_picture(const std::array<std::size_t,2>& posit,const drawable& img)
{
std::size_t col(posit[0]),row(posit[1]);
if(!this->usable())
throw std::logic_error(__func__);
if(col>this->get_width()-1||row>this->get_height()-1)
throw std::out_of_range(__func__);
for(std::size_t r=row; r<this->get_height()&&r-row<img.get_height(); ++r)
for(std::size_t c=col; c<this->get_width()&&c-col<img.get_width(); ++c)
this->draw_pixel({r,c},img.get_pixel({r-row,c-col}));
}
};
}<|endoftext|> |
<commit_before>/*
* This file is part of the OpenKinect Project. http://www.openkinect.org
*
* Copyright (c) 2011 individual OpenKinect contributors. See the CONTRIB file
* for details.
*
* This code is licensed to you under the terms of the Apache License, version
* 2.0, or, at your option, the terms of the GNU General Public License,
* version 2.0. See the APACHE20 and GPL2 files for the text of the licenses,
* or the following URLs:
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.gnu.org/licenses/gpl-2.0.txt
*
* If you redistribute this file in source form, modified or unmodified, you
* may:
* 1) Leave this header intact and distribute it under the same terms,
* accompanying it with the APACHE20 and GPL20 files, or
* 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or
* 3) Delete the GPL v2 clause and accompany it with the APACHE20 file
* In all cases you must keep the copyright notice intact and include a copy
* of the CONTRIB file.
*
* Binary distributions must follow the binary distribution requirements of
* either License.
*/
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <signal.h>
#include <opencv2/opencv.hpp>
#include <libfreenect2/libfreenect2.hpp>
#include <libfreenect2/frame_listener_impl.h>
#include <libfreenect2/threading.h>
#include <libfreenect2/registration.h>
#include <libfreenect2/packet_pipeline.h>
bool protonect_shutdown = false;
void sigint_handler(int s)
{
protonect_shutdown = true;
}
std::string tostr(int x)
{
std::stringstream str;
str << x;
return str.str();
}
int main(int argc, char *argv[])
{
std::string program_path(argv[0]);
size_t executable_name_idx = program_path.rfind("Protonect");
std::string binpath = "/";
if(executable_name_idx != std::string::npos)
{
binpath = program_path.substr(0, executable_name_idx);
}
libfreenect2::Freenect2 freenect2;
libfreenect2::Freenect2Device *dev = 0;
libfreenect2::PacketPipeline *pipeline = 0;
if(freenect2.enumerateDevices() == 0)
{
std::cout << "no device connected!" << std::endl;
return -1;
}
std::string serial = freenect2.getDefaultDeviceSerialNumber();
int threshold = 128;
for(int argI = 1; argI < argc; ++argI)
{
const std::string arg(argv[argI]);
if(arg == "cpu")
{
if(!pipeline)
pipeline = new libfreenect2::CpuPacketPipeline();
}
else if(arg == "gl")
{
#ifdef LIBFREENECT2_WITH_OPENGL_SUPPORT
if(!pipeline)
pipeline = new libfreenect2::OpenGLPacketPipeline();
#else
std::cout << "OpenGL pipeline is not supported!" << std::endl;
#endif
}
else if(arg == "cl")
{
#ifdef LIBFREENECT2_WITH_OPENCL_SUPPORT
if(!pipeline)
pipeline = new libfreenect2::OpenCLPacketPipeline();
#else
std::cout << "OpenCL pipeline is not supported!" << std::endl;
#endif
}
else if (arg == "-t") {
std::string thresholdString (argv[argI+1]);
std::istringstream ss(argv[argI+1]);
int x;
if (!(ss >> threshold)) {
std::cerr << "Invalid number " << argv[argI+1] << '\n';
}
argI += 1;
}
else if(arg.find_first_not_of("0123456789") == std::string::npos) //check if parameter could be a serial number
{
serial = arg;
}
else
{
std::cout << "Unknown argument: " << arg << std::endl;
}
}
if(pipeline)
{
dev = freenect2.openDevice(serial, pipeline);
}
else
{
dev = freenect2.openDevice(serial);
}
if(dev == 0)
{
std::cout << "failure opening device!" << std::endl;
return -1;
}
signal(SIGINT,sigint_handler);
protonect_shutdown = false;
libfreenect2::SyncMultiFrameListener listener(libfreenect2::Frame::Color | libfreenect2::Frame::Ir | libfreenect2::Frame::Depth);
libfreenect2::FrameMap frames;
libfreenect2::Frame undistorted(512, 424, 4), registered(512, 424, 4);
dev->setColorFrameListener(&listener);
dev->setIrAndDepthFrameListener(&listener);
dev->start();
std::cout << "device serial: " << dev->getSerialNumber() << std::endl;
std::cout << "device firmware: " << dev->getFirmwareVersion() << std::endl;
libfreenect2::Registration* registration = new libfreenect2::Registration(dev->getIrCameraParams(), dev->getColorCameraParams());
std::string filename ("test_" );
int i = 0;
while(!protonect_shutdown)
{
listener.waitForNewFrame(frames);
libfreenect2::Frame *rgb = frames[libfreenect2::Frame::Color];
libfreenect2::Frame *ir = frames[libfreenect2::Frame::Ir];
libfreenect2::Frame *depth = frames[libfreenect2::Frame::Depth];
cv::imshow("rgb", cv::Mat(rgb->height, rgb->width, CV_8UC4, rgb->data));
//cv::imshow("ir", cv::Mat(ir->height, ir->width, CV_32FC1, ir->data) / 20000.0f);
//cv::imshow("depth", cv::Mat(depth->height, depth->width, CV_32FC1, depth->data) / 4500.0f);
registration->apply(rgb, depth, &undistorted, ®istered);
//cv::imshow("undistorted", cv::Mat(undistorted.height, undistorted.width, CV_32FC1, undistorted.data) / 4500.0f);
//cv::imshow("registered", cv::Mat(registered.height, registered.width, CV_8UC4, registered.data));
if (i > 10) {
i = 0;
for (int j=0; j<=10; j++) {
std::string jIndex = tostr(j);
if(remove((filename + jIndex + ".jpg").c_str()) != 0) {
perror( "Error deleting file" );
} else {
puts( "File successfully deleted" );
}
}
}
cv::Mat undistortedFrame = cv::Mat(undistorted.height, undistorted.width, CV_32FC1, undistorted.data) / 4500.0f;
cv::Mat img_bw;
undistortedFrame.convertTo(img_bw, CV_8UC4, 255);
cv::Mat thresh = img_bw > threshold;
cv::imshow("undistorted", thresh);
std::string index = tostr(i);
cv::imwrite((filename + index + ".jpg").c_str(), thresh);
i += 1;
int key = cv::waitKey(1);
protonect_shutdown = protonect_shutdown || (key > 0 && ((key & 0xFF) == 27)); // shutdown on escape
if (!protonect_shutdown) {
std::cout << "key=" << (key & 0xFF) << std::endl;
if (key == 82) {
threshold += 1;
std::cout << "increasing threshold" << std::endl;
} else if (key == 83) {
threshold -= 1;
std::cout << "decreasing threshold" << std::endl;
}
}
listener.release(frames);
libfreenect2::this_thread::sleep_for(libfreenect2::chrono::milliseconds(1000));
}
// TODO: restarting ir stream doesn't work!
// TODO: bad things will happen, if frame listeners are freed before dev->stop() :(
dev->stop();
dev->close();
delete registration;
return 0;
}
<commit_msg>added optional threshol parameter<commit_after>/*
* This file is part of the OpenKinect Project. http://www.openkinect.org
*
* Copyright (c) 2011 individual OpenKinect contributors. See the CONTRIB file
* for details.
*
* This code is licensed to you under the terms of the Apache License, version
* 2.0, or, at your option, the terms of the GNU General Public License,
* version 2.0. See the APACHE20 and GPL2 files for the text of the licenses,
* or the following URLs:
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.gnu.org/licenses/gpl-2.0.txt
*
* If you redistribute this file in source form, modified or unmodified, you
* may:
* 1) Leave this header intact and distribute it under the same terms,
* accompanying it with the APACHE20 and GPL20 files, or
* 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or
* 3) Delete the GPL v2 clause and accompany it with the APACHE20 file
* In all cases you must keep the copyright notice intact and include a copy
* of the CONTRIB file.
*
* Binary distributions must follow the binary distribution requirements of
* either License.
*/
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <signal.h>
#include <opencv2/opencv.hpp>
#include <libfreenect2/libfreenect2.hpp>
#include <libfreenect2/frame_listener_impl.h>
#include <libfreenect2/threading.h>
#include <libfreenect2/registration.h>
#include <libfreenect2/packet_pipeline.h>
bool protonect_shutdown = false;
void sigint_handler(int s)
{
protonect_shutdown = true;
}
std::string tostr(int x)
{
std::stringstream str;
str << x;
return str.str();
}
int main(int argc, char *argv[])
{
std::string program_path(argv[0]);
size_t executable_name_idx = program_path.rfind("Protonect");
std::string binpath = "/";
if(executable_name_idx != std::string::npos)
{
binpath = program_path.substr(0, executable_name_idx);
}
libfreenect2::Freenect2 freenect2;
libfreenect2::Freenect2Device *dev = 0;
libfreenect2::PacketPipeline *pipeline = 0;
if(freenect2.enumerateDevices() == 0)
{
std::cout << "no device connected!" << std::endl;
return -1;
}
std::string serial = freenect2.getDefaultDeviceSerialNumber();
int threshold = -1;
for(int argI = 1; argI < argc; ++argI)
{
const std::string arg(argv[argI]);
if(arg == "cpu")
{
if(!pipeline)
pipeline = new libfreenect2::CpuPacketPipeline();
}
else if(arg == "gl")
{
#ifdef LIBFREENECT2_WITH_OPENGL_SUPPORT
if(!pipeline)
pipeline = new libfreenect2::OpenGLPacketPipeline();
#else
std::cout << "OpenGL pipeline is not supported!" << std::endl;
#endif
}
else if(arg == "cl")
{
#ifdef LIBFREENECT2_WITH_OPENCL_SUPPORT
if(!pipeline)
pipeline = new libfreenect2::OpenCLPacketPipeline();
#else
std::cout << "OpenCL pipeline is not supported!" << std::endl;
#endif
}
else if (arg == "-t") {
std::string thresholdString (argv[argI+1]);
std::istringstream ss(argv[argI+1]);
int x;
if (!(ss >> threshold)) {
std::cerr << "Invalid number " << argv[argI+1] << '\n';
}
argI += 1;
}
else if(arg.find_first_not_of("0123456789") == std::string::npos) //check if parameter could be a serial number
{
serial = arg;
}
else
{
std::cout << "Unknown argument: " << arg << std::endl;
}
}
if(pipeline)
{
dev = freenect2.openDevice(serial, pipeline);
}
else
{
dev = freenect2.openDevice(serial);
}
if(dev == 0)
{
std::cout << "failure opening device!" << std::endl;
return -1;
}
signal(SIGINT,sigint_handler);
protonect_shutdown = false;
libfreenect2::SyncMultiFrameListener listener(libfreenect2::Frame::Color | libfreenect2::Frame::Ir | libfreenect2::Frame::Depth);
libfreenect2::FrameMap frames;
libfreenect2::Frame undistorted(512, 424, 4), registered(512, 424, 4);
dev->setColorFrameListener(&listener);
dev->setIrAndDepthFrameListener(&listener);
dev->start();
std::cout << "device serial: " << dev->getSerialNumber() << std::endl;
std::cout << "device firmware: " << dev->getFirmwareVersion() << std::endl;
libfreenect2::Registration* registration = new libfreenect2::Registration(dev->getIrCameraParams(), dev->getColorCameraParams());
std::string filename ("test_" );
int i = 0;
while(!protonect_shutdown)
{
listener.waitForNewFrame(frames);
libfreenect2::Frame *rgb = frames[libfreenect2::Frame::Color];
libfreenect2::Frame *ir = frames[libfreenect2::Frame::Ir];
libfreenect2::Frame *depth = frames[libfreenect2::Frame::Depth];
cv::imshow("rgb", cv::Mat(rgb->height, rgb->width, CV_8UC4, rgb->data));
//cv::imshow("ir", cv::Mat(ir->height, ir->width, CV_32FC1, ir->data) / 20000.0f);
//cv::imshow("depth", cv::Mat(depth->height, depth->width, CV_32FC1, depth->data) / 4500.0f);
registration->apply(rgb, depth, &undistorted, ®istered);
//cv::imshow("undistorted", cv::Mat(undistorted.height, undistorted.width, CV_32FC1, undistorted.data) / 4500.0f);
//cv::imshow("registered", cv::Mat(registered.height, registered.width, CV_8UC4, registered.data));
if (i > 10) {
i = 0;
for (int j=0; j<=10; j++) {
std::string jIndex = tostr(j);
if(remove((filename + jIndex + ".jpg").c_str()) != 0) {
perror( "Error deleting file" );
} else {
puts( "File successfully deleted" );
}
}
}
cv::Mat undistortedFrame = cv::Mat(undistorted.height, undistorted.width, CV_32FC1, undistorted.data) / 4500.0f;
cv::Mat img_bw;
undistortedFrame.convertTo(img_bw, CV_8UC4, 255);
cv::Mat thresh;
if (threshold >= 0) {
thresh = img_bw > threshold;
} else {
thresh = img_bw;
}
cv::imshow("undistorted", thresh);
std::string index = tostr(i);
cv::imwrite((filename + index + ".jpg").c_str(), thresh);
i += 1;
int key = cv::waitKey(1);
protonect_shutdown = protonect_shutdown || (key > 0 && ((key & 0xFF) == 27)); // shutdown on escape
if (!protonect_shutdown) {
std::cout << "key=" << (key & 0xFF) << std::endl;
if (key == 82) {
threshold += 1;
std::cout << "increasing threshold" << std::endl;
} else if (key == 83) {
threshold -= 1;
std::cout << "decreasing threshold" << std::endl;
}
}
listener.release(frames);
libfreenect2::this_thread::sleep_for(libfreenect2::chrono::milliseconds(1000));
}
// TODO: restarting ir stream doesn't work!
// TODO: bad things will happen, if frame listeners are freed before dev->stop() :(
dev->stop();
dev->close();
delete registration;
return 0;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.