text
stringlengths 54
60.6k
|
|---|
<commit_before>/***********************************************************************
load_jpeg.cpp - Example showing how to insert BLOB data into the
database from a file.
Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB, and
(c) 2004-2009 by Educational Technology Resources, Inc. Others may
also hold copyrights on code in this file. See the CREDITS.txt 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 "cmdline.h"
#include "images.h"
#include "printdata.h"
#include <fstream>
using namespace std;
using namespace mysqlpp;
// This is just an implementation detail for the example. Skip down to
// main() for the concept this example is trying to demonstrate.
static bool
is_jpeg(const char* img_data)
{
const unsigned char* idp =
reinterpret_cast<const unsigned char*>(img_data);
return (idp[0] == 0xFF) && (idp[1] == 0xD8) &&
((memcmp(idp + 6, "JFIF", 4) == 0) ||
(memcmp(idp + 6, "Exif", 4) == 0));
}
// Another implementation detail. Skip to main().
static bool
load_jpeg_file(const mysqlpp::examples::CommandLine& cmdline,
images& img, string& img_name)
{
if (cmdline.extra_args().size() == 0) {
// Nothing for us to do here. Caller will insert NULL BLOB.
return true;
}
// Got a file's name on the command line, so open it.
img_name = cmdline.extra_args()[0];
ifstream img_file(img_name.c_str(), ios::ate | ios::binary);
if (img_file) {
// File opened, so try to slurp its contents into RAM. The key
// thing to get from this function is that we're storing the
// binary data in a mysqlpp::sql_blob value, which we assign from
// a C++ string (stringstream::str()), thus not truncating the
// string at the first embedded null character.
stringstream sstr;
sstr << img_file.rdbuf();
img.data.data = sstr.str();
// Check JPEG data for sanity
if (img.data.data.size() > 10) {
// The following triple 'data' sure does look foolish,
// doesn't it? Sorry, we're not trying to be obscure here,
// it's just a coincidence of naming. Right-to-left, what
// we have here is:
//
// 1. A call to mysqlpp::sql_blob::data() (mirroring C++'s
// std::string:data() interface) to get the raw C data
// pointer without null-terminating it first.
// 2. Access to the mysqlpp::sql_blob object through its
// mysqlpp::Null<> wrapper, which lets us have a "NULL
// JPEG" in the DB when the file doesn't exist.
// 3. Access to the JPEG BLOB column, images.data.
if (is_jpeg(img.data.data.data())) {
return true;
}
else {
cerr << '"' << img_file <<
"\" isn't a JPEG!" << endl;
cmdline.print_usage("[jpeg_file]");
return false;
}
}
else {
cerr << "File is too short to be a JPEG!" << endl;
cmdline.print_usage("[jpeg_file]");
return false;
}
}
}
int
main(int argc, char *argv[])
{
// Get database access parameters from command line
mysqlpp::examples::CommandLine cmdline(argc, argv);
if (!cmdline) {
return 1;
}
try {
// Establish the connection to the database server.
mysqlpp::Connection con(mysqlpp::examples::db_name,
cmdline.server(), cmdline.user(), cmdline.pass());
// Load the file named on the command line
images img(mysqlpp::null, mysqlpp::null);
string img_name("NULL");
if (load_jpeg_file(cmdline, img, img_name)) {
// Insert image data or SQL NULL into the images.data BLOB
// column. The key here is that we're holding the raw
// binary data in a mysqlpp::sql_blob, which avoids data
// conversion problems that can lead to treating BLOB data
// as C strings, thus causing null-truncation. The fact
// that we're using SSQLS here is a side issue, simply
// demonstrating that mysqlpp::Null<mysqlpp::sql_blob> is
// now legal in SSQLS, as of MySQL++ 3.0.7.
Query query = con.query();
query.insert(img);
SimpleResult res = query.execute();
// Report successful insertion
cout << "Inserted \"" << img_name <<
"\" into images table, " << img.data.data.size() <<
" bytes, ID " << res.insert_id() << endl;
}
}
catch (const BadQuery& er) {
// Handle any query errors
cerr << "Query error: " << er.what() << endl;
return -1;
}
catch (const BadConversion& er) {
// Handle bad conversions
cerr << "Conversion error: " << er.what() << endl <<
"\tretrieved data size: " << er.retrieved <<
", actual size: " << er.actual_size << endl;
return -1;
}
catch (const Exception& er) {
// Catch-all for any other MySQL++ exceptions
cerr << "Error: " << er.what() << endl;
return -1;
}
return 0;
}
<commit_msg>DRY principle fix to previous<commit_after>/***********************************************************************
load_jpeg.cpp - Example showing how to insert BLOB data into the
database from a file.
Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB, and
(c) 2004-2009 by Educational Technology Resources, Inc. Others may
also hold copyrights on code in this file. See the CREDITS.txt 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 "cmdline.h"
#include "images.h"
#include "printdata.h"
#include <fstream>
using namespace std;
using namespace mysqlpp;
// This is just an implementation detail for the example. Skip down to
// main() for the concept this example is trying to demonstrate.
static bool
is_jpeg(const char* img_data)
{
const unsigned char* idp =
reinterpret_cast<const unsigned char*>(img_data);
return (idp[0] == 0xFF) && (idp[1] == 0xD8) &&
((memcmp(idp + 6, "JFIF", 4) == 0) ||
(memcmp(idp + 6, "Exif", 4) == 0));
}
// Another implementation detail. Skip to main().
static bool
load_jpeg_file(const mysqlpp::examples::CommandLine& cmdline,
images& img, string& img_name)
{
if (cmdline.extra_args().size() == 0) {
// Nothing for us to do here. Caller will insert NULL BLOB.
return true;
}
// Got a file's name on the command line, so open it.
img_name = cmdline.extra_args()[0];
ifstream img_file(img_name.c_str(), ios::ate | ios::binary);
if (img_file) {
// File opened, so try to slurp its contents into RAM. The key
// thing to get from this function is that we're storing the
// binary data in a mysqlpp::sql_blob value, which we assign from
// a C++ string (stringstream::str()), thus not truncating the
// string at the first embedded null character.
stringstream sstr;
sstr << img_file.rdbuf();
img.data.data = sstr.str();
// Check JPEG data for sanity
if (img.data.data.size() > 10) {
// The following triple 'data' sure does look foolish,
// doesn't it? Sorry, we're not trying to be obscure here,
// it's just a coincidence of naming. Right-to-left, what
// we have here is:
//
// 1. A call to mysqlpp::sql_blob::data() (mirroring C++'s
// std::string:data() interface) to get the raw C data
// pointer without null-terminating it first.
// 2. Access to the mysqlpp::sql_blob object through its
// mysqlpp::Null<> wrapper, which lets us have a "NULL
// JPEG" in the DB when the file doesn't exist.
// 3. Access to the JPEG BLOB column, images.data.
if (is_jpeg(img.data.data.data())) {
return true;
}
else {
cerr << '"' << img_file <<
"\" isn't a JPEG!" << endl;
}
}
else {
cerr << "File is too short to be a JPEG!" << endl;
}
}
cmdline.print_usage("[jpeg_file]");
return false;
}
int
main(int argc, char *argv[])
{
// Get database access parameters from command line
mysqlpp::examples::CommandLine cmdline(argc, argv);
if (!cmdline) {
return 1;
}
try {
// Establish the connection to the database server.
mysqlpp::Connection con(mysqlpp::examples::db_name,
cmdline.server(), cmdline.user(), cmdline.pass());
// Load the file named on the command line
images img(mysqlpp::null, mysqlpp::null);
string img_name("NULL");
if (load_jpeg_file(cmdline, img, img_name)) {
// Insert image data or SQL NULL into the images.data BLOB
// column. The key here is that we're holding the raw
// binary data in a mysqlpp::sql_blob, which avoids data
// conversion problems that can lead to treating BLOB data
// as C strings, thus causing null-truncation. The fact
// that we're using SSQLS here is a side issue, simply
// demonstrating that mysqlpp::Null<mysqlpp::sql_blob> is
// now legal in SSQLS, as of MySQL++ 3.0.7.
Query query = con.query();
query.insert(img);
SimpleResult res = query.execute();
// Report successful insertion
cout << "Inserted \"" << img_name <<
"\" into images table, " << img.data.data.size() <<
" bytes, ID " << res.insert_id() << endl;
}
}
catch (const BadQuery& er) {
// Handle any query errors
cerr << "Query error: " << er.what() << endl;
return -1;
}
catch (const BadConversion& er) {
// Handle bad conversions
cerr << "Conversion error: " << er.what() << endl <<
"\tretrieved data size: " << er.retrieved <<
", actual size: " << er.actual_size << endl;
return -1;
}
catch (const Exception& er) {
// Catch-all for any other MySQL++ exceptions
cerr << "Error: " << er.what() << endl;
return -1;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: doctemplates.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: mav $ $Date: 2002-07-10 09:31:28 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2001 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SFX_DOCTEMPLATES_HXX_
#define _SFX_DOCTEMPLATES_HXX_
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDOCUMENTTEMPLATES_HPP_
#include <com/sun/star/frame/XDocumentTemplates.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTORABLE_HPP_
#include <com/sun/star/frame/XStorable.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XLOCALIZABLE_HPP_
#include <com/sun/star/lang/XLocalizable.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_
#include <com/sun/star/ucb/XContent.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif
#ifndef _SFX_SFXUNO_HXX
#include <sfxuno.hxx>
#endif
//--------------------------------------------------------------------------------------------------------
#define LOCALE ::com::sun::star::lang::Locale
#define REFERENCE ::com::sun::star::uno::Reference
#define RUNTIMEEXCEPTION ::com::sun::star::uno::RuntimeException
#define PROPERTYVALUE ::com::sun::star::beans::PropertyValue
#define XCONTENT ::com::sun::star::ucb::XContent
#define XDOCUMENTTEMPLATES ::com::sun::star::frame::XDocumentTemplates
#define XINTERFACE ::com::sun::star::uno::XInterface
#define XLOCALIZABLE ::com::sun::star::lang::XLocalizable
#define XMODEL ::com::sun::star::frame::XModel
#define XMULTISERVICEFACTORY ::com::sun::star::lang::XMultiServiceFactory
#define XNAMEACCESS ::com::sun::star::container::XNameAccess
#define XSERVICEINFO ::com::sun::star::lang::XServiceInfo
#define XSTORABLE ::com::sun::star::frame::XStorable
//--------------------------------------------------------------------------------------------------------
class SfxDocTplService_Impl;
class SfxDocTplService: public ::cppu::WeakImplHelper3< XLOCALIZABLE, XDOCUMENTTEMPLATES, XSERVICEINFO >
{
SfxDocTplService_Impl *pImp;
public:
SFX_DECL_XSERVICEINFO
SfxDocTplService( const REFERENCE < ::com::sun::star::lang::XMultiServiceFactory >& xFactory );
~SfxDocTplService();
// --- XLocalizable ---
void SAL_CALL setLocale( const LOCALE & eLocale ) throw( RUNTIMEEXCEPTION );
LOCALE SAL_CALL getLocale() throw( RUNTIMEEXCEPTION );
// --- XDocumentTemplates ---
REFERENCE< XCONTENT > SAL_CALL getContent() throw( RUNTIMEEXCEPTION );
sal_Bool SAL_CALL storeTemplate( const ::rtl::OUString& GroupName,
const ::rtl::OUString& TemplateName,
const REFERENCE< XSTORABLE >& Storable ) throw( RUNTIMEEXCEPTION );
sal_Bool SAL_CALL addTemplate( const ::rtl::OUString& GroupName,
const ::rtl::OUString& TemplateName,
const ::rtl::OUString& SourceURL ) throw( RUNTIMEEXCEPTION );
sal_Bool SAL_CALL removeTemplate( const ::rtl::OUString& GroupName,
const ::rtl::OUString& TemplateName ) throw( RUNTIMEEXCEPTION );
sal_Bool SAL_CALL renameTemplate( const ::rtl::OUString& GroupName,
const ::rtl::OUString& OldTemplateName,
const ::rtl::OUString& NewTemplateName ) throw( RUNTIMEEXCEPTION );
sal_Bool SAL_CALL addGroup( const ::rtl::OUString& GroupName ) throw( RUNTIMEEXCEPTION );
sal_Bool SAL_CALL removeGroup( const ::rtl::OUString& GroupName ) throw( RUNTIMEEXCEPTION );
sal_Bool SAL_CALL renameGroup( const ::rtl::OUString& OldGroupName,
const ::rtl::OUString& NewGroupName ) throw( RUNTIMEEXCEPTION );
void SAL_CALL update() throw( RUNTIMEEXCEPTION );
};
#endif
<commit_msg>INTEGRATION: CWS indephome (1.3.512); FILE MERGED 2004/06/03 07:54:27 kso 1.3.512.1: #i29764# - #define LOCALE ... caused problems, renamed to UNOLOCALE.<commit_after>/*************************************************************************
*
* $RCSfile: doctemplates.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-07-05 10:35:50 $
*
* 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: 2001 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SFX_DOCTEMPLATES_HXX_
#define _SFX_DOCTEMPLATES_HXX_
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDOCUMENTTEMPLATES_HPP_
#include <com/sun/star/frame/XDocumentTemplates.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTORABLE_HPP_
#include <com/sun/star/frame/XStorable.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XLOCALIZABLE_HPP_
#include <com/sun/star/lang/XLocalizable.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_
#include <com/sun/star/ucb/XContent.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif
#ifndef _SFX_SFXUNO_HXX
#include <sfxuno.hxx>
#endif
//--------------------------------------------------------------------------------------------------------
#define UNOLOCALE ::com::sun::star::lang::Locale
#define REFERENCE ::com::sun::star::uno::Reference
#define RUNTIMEEXCEPTION ::com::sun::star::uno::RuntimeException
#define PROPERTYVALUE ::com::sun::star::beans::PropertyValue
#define XCONTENT ::com::sun::star::ucb::XContent
#define XDOCUMENTTEMPLATES ::com::sun::star::frame::XDocumentTemplates
#define XINTERFACE ::com::sun::star::uno::XInterface
#define XLOCALIZABLE ::com::sun::star::lang::XLocalizable
#define XMODEL ::com::sun::star::frame::XModel
#define XMULTISERVICEFACTORY ::com::sun::star::lang::XMultiServiceFactory
#define XNAMEACCESS ::com::sun::star::container::XNameAccess
#define XSERVICEINFO ::com::sun::star::lang::XServiceInfo
#define XSTORABLE ::com::sun::star::frame::XStorable
//--------------------------------------------------------------------------------------------------------
class SfxDocTplService_Impl;
class SfxDocTplService: public ::cppu::WeakImplHelper3< XLOCALIZABLE, XDOCUMENTTEMPLATES, XSERVICEINFO >
{
SfxDocTplService_Impl *pImp;
public:
SFX_DECL_XSERVICEINFO
SfxDocTplService( const REFERENCE < ::com::sun::star::lang::XMultiServiceFactory >& xFactory );
~SfxDocTplService();
// --- XLocalizable ---
void SAL_CALL setLocale( const UNOLOCALE & eLocale ) throw( RUNTIMEEXCEPTION );
UNOLOCALE SAL_CALL getLocale() throw( RUNTIMEEXCEPTION );
// --- XDocumentTemplates ---
REFERENCE< XCONTENT > SAL_CALL getContent() throw( RUNTIMEEXCEPTION );
sal_Bool SAL_CALL storeTemplate( const ::rtl::OUString& GroupName,
const ::rtl::OUString& TemplateName,
const REFERENCE< XSTORABLE >& Storable ) throw( RUNTIMEEXCEPTION );
sal_Bool SAL_CALL addTemplate( const ::rtl::OUString& GroupName,
const ::rtl::OUString& TemplateName,
const ::rtl::OUString& SourceURL ) throw( RUNTIMEEXCEPTION );
sal_Bool SAL_CALL removeTemplate( const ::rtl::OUString& GroupName,
const ::rtl::OUString& TemplateName ) throw( RUNTIMEEXCEPTION );
sal_Bool SAL_CALL renameTemplate( const ::rtl::OUString& GroupName,
const ::rtl::OUString& OldTemplateName,
const ::rtl::OUString& NewTemplateName ) throw( RUNTIMEEXCEPTION );
sal_Bool SAL_CALL addGroup( const ::rtl::OUString& GroupName ) throw( RUNTIMEEXCEPTION );
sal_Bool SAL_CALL removeGroup( const ::rtl::OUString& GroupName ) throw( RUNTIMEEXCEPTION );
sal_Bool SAL_CALL renameGroup( const ::rtl::OUString& OldGroupName,
const ::rtl::OUString& NewGroupName ) throw( RUNTIMEEXCEPTION );
void SAL_CALL update() throw( RUNTIMEEXCEPTION );
};
#endif
<|endoftext|>
|
<commit_before>/*! \file SpecularTransmission.cpp
* \author Jared Hoberock
* \brief Implementation of SpecularTransmission class.
*/
#include "SpecularTransmission.h"
#include "../geometry/Mappings.h"
SpecularTransmission
::SpecularTransmission(const Spectrum &t,
const float etai,
const float etat)
:Parent(),
mTransmittance(t),
mFresnel(etai,etat)
{
;
} // end SpecularTransmission::SpecularTransmission()
Spectrum SpecularTransmission
::sample(const Vector &wo,
const DifferentialGeometry &dg,
const float u0,
const float u1,
const float u2,
Vector &wi,
float &pdf,
bool &delta,
ComponentIndex &component) const
{
delta = true;
component = 0;
Spectrum result(0,0,0);
pdf = 0;
// figure out which eta is incident/transmitted
float cosi = wo.dot(dg.getNormal());
bool entering = cosi > 0;
float ei = mFresnel.mEtai, et = mFresnel.mEtat;
if(!entering) std::swap(ei,et);
// compute refracted ray direction
float sini2 = 1.0f - cosi*cosi;
float eta = ei / et;
float sint2 = eta * eta * sini2;
// check for total internal refraction
if(sint2 <= 1.0f)
{
float cost = -sqrtf(std::max(0.0f, 1.0f - sint2));
if(entering) cost = -cost;
wi = (eta*cosi - cost)*dg.getNormal() - eta * wo;
pdf = 1.0f;
// compute fresnel term
Spectrum f = mFresnel.evaluate(cosi, cost);
result = (et*et)/(ei*ei) * (Spectrum::white() - f) * mTransmittance;
result /= dg.getNormal().absDot(wi);
} // end if
return result;
} // end SpecularTransmission::sample()
Spectrum SpecularTransmission
::evaluate(const Vector &wo,
const DifferentialGeometry &dg,
const Vector &wi) const
{
return Spectrum::black();
} // end SpecularTransmission::evaluate()
Spectrum SpecularTransmission
::evaluate(const Vector &wo,
const DifferentialGeometry &dg,
const Vector &wi,
const bool delta,
const ComponentIndex component,
float &pdf) const
{
pdf = 0;
Spectrum result(Spectrum::black());
if(delta)
{
pdf = 1.0;
// figure out which eta is incident/transmitted
float cosi = wo.dot(dg.getNormal());
bool entering = cosi > 0;
float ei = mFresnel.mEtai, et = mFresnel.mEtat;
if(!entering) std::swap(ei,et);
// compute refracted ray direction
float sini2 = 1.0f - cosi*cosi;
float eta = ei / et;
float sint2 = eta * eta * sini2;
// assume no total internal refraction
float cost = -sqrtf(std::max(0.0f, 1.0f - sint2));
if(entering) cost = -cost;
// compute fresnel term
Spectrum f = mFresnel.evaluate(cosi, cost);
result = (et*et)/(ei*ei) * (Spectrum::white() - f) * mTransmittance;
result /= dg.getNormal().absDot(wi);
} // end if
return result;
} // end SpecularTransmission::evaluate()
<commit_msg>When we call sample(), the pdf returned should always be 1.0. Also, saturate the fresnel term so as not to introduce negative numbers.<commit_after>/*! \file SpecularTransmission.cpp
* \author Jared Hoberock
* \brief Implementation of SpecularTransmission class.
*/
#include "SpecularTransmission.h"
#include "../geometry/Mappings.h"
SpecularTransmission
::SpecularTransmission(const Spectrum &t,
const float etai,
const float etat)
:Parent(),
mTransmittance(t),
mFresnel(etai,etat)
{
;
} // end SpecularTransmission::SpecularTransmission()
Spectrum SpecularTransmission
::sample(const Vector &wo,
const DifferentialGeometry &dg,
const float u0,
const float u1,
const float u2,
Vector &wi,
float &pdf,
bool &delta,
ComponentIndex &component) const
{
delta = true;
component = 0;
Spectrum result(0,0,0);
pdf = 1.0f;
// figure out which eta is incident/transmitted
float cosi = wo.dot(dg.getNormal());
bool entering = cosi > 0;
float ei = mFresnel.mEtai, et = mFresnel.mEtat;
if(!entering) std::swap(ei,et);
// compute refracted ray direction
float sini2 = 1.0f - cosi*cosi;
float eta = ei / et;
float sint2 = eta * eta * sini2;
// check for total internal refraction
if(sint2 <= 1.0f)
{
float cost = -sqrtf(std::max(0.0f, 1.0f - sint2));
if(entering) cost = -cost;
wi = (eta*cosi - cost)*dg.getNormal() - eta * wo;
// compute fresnel term
Spectrum f = mFresnel.evaluate(cosi, cost);
f = Spectrum::white() - f;
f.saturate();
result = (et*et)/(ei*ei) * f * mTransmittance;
result /= dg.getNormal().absDot(wi);
} // end if
return result;
} // end SpecularTransmission::sample()
Spectrum SpecularTransmission
::evaluate(const Vector &wo,
const DifferentialGeometry &dg,
const Vector &wi) const
{
return Spectrum::black();
} // end SpecularTransmission::evaluate()
Spectrum SpecularTransmission
::evaluate(const Vector &wo,
const DifferentialGeometry &dg,
const Vector &wi,
const bool delta,
const ComponentIndex component,
float &pdf) const
{
pdf = 0;
Spectrum result(Spectrum::black());
if(delta)
{
pdf = 1.0;
// figure out which eta is incident/transmitted
float cosi = wo.dot(dg.getNormal());
bool entering = cosi > 0;
float ei = mFresnel.mEtai, et = mFresnel.mEtat;
if(!entering) std::swap(ei,et);
// compute refracted ray direction
float sini2 = 1.0f - cosi*cosi;
float eta = ei / et;
float sint2 = eta * eta * sini2;
// assume no total internal refraction
float cost = -sqrtf(std::max(0.0f, 1.0f - sint2));
if(entering) cost = -cost;
// compute fresnel term
Spectrum f = mFresnel.evaluate(cosi, cost);
f = Spectrum::white() - f;
f.saturate();
result = (et*et)/(ei*ei) * f * mTransmittance;
result /= dg.getNormal().absDot(wi);
} // end if
return result;
} // end SpecularTransmission::evaluate()
<|endoftext|>
|
<commit_before>#include "ast.h"
#include <iostream>
#include <sstream>
#include <map>
#include <functional>
#include <stdexcept>
#include <cassert>
#include "utils.h"
using namespace std;
extern VarStack nowStack;
TValue ast::Identifier::run() {
std::cout << "Creating identifier: " << name << std::endl;
value = nowStack.getVar(name);
return value;
}
TValue ast::IntegerType::run() {
std::cout << "Creating integer: " << val << std::endl;
return value;
}
TValue ast::RealType::run() {
std::cout << "Creating real: " << val << std::endl;
value.type = TValue::TType::Tdouble;
value.sValue.dou = val;
return value;
}
TValue ast::CharType::run() {
std::cout << "Creating char: " << val << std::endl;
return value;
}
TValue ast::StringType::run() {
std::cout << "Creating String: " << val << std::endl;
value.type = TValue::TType::Tstring;
value.sValue.str = val;
return value;
}
TValue ast::BooleanType::run() {
std::cout << "Creating boolean: " << val << std::endl;
value = TValue(val);
return value;
}
TValue ast::RangeType::run() {
std::cout << "Creating subscript range from " << this->low << " to " << this->high << std::endl;
return value;
}
TValue ast::Operator::run() {
if (op!= OpType::assign)
{
op1->run();
}
bool asgFlag = false;
switch (op)
{
case OpType::land :{
if (op1->value.toBoolean())
{
op2->run();
value = op2->value;
}
else
{
value = op1->value;
}
break;
}
case OpType::lor :{
if (!op1->value.toBoolean())
{
op2->run();
value = op2->value;
}
else
{
value = op1->value;
}
break;
}
case OpType::lnot :{
value = !op1->value;
break;
}
case OpType::bit_not :{
value = ~op1->value;
break;
}
case OpType::positive :{
value = - -op1->value;
break;
}
case OpType::negtive :{
value = -op1->value;
break;
}
case OpType::pplus :{
RealType tempE(1);
Operator tempO(op1,OpType::plus_assign,&tempE);
tempO.run();
value = tempO.value;
break;
}
case OpType::mminus :{
RealType tempE(1);
Operator tempO(op1,OpType::minus_assign,&tempE);
tempO.run();
value = tempO.value;
break;
}
case OpType::rpplus :{
value = op1->value;
RealType tempE(1);
Operator tempO(op1,OpType::plus_assign,&tempE);
tempO.run();
break;
}
case OpType::rmminus :{
value = op1->value;
RealType tempE(1);
Operator tempO(op1,OpType::minus_assign,&tempE);
tempO.run();
break;
}
case OpType::type :{
value = TValue(op1->value.getTypeString());
break;
}
case OpType::voido :{
value = TValue::undefined();
break;
}
default:
{
op2->run();
switch(op)
{
case OpType::assign :{
asgFlag = true;
value = op2->value;
break;
}
case OpType::plus_assign :{
asgFlag = true;
}
case OpType::plus :{
value = op1->value + op2->value;
break;
}
case OpType::minus_assign :{
asgFlag = true;
}
case OpType::minus :{
value = op1->value - op2->value;
break;
}
case OpType::mul_assign :{
asgFlag = true;
}
case OpType::mul :{
value = op1->value * op2->value;
break;
}
case OpType::div_assign :{
asgFlag = true;
}
case OpType::div :{
value = op1->value / op2->value;
break;
}
case OpType::mod_assign :{
asgFlag = true;
}
case OpType::mod :{
value = op1->value % op2->value;
break;
}
case OpType::bit_and_assign :{
asgFlag = true;
}
case OpType::bit_and :{
value = op1->value & op2->value;
break;
}
case OpType::bit_or_assign :{
asgFlag = true;
}
case OpType::bit_or :{
value = op1->value | op2->value;
break;
}
case OpType::bit_xor_assign :{
asgFlag = true;
}
case OpType::bit_xor :{
value = op1->value ^ op2->value;
break;
}
case OpType::eq :{
value = op1->value == op2->value;
break;
}
case OpType::ne :{
value = op1->value != op2->value;
break;
}
case OpType::lt :{
value = op1->value < op2->value;
break;
}
case OpType::gt :{
value = op1->value > op2->value;
break;
}
case OpType::le :{
value = op1->value <= op2->value;
break;
}
case OpType::ge :{
value = op1->value >= op2->value;
break;
}
case OpType::aeq :{
value = op1->value == op2->value;
if (op1->value.getType() != op2->value.getType()) {
value = TValue(false);
}
break;
}
case OpType::ane :{
value = op1->value == op2->value;
if (op1->value.getType() != op2->value.getType()) {
value = TValue(true);
}
break;
}
case OpType::lsh_assign :{
asgFlag = true;
}
case OpType::lsh :{
value = op1->value << op2->value;
break;
}
case OpType::rsh_assign :{
asgFlag = true;
}
case OpType::rsh :{
value = op1->value >> op2->value;
break;
}
case OpType::lrsh_assign :{
asgFlag = true;
}
case OpType::lrsh :{
value = op1->value.logicRShift(op2->value);
break;
}
}
}
}
if (asgFlag) {
auto id = dynamic_cast<Identifier*>(op1);
if (id == nullptr)
{
yyerror("leftside exp error");
}
else
{
nowStack.assignAndNew(id->name,value);
}
}
return value;
}
TValue ast::AssignmentStmt::run() {
return value;
}
TValue ast::ConstDecl::run() {
return value;
}
TValue ast::VarDecl::run() {
return value;
}
TValue ast::Program::run() {
return value;
}
TValue ast::Routine::run() {
return value;
}
TValue ast::FunctionDeclaration::run() {
std::cout << "declaring function: " << function_name->name << std::endl;
std::cout << "with parameters: ";
for (auto parameter : *parameter_list) {
std::cout << parameter->name << " ";
}
std::cout << std::endl;
value = TValue(this);
nowStack.assignAndNew(function_name->name, value);
return value;
}
TValue ast::CallExpression::run() {
std::cout << "calling function: " << function_name->name << std::endl;
value = nowStack.getVar(function_name->name);
FunctionDeclaration *function = value.func;
ParameterList *pl = function->parameter_list;
FunctionBody *fb = function->function_body;
if (argument_list) {
int index = 0;
if (pl->size() != argument_list->size()) {
yyerror("wrong number of arguments");
}
for (auto arg : *argument_list) {
arg->run();
}
std::cout << "with arguments: ";
for (auto arg : *argument_list) {
switch (arg->value.type) { case TValue::TType::Tstring: {
std::cout << arg->value.sValue.str << " ";
nowStack.assignAndNew(pl->at(index)->name, arg->value);
index++;
break;
}
case TValue::TType::Tdouble: {
std::cout << arg->value.sValue.dou << " ";
nowStack.assignAndNew(pl->at(index)->name, arg->value);
index++;
break;
}
}
}
std::cout << std::endl;
}
fb->run();
return value;
}
TValue ast::FuncCall::run() {
return value;
}
TValue ast::ProcCall::run() {
return value;
}
TValue ast::SysFuncCall::run() {
return value;
}
TValue ast::SysProcCall::run() {
return value;
}
TValue ast::TypeDecl::run() {
return value;
}
TValue ast::Expression::run() {
return value;
}
TValue ast::WhileStmt::run() {
return value;
}
TValue ast::ForStmt::run() {
return value;
}
TValue ast::CaseStmt::run() {
return value;
}
TValue ast::IfStmt::run() {
condition->run();
if(condition->value.toBoolean() == TValue(1).toBoolean()){
thenStmt->run();
}else{
if(elseStmt!=nullptr){
elseStmt->run();
}
}
return value;
}
TValue ast::SwitchStmt::run() {
return value;
}
// TValue ast::ArrayType::run() {
// return value;
// }
TValue ast::ArrayRef::run() {
return value;
}
TValue ast::ContinueStmt::run() {
return value;
}
TValue ast::BreakStmt::run() {
return value;
}
TValue ast::TryStmt::run() {
return value;
}
TValue ast::ThrowStmt::run() {
return value;
}
TValue ast::FinallyStmt::run() {
return value;
}
TValue ast::CatchStmt::run() {
return value;
}
TValue ast::ArrayType::run() {
for (auto expPtr : elList) {
expPtr->run();
}
std::vector<TValue> values = std::vector<TValue>(elList.size());
for (int i=0; i<elList.size(); i++) {
values[i] = elList[i]->value;
}
value.arr = values;
value.type = TValue::TType::Tarray;
std::cout << "Creating array: " << "values" << std::endl;
for (auto val : value.arr) {
std::cout << val.toString() << ", ";
}
std::cout << std::endl;
return value;
}
TValue ast::StatementList::run() {
for (auto stmt: list){
stmt->run();
}
return value;
}
TValue ast::Block::run() {
std::cout << "Enter new block!" << std::endl;
nowStack.push_new();
this->stmtList->run();
nowStack.print();
nowStack.pop();
std::cout << "Exit from block!" << std::endl;
nowStack.print();
return value;
}
<commit_msg>factor<commit_after>#include "ast.h"
#include <iostream>
#include <sstream>
#include <map>
#include <functional>
#include <stdexcept>
#include <cassert>
#include "utils.h"
using namespace std;
extern VarStack nowStack;
TValue ast::Identifier::run() {
std::cout << "Creating identifier: " << name << std::endl;
value = nowStack.getVar(name);
return value;
}
TValue ast::IntegerType::run() {
std::cout << "Creating integer: " << val << std::endl;
return value;
}
TValue ast::RealType::run() {
std::cout << "Creating real: " << val << std::endl;
value.type = TValue::TType::Tdouble;
value.sValue.dou = val;
return value;
}
TValue ast::CharType::run() {
std::cout << "Creating char: " << val << std::endl;
return value;
}
TValue ast::StringType::run() {
std::cout << "Creating String: " << val << std::endl;
value.type = TValue::TType::Tstring;
value.sValue.str = val;
return value;
}
TValue ast::BooleanType::run() {
std::cout << "Creating boolean: " << val << std::endl;
value = TValue(val);
return value;
}
TValue ast::RangeType::run() {
std::cout << "Creating subscript range from " << this->low << " to " << this->high << std::endl;
return value;
}
TValue ast::Operator::run() {
if (op!= OpType::assign)
{
op1->run();
}
bool asgFlag = false;
switch (op)
{
case OpType::land :{
if (op1->value.toBoolean())
{
op2->run();
value = op2->value;
}
else
{
value = op1->value;
}
break;
}
case OpType::lor :{
if (!op1->value.toBoolean())
{
op2->run();
value = op2->value;
}
else
{
value = op1->value;
}
break;
}
case OpType::lnot :{
value = !op1->value;
break;
}
case OpType::bit_not :{
value = ~op1->value;
break;
}
case OpType::positive :{
value = - -op1->value;
break;
}
case OpType::negtive :{
value = -op1->value;
break;
}
case OpType::pplus :{
RealType tempE(1);
Operator tempO(op1,OpType::plus_assign,&tempE);
tempO.run();
value = tempO.value;
break;
}
case OpType::mminus :{
RealType tempE(1);
Operator tempO(op1,OpType::minus_assign,&tempE);
tempO.run();
value = tempO.value;
break;
}
case OpType::rpplus :{
value = op1->value;
RealType tempE(1);
Operator tempO(op1,OpType::plus_assign,&tempE);
tempO.run();
break;
}
case OpType::rmminus :{
value = op1->value;
RealType tempE(1);
Operator tempO(op1,OpType::minus_assign,&tempE);
tempO.run();
break;
}
case OpType::type :{
value = TValue(op1->value.getTypeString());
break;
}
case OpType::voido :{
value = TValue::undefined();
break;
}
default:
{
op2->run();
switch(op)
{
case OpType::assign :{
asgFlag = true;
value = op2->value;
break;
}
case OpType::plus_assign :{
asgFlag = true;
}
case OpType::plus :{
value = op1->value + op2->value;
break;
}
case OpType::minus_assign :{
asgFlag = true;
}
case OpType::minus :{
value = op1->value - op2->value;
break;
}
case OpType::mul_assign :{
asgFlag = true;
}
case OpType::mul :{
value = op1->value * op2->value;
break;
}
case OpType::div_assign :{
asgFlag = true;
}
case OpType::div :{
value = op1->value / op2->value;
break;
}
case OpType::mod_assign :{
asgFlag = true;
}
case OpType::mod :{
value = op1->value % op2->value;
break;
}
case OpType::bit_and_assign :{
asgFlag = true;
}
case OpType::bit_and :{
value = op1->value & op2->value;
break;
}
case OpType::bit_or_assign :{
asgFlag = true;
}
case OpType::bit_or :{
value = op1->value | op2->value;
break;
}
case OpType::bit_xor_assign :{
asgFlag = true;
}
case OpType::bit_xor :{
value = op1->value ^ op2->value;
break;
}
case OpType::eq :{
value = op1->value == op2->value;
break;
}
case OpType::ne :{
value = op1->value != op2->value;
break;
}
case OpType::lt :{
value = op1->value < op2->value;
break;
}
case OpType::gt :{
value = op1->value > op2->value;
break;
}
case OpType::le :{
value = op1->value <= op2->value;
break;
}
case OpType::ge :{
value = op1->value >= op2->value;
break;
}
case OpType::aeq :{
value = op1->value == op2->value;
if (op1->value.getType() != op2->value.getType()) {
value = TValue(false);
}
break;
}
case OpType::ane :{
value = op1->value == op2->value;
if (op1->value.getType() != op2->value.getType()) {
value = TValue(true);
}
break;
}
case OpType::lsh_assign :{
asgFlag = true;
}
case OpType::lsh :{
value = op1->value << op2->value;
break;
}
case OpType::rsh_assign :{
asgFlag = true;
}
case OpType::rsh :{
value = op1->value >> op2->value;
break;
}
case OpType::lrsh_assign :{
asgFlag = true;
}
case OpType::lrsh :{
value = op1->value.logicRShift(op2->value);
break;
}
}
}
}
if (asgFlag) {
auto id = dynamic_cast<Identifier*>(op1);
if (id == nullptr)
{
yyerror("leftside exp error");
}
else
{
nowStack.assignAndNew(id->name,value);
}
}
return value;
}
TValue ast::AssignmentStmt::run() {
return value;
}
TValue ast::ConstDecl::run() {
return value;
}
TValue ast::VarDecl::run() {
return value;
}
TValue ast::Program::run() {
return value;
}
TValue ast::Routine::run() {
return value;
}
TValue ast::FunctionDeclaration::run() {
std::cout << "declaring function: " << function_name->name << std::endl;
std::cout << "with parameters: ";
for (auto parameter : *parameter_list) {
std::cout << parameter->name << " ";
}
std::cout << std::endl;
value = TValue(this);
nowStack.assignAndNew(function_name->name, value);
return value;
}
TValue ast::CallExpression::run() {
std::cout << "calling function: " << function_name->name << std::endl;
value = nowStack.getVar(function_name->name);
FunctionDeclaration *function = value.func;
ParameterList *pl = function->parameter_list;
FunctionBody *fb = function->function_body;
if (argument_list) {
int index = 0;
if (pl->size() != argument_list->size()) {
yyerror("wrong number of arguments");
}
for (auto arg : *argument_list) {
arg->run();
}
std::cout << "with arguments: ";
for (auto arg : *argument_list) {
switch (arg->value.type) {
case TValue::TType::Tstring: {
std::cout << arg->value.sValue.str << " ";
break;
}
case TValue::TType::Tdouble: {
std::cout << arg->value.sValue.dou << " ";
break;
}
}
nowStack.assignAndNew(pl->at(index)->name, arg->value);
index++;
}
std::cout << std::endl;
}
fb->run();
return value;
}
TValue ast::FuncCall::run() {
return value;
}
TValue ast::ProcCall::run() {
return value;
}
TValue ast::SysFuncCall::run() {
return value;
}
TValue ast::SysProcCall::run() {
return value;
}
TValue ast::TypeDecl::run() {
return value;
}
TValue ast::Expression::run() {
return value;
}
TValue ast::WhileStmt::run() {
return value;
}
TValue ast::ForStmt::run() {
return value;
}
TValue ast::CaseStmt::run() {
return value;
}
TValue ast::IfStmt::run() {
condition->run();
if(condition->value.toBoolean() == TValue(1).toBoolean()){
thenStmt->run();
}else{
if(elseStmt!=nullptr){
elseStmt->run();
}
}
return value;
}
TValue ast::SwitchStmt::run() {
return value;
}
// TValue ast::ArrayType::run() {
// return value;
// }
TValue ast::ArrayRef::run() {
return value;
}
TValue ast::ContinueStmt::run() {
return value;
}
TValue ast::BreakStmt::run() {
return value;
}
TValue ast::TryStmt::run() {
return value;
}
TValue ast::ThrowStmt::run() {
return value;
}
TValue ast::FinallyStmt::run() {
return value;
}
TValue ast::CatchStmt::run() {
return value;
}
TValue ast::ArrayType::run() {
for (auto expPtr : elList) {
expPtr->run();
}
std::vector<TValue> values = std::vector<TValue>(elList.size());
for (int i=0; i<elList.size(); i++) {
values[i] = elList[i]->value;
}
value.arr = values;
value.type = TValue::TType::Tarray;
std::cout << "Creating array: " << "values" << std::endl;
for (auto val : value.arr) {
std::cout << val.toString() << ", ";
}
std::cout << std::endl;
return value;
}
TValue ast::StatementList::run() {
for (auto stmt: list){
stmt->run();
}
return value;
}
TValue ast::Block::run() {
std::cout << "Enter new block!" << std::endl;
nowStack.push_new();
this->stmtList->run();
nowStack.print();
nowStack.pop();
std::cout << "Exit from block!" << std::endl;
nowStack.print();
return value;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: viewstrategy.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2003-04-24 14:01: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): _______________________________________
*
*
************************************************************************/
#ifndef CONFIGMGR_VIEWBEHAVIOR_HXX_
#define CONFIGMGR_VIEWBEHAVIOR_HXX_
#ifndef CONFIGMGR_VIEWNODE_HXX_
#include "viewnode.hxx"
#endif
#ifndef CONFIGMGR_GROUPNODEBEHAVIOR_HXX_
#include "groupnodeimpl.hxx"
#endif
#ifndef CONFIGMGR_SETNODEBEHAVIOR_HXX_
#include "setnodeimpl.hxx"
#endif
#ifndef _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_
#include <salhelper/simplereferenceobject.hxx>
#endif
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
namespace configmgr
{
//-----------------------------------------------------------------------------
namespace memory { class Segment; }
//-----------------------------------------------------------------------------
namespace configuration
{
class SetElementChangeImpl;
class ValueChangeImpl;
}
//-----------------------------------------------------------------------------
namespace view
{
//-----------------------------------------------------------------------------
struct NodeFactory;
//-----------------------------------------------------------------------------
using configuration::Name;
using configuration::NodeOffset;
using configuration::TreeDepth;
typedef com::sun::star::uno::Any UnoAny;
typedef com::sun::star::uno::Type UnoType;
//-----------------------------------------------------------------------------
class ViewStrategy : public salhelper::SimpleReferenceObject
{
// node attributes
public:
/// retrieve the attributes of the node
Name getName(Node const& _aNode) const;
/// retrieve the attributes of the node
node::Attributes getAttributes(Node const& _aNode) const;
// tracking pending changes
public:
typedef configuration::NodeChanges NodeChanges;
void collectChanges(Tree const& _aTree, NodeChanges& rChanges) const;
bool hasChanges(Tree const& _aTree) const;
bool hasChanges(Node const& _aNode) const;
void markChanged(Node const& _aNode);
// commit protocol
public:
std::auto_ptr<SubtreeChange> preCommitChanges(Tree const& _aTree, configuration::ElementList& _rRemovedElements);
void finishCommit(Tree const& _aTree, SubtreeChange& rRootChange);
void revertCommit(Tree const& _aTree, SubtreeChange& rRootChange);
void recoverFailedCommit(Tree const& _aTree, SubtreeChange& rRootChange);
// notification protocol
public:
typedef configuration::NodeChangesInformation NodeChangesInformation;
/// Adjust the internal representation after external changes to the original data - build NodeChangeInformation objects for notification
void adjustToChanges(NodeChangesInformation& rLocalChanges, Node const & _aNode, SubtreeChange const& aExternalChange);
// visitor dispatch
public:
typedef configuration::GroupMemberVisitor GroupMemberVisitor;
typedef configuration::SetNodeVisitor SetNodeVisitor;
GroupMemberVisitor::Result dispatchToValues(GroupNode const& _aNode, GroupMemberVisitor& _aVisitor);
/// Call <code>aVisitor.visit(aElement)</code> for each element in this set until SetNodeVisitor::DONE is returned.
SetNodeVisitor::Result dispatchToElements(SetNode const& _aNode, SetNodeVisitor& _aVisitor);
// value (element) node specific operations
public:
/// Does this node assume its default value
/// retrieve the current value of this node
UnoAny getValue(ValueNode const& _aNode) const;
/// get the type of this value
UnoType getValueType(ValueNode const& _aNode) const;
// group node specific operations
public:
typedef configuration::ValueMemberNode ValueMemberNode;
typedef configuration::ValueMemberUpdate ValueMemberUpdate;
/// does this hold a child value of the given name
bool hasValue(GroupNode const& _aNode, Name const& _aName) const;
/// does this hold a child value
bool hasValue(GroupNode const& _aNode) const;
/// are defaults for this node available ?
bool areValueDefaultsAvailable(GroupNode const& _aNode) const;
/// retrieve data for the child value of the given name
ValueMemberNode getValue(GroupNode const& _aNode, Name const& _aName) const;
/// retrieve data for updating the child value of the given name
ValueMemberUpdate getValueForUpdate(GroupNode const & _aNode, Name const& _aName);
// set node specific operations
public:
typedef configuration::ElementTreeData SetNodeElement;
typedef configuration::SetEntry SetNodeEntry;
/// does this set contain any elements (loads elements if needed)
bool isEmpty(SetNode const& _aNode) const;
/// does this set contain an element named <var>aName</var> (loads elements if needed)
SetNodeEntry findElement(SetNode const& _aNode, Name const& aName) const;
/// does this set contain an element named <var>aName</var> (and is that element loaded ?)
SetNodeEntry findAvailableElement(SetNode const& _aNode, Name const& aName) const;
/// insert a new entry into this set
void insertElement(SetNode const& _aNode, Name const& aName, SetNodeEntry const& aNewEntry);
/// remove an existing entry into this set
void removeElement(SetNode const& _aNode, Name const& aName);
/** Create a Subtree change as 'diff' which allows transforming the set to its default state
(given that <var>_rDefaultTree</var> points to a default instance of this set)
<p>Ownership of added trees should be transferred to the SubtreeChange.</p>
*/
std::auto_ptr<SubtreeChange> differenceToDefaultState(SetNode const& _aNode, ISubtree& _rDefaultTree) const;
/// Get the template that describes elements of this set
configuration::TemplateHolder getElementTemplate(SetNode const& _aNode) const;
/// Get a template provider that can create new elements for this set
configuration::TemplateProvider getTemplateProvider(SetNode const& _aNode) const;
// create a view::Tree from a configuration::SetEntry
Tree extractTree(SetNodeEntry const& _anEntry);
// creating/changing state/strategy
public:
NodeFactory& getNodeFactory();
// direct update access to data
public:
void releaseDataSegment();
memory::Segment const * getDataSegment() const;
memory::Segment * getDataSegmentForUpdate();
data::NodeAddress ::DataType * getDataForUpdate(data::NodeAccessRef const & _aNode);
data::SetNodeAddress::DataType * getDataForUpdate(data::SetNodeAccess const & _aNode);
data::GroupNodeAddress::DataType * getDataForUpdate(data::GroupNodeAccess const & _aNode);
data::ValueNodeAddress::DataType * getDataForUpdate(data::ValueNodeAccess const & _aNode);
// access to node innards
protected:
/// provide access to the data of the underlying node
data::NodeAccessRef getNodeAccessRef(Node const& _aNode) const;
/// provide access to the address of the underlying node
data::NodeAddress getNodeAddress(Node const& _aNode) const;
/// retrieve the name of the underlying node
Name getNodeName(Node const& _aNode) const;
/// retrieve the attributes of the underlying node
node::Attributes getNodeAttributes(Node const& _aNode) const;
protected:
//helper for migration to new (info based) model for adjusting to changes
static void addLocalChangeHelper( NodeChangesInformation& rLocalChanges, configuration::NodeChange const& aChange);
private:
void implAdjustToValueChanges(NodeChangesInformation& rLocalChanges, GroupNode const& _aGroupNode, SubtreeChange const& rExternalChanges);
void implAdjustToSubChanges(NodeChangesInformation& rLocalChanges, GroupNode const & _aGroupNode, SubtreeChange const& rExternalChanges);
void implAdjustToElementChanges(NodeChangesInformation& rLocalChanges, SetNode const& _aNode, SubtreeChange const& rExternalChanges, TreeDepth nDepth);
void implAdjustToElementChange (NodeChangesInformation& rLocalChanges, SetNode const& _aNode, Change const& rElementChange, TreeDepth nElementDepth);
void implCommitDirectIn(data::TreeAccessor const& _aPlaceHolder, Node const& _aNode);
protected:
void checkInstance(Tree const& _aTreeForThis) const;
SetNodeEntry implFindElement(SetNode const& _aNode, Name const& aName) const;
SetNodeElement implMakeElement(SetNode const& _aNode, SetNodeEntry const& anEntry) const;
// virtual interface - these functions must be provided
private:
// change handling
virtual bool doHasChanges(Node const& _aNode) const = 0;
virtual void doMarkChanged(Node const& _aNode) = 0;
virtual NodeFactory& doGetNodeFactory() = 0;
// virtual interface - these functions all have default implementations without support for pending changes
protected:
virtual void doReleaseDataSegment() = 0;
// special support for direct changes to underlying data - default is no support
virtual data::NodeAddress::DataType * implAccessForUpdate(data::NodeAccessRef const & _aDataAccess);
virtual memory::Segment const * doGetDataSegment() const = 0;
virtual memory::Segment * doGetDataSegmentForUpdate();
// change handling
virtual void doCollectChanges(Node const& _aNode, NodeChanges& rChanges) const;
// commit protocol
virtual std::auto_ptr<SubtreeChange> doPreCommitChanges(Tree const& _aTree, configuration::ElementList& _rRemovedElements);
virtual void doFailedCommit(Tree const& _aTree, SubtreeChange& rChanges);
virtual void doFinishCommit(Tree const& _aTree, SubtreeChange& rChanges);
virtual void doRevertCommit(Tree const& _aTree, SubtreeChange& rChanges);
// notification protocol
virtual configuration::ValueChangeImpl* doAdjustToValueChange(GroupNode const& _aGroupNode, Name const& aName, ValueChange const& rExternalChange);
// common attributes
virtual node::Attributes doAdjustAttributes(node::Attributes const& _aAttributes) const = 0;
// group member access
virtual ValueMemberNode doGetValueMember(GroupNode const& _aNode, Name const& _aName, bool _bForUpdate) const = 0;
// set element access
virtual void doInsertElement(SetNode const& _aNode, Name const& aName, SetNodeEntry const& aNewEntry) = 0;
virtual void doRemoveElement(SetNode const& _aNode, Name const& aName) = 0;
// strategy change support
/* virtual void doCommitChanges(Node const& _aNode);
virtual rtl::Reference<ViewStrategy> doCloneDirect() = 0;
virtual rtl::Reference<ViewStrategy> doCloneIndirect() = 0;
*/ };
//-----------------------------------------------------------------------------
inline Name ViewStrategy::getName(Node const& _aNode) const
{ return getNodeName(_aNode); }
inline node::Attributes ViewStrategy::getAttributes(Node const& _aNode) const
{ return doAdjustAttributes(getNodeAttributes(_aNode)); }
inline bool ViewStrategy::hasChanges(Node const& _aNode) const
{ return doHasChanges(_aNode); }
inline NodeFactory& ViewStrategy::getNodeFactory()
{ return doGetNodeFactory(); }
inline void ViewStrategy::releaseDataSegment()
{ doReleaseDataSegment(); }
inline memory::Segment const * ViewStrategy::getDataSegment() const
{ return doGetDataSegment(); }
inline memory::Segment * ViewStrategy::getDataSegmentForUpdate()
{ return doGetDataSegmentForUpdate(); }
//-----------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
}
#endif // CONFIGMGR_CONFIGNODEBEHAVIOR_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.180); FILE MERGED 2005/09/05 17:05:36 rt 1.5.180.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: viewstrategy.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 04:37:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CONFIGMGR_VIEWBEHAVIOR_HXX_
#define CONFIGMGR_VIEWBEHAVIOR_HXX_
#ifndef CONFIGMGR_VIEWNODE_HXX_
#include "viewnode.hxx"
#endif
#ifndef CONFIGMGR_GROUPNODEBEHAVIOR_HXX_
#include "groupnodeimpl.hxx"
#endif
#ifndef CONFIGMGR_SETNODEBEHAVIOR_HXX_
#include "setnodeimpl.hxx"
#endif
#ifndef _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_
#include <salhelper/simplereferenceobject.hxx>
#endif
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
namespace configmgr
{
//-----------------------------------------------------------------------------
namespace memory { class Segment; }
//-----------------------------------------------------------------------------
namespace configuration
{
class SetElementChangeImpl;
class ValueChangeImpl;
}
//-----------------------------------------------------------------------------
namespace view
{
//-----------------------------------------------------------------------------
struct NodeFactory;
//-----------------------------------------------------------------------------
using configuration::Name;
using configuration::NodeOffset;
using configuration::TreeDepth;
typedef com::sun::star::uno::Any UnoAny;
typedef com::sun::star::uno::Type UnoType;
//-----------------------------------------------------------------------------
class ViewStrategy : public salhelper::SimpleReferenceObject
{
// node attributes
public:
/// retrieve the attributes of the node
Name getName(Node const& _aNode) const;
/// retrieve the attributes of the node
node::Attributes getAttributes(Node const& _aNode) const;
// tracking pending changes
public:
typedef configuration::NodeChanges NodeChanges;
void collectChanges(Tree const& _aTree, NodeChanges& rChanges) const;
bool hasChanges(Tree const& _aTree) const;
bool hasChanges(Node const& _aNode) const;
void markChanged(Node const& _aNode);
// commit protocol
public:
std::auto_ptr<SubtreeChange> preCommitChanges(Tree const& _aTree, configuration::ElementList& _rRemovedElements);
void finishCommit(Tree const& _aTree, SubtreeChange& rRootChange);
void revertCommit(Tree const& _aTree, SubtreeChange& rRootChange);
void recoverFailedCommit(Tree const& _aTree, SubtreeChange& rRootChange);
// notification protocol
public:
typedef configuration::NodeChangesInformation NodeChangesInformation;
/// Adjust the internal representation after external changes to the original data - build NodeChangeInformation objects for notification
void adjustToChanges(NodeChangesInformation& rLocalChanges, Node const & _aNode, SubtreeChange const& aExternalChange);
// visitor dispatch
public:
typedef configuration::GroupMemberVisitor GroupMemberVisitor;
typedef configuration::SetNodeVisitor SetNodeVisitor;
GroupMemberVisitor::Result dispatchToValues(GroupNode const& _aNode, GroupMemberVisitor& _aVisitor);
/// Call <code>aVisitor.visit(aElement)</code> for each element in this set until SetNodeVisitor::DONE is returned.
SetNodeVisitor::Result dispatchToElements(SetNode const& _aNode, SetNodeVisitor& _aVisitor);
// value (element) node specific operations
public:
/// Does this node assume its default value
/// retrieve the current value of this node
UnoAny getValue(ValueNode const& _aNode) const;
/// get the type of this value
UnoType getValueType(ValueNode const& _aNode) const;
// group node specific operations
public:
typedef configuration::ValueMemberNode ValueMemberNode;
typedef configuration::ValueMemberUpdate ValueMemberUpdate;
/// does this hold a child value of the given name
bool hasValue(GroupNode const& _aNode, Name const& _aName) const;
/// does this hold a child value
bool hasValue(GroupNode const& _aNode) const;
/// are defaults for this node available ?
bool areValueDefaultsAvailable(GroupNode const& _aNode) const;
/// retrieve data for the child value of the given name
ValueMemberNode getValue(GroupNode const& _aNode, Name const& _aName) const;
/// retrieve data for updating the child value of the given name
ValueMemberUpdate getValueForUpdate(GroupNode const & _aNode, Name const& _aName);
// set node specific operations
public:
typedef configuration::ElementTreeData SetNodeElement;
typedef configuration::SetEntry SetNodeEntry;
/// does this set contain any elements (loads elements if needed)
bool isEmpty(SetNode const& _aNode) const;
/// does this set contain an element named <var>aName</var> (loads elements if needed)
SetNodeEntry findElement(SetNode const& _aNode, Name const& aName) const;
/// does this set contain an element named <var>aName</var> (and is that element loaded ?)
SetNodeEntry findAvailableElement(SetNode const& _aNode, Name const& aName) const;
/// insert a new entry into this set
void insertElement(SetNode const& _aNode, Name const& aName, SetNodeEntry const& aNewEntry);
/// remove an existing entry into this set
void removeElement(SetNode const& _aNode, Name const& aName);
/** Create a Subtree change as 'diff' which allows transforming the set to its default state
(given that <var>_rDefaultTree</var> points to a default instance of this set)
<p>Ownership of added trees should be transferred to the SubtreeChange.</p>
*/
std::auto_ptr<SubtreeChange> differenceToDefaultState(SetNode const& _aNode, ISubtree& _rDefaultTree) const;
/// Get the template that describes elements of this set
configuration::TemplateHolder getElementTemplate(SetNode const& _aNode) const;
/// Get a template provider that can create new elements for this set
configuration::TemplateProvider getTemplateProvider(SetNode const& _aNode) const;
// create a view::Tree from a configuration::SetEntry
Tree extractTree(SetNodeEntry const& _anEntry);
// creating/changing state/strategy
public:
NodeFactory& getNodeFactory();
// direct update access to data
public:
void releaseDataSegment();
memory::Segment const * getDataSegment() const;
memory::Segment * getDataSegmentForUpdate();
data::NodeAddress ::DataType * getDataForUpdate(data::NodeAccessRef const & _aNode);
data::SetNodeAddress::DataType * getDataForUpdate(data::SetNodeAccess const & _aNode);
data::GroupNodeAddress::DataType * getDataForUpdate(data::GroupNodeAccess const & _aNode);
data::ValueNodeAddress::DataType * getDataForUpdate(data::ValueNodeAccess const & _aNode);
// access to node innards
protected:
/// provide access to the data of the underlying node
data::NodeAccessRef getNodeAccessRef(Node const& _aNode) const;
/// provide access to the address of the underlying node
data::NodeAddress getNodeAddress(Node const& _aNode) const;
/// retrieve the name of the underlying node
Name getNodeName(Node const& _aNode) const;
/// retrieve the attributes of the underlying node
node::Attributes getNodeAttributes(Node const& _aNode) const;
protected:
//helper for migration to new (info based) model for adjusting to changes
static void addLocalChangeHelper( NodeChangesInformation& rLocalChanges, configuration::NodeChange const& aChange);
private:
void implAdjustToValueChanges(NodeChangesInformation& rLocalChanges, GroupNode const& _aGroupNode, SubtreeChange const& rExternalChanges);
void implAdjustToSubChanges(NodeChangesInformation& rLocalChanges, GroupNode const & _aGroupNode, SubtreeChange const& rExternalChanges);
void implAdjustToElementChanges(NodeChangesInformation& rLocalChanges, SetNode const& _aNode, SubtreeChange const& rExternalChanges, TreeDepth nDepth);
void implAdjustToElementChange (NodeChangesInformation& rLocalChanges, SetNode const& _aNode, Change const& rElementChange, TreeDepth nElementDepth);
void implCommitDirectIn(data::TreeAccessor const& _aPlaceHolder, Node const& _aNode);
protected:
void checkInstance(Tree const& _aTreeForThis) const;
SetNodeEntry implFindElement(SetNode const& _aNode, Name const& aName) const;
SetNodeElement implMakeElement(SetNode const& _aNode, SetNodeEntry const& anEntry) const;
// virtual interface - these functions must be provided
private:
// change handling
virtual bool doHasChanges(Node const& _aNode) const = 0;
virtual void doMarkChanged(Node const& _aNode) = 0;
virtual NodeFactory& doGetNodeFactory() = 0;
// virtual interface - these functions all have default implementations without support for pending changes
protected:
virtual void doReleaseDataSegment() = 0;
// special support for direct changes to underlying data - default is no support
virtual data::NodeAddress::DataType * implAccessForUpdate(data::NodeAccessRef const & _aDataAccess);
virtual memory::Segment const * doGetDataSegment() const = 0;
virtual memory::Segment * doGetDataSegmentForUpdate();
// change handling
virtual void doCollectChanges(Node const& _aNode, NodeChanges& rChanges) const;
// commit protocol
virtual std::auto_ptr<SubtreeChange> doPreCommitChanges(Tree const& _aTree, configuration::ElementList& _rRemovedElements);
virtual void doFailedCommit(Tree const& _aTree, SubtreeChange& rChanges);
virtual void doFinishCommit(Tree const& _aTree, SubtreeChange& rChanges);
virtual void doRevertCommit(Tree const& _aTree, SubtreeChange& rChanges);
// notification protocol
virtual configuration::ValueChangeImpl* doAdjustToValueChange(GroupNode const& _aGroupNode, Name const& aName, ValueChange const& rExternalChange);
// common attributes
virtual node::Attributes doAdjustAttributes(node::Attributes const& _aAttributes) const = 0;
// group member access
virtual ValueMemberNode doGetValueMember(GroupNode const& _aNode, Name const& _aName, bool _bForUpdate) const = 0;
// set element access
virtual void doInsertElement(SetNode const& _aNode, Name const& aName, SetNodeEntry const& aNewEntry) = 0;
virtual void doRemoveElement(SetNode const& _aNode, Name const& aName) = 0;
// strategy change support
/* virtual void doCommitChanges(Node const& _aNode);
virtual rtl::Reference<ViewStrategy> doCloneDirect() = 0;
virtual rtl::Reference<ViewStrategy> doCloneIndirect() = 0;
*/ };
//-----------------------------------------------------------------------------
inline Name ViewStrategy::getName(Node const& _aNode) const
{ return getNodeName(_aNode); }
inline node::Attributes ViewStrategy::getAttributes(Node const& _aNode) const
{ return doAdjustAttributes(getNodeAttributes(_aNode)); }
inline bool ViewStrategy::hasChanges(Node const& _aNode) const
{ return doHasChanges(_aNode); }
inline NodeFactory& ViewStrategy::getNodeFactory()
{ return doGetNodeFactory(); }
inline void ViewStrategy::releaseDataSegment()
{ doReleaseDataSegment(); }
inline memory::Segment const * ViewStrategy::getDataSegment() const
{ return doGetDataSegment(); }
inline memory::Segment * ViewStrategy::getDataSegmentForUpdate()
{ return doGetDataSegmentForUpdate(); }
//-----------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
}
#endif // CONFIGMGR_CONFIGNODEBEHAVIOR_HXX_
<|endoftext|>
|
<commit_before>// OpenQASM example, executes an OpenQASM circuit read from the input stream
// (repeatedly if the number of repetitions is passed as an argument)
// Source: ./examples/qasm/qasm.cpp
#include <iostream>
#include "qpp.h"
int main(int argc, char** argv) {
using namespace qpp;
QCircuit qc;
// read the circuit from the input stream
qc = qasm::read(std::cin);
idx reps = 1;
if (argc > 1)
reps = std::stoi(argv[1]);
// initialize the quantum engine with a circuit
QEngine q_engine{qc};
// display the quantum circuit and its corresponding resources
std::cout << qc << "\n\n" << qc.get_resources() << "\n\n";
// execute the quantum circuit
q_engine.execute(reps);
// display the measurement statistics
std::cout << q_engine << '\n';
// uncomment the following lines if you want to display the final state
/*
ket psi_final = q_engine.get_psi();
std::cout << ">> Final state (transpose):\n"
<< disp(transpose(psi_final)) << '\n';
*/
}
<commit_msg>Update qasm.cpp<commit_after>// OpenQASM example, executes an OpenQASM circuit read from the input stream
// (repeatedly if the number of repetitions is passed as an argument)
// Source: ./examples/qasm/qasm.cpp
#include <iostream>
#include "qpp.h"
int main(int argc, char** argv) {
using namespace qpp;
// read the circuit from the input stream
QCircuit qc = qasm::read(std::cin);
// initialize the quantum engine with a circuit
QEngine q_engine{qc};
// display the quantum circuit and its corresponding resources
std::cout << qc << "\n\n" << qc.get_resources() << "\n\n";
// execute the quantum circuit
idx reps = argc > 1 ? std::stoi(argv[1]) : 1; // repetitions
q_engine.execute(reps);
// display the measurement statistics
std::cout << q_engine << '\n';
// display the final state on demand
if (argc > 2) {
std::cout << ">> Final state (transpose):\n";
std::cout << disp(transpose(q_engine.get_psi())) << '\n';
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: pres.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: ka $ $Date: 2001-04-04 16:35:12 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _PRESENTATION_HXX
#define _PRESENTATION_HXX
enum AutoLayout
{
AUTOLAYOUT_TITLE,
AUTOLAYOUT_ENUM,
AUTOLAYOUT_CHART,
AUTOLAYOUT_2TEXT,
AUTOLAYOUT_TEXTCHART,
AUTOLAYOUT_ORG,
AUTOLAYOUT_TEXTCLIP,
AUTOLAYOUT_CHARTTEXT,
AUTOLAYOUT_TAB,
AUTOLAYOUT_CLIPTEXT,
AUTOLAYOUT_TEXTOBJ,
AUTOLAYOUT_OBJ,
AUTOLAYOUT_TEXT2OBJ,
AUTOLAYOUT_OBJTEXT,
AUTOLAYOUT_OBJOVERTEXT,
AUTOLAYOUT_2OBJTEXT,
AUTOLAYOUT_2OBJOVERTEXT,
AUTOLAYOUT_TEXTOVEROBJ,
AUTOLAYOUT_4OBJ,
AUTOLAYOUT_ONLY_TITLE,
AUTOLAYOUT_NONE,
AUTOLAYOUT_NOTES,
AUTOLAYOUT_HANDOUT1,
AUTOLAYOUT_HANDOUT2,
AUTOLAYOUT_HANDOUT3,
AUTOLAYOUT_HANDOUT4,
AUTOLAYOUT_HANDOUT6,
AUTOLAYOUT_VERTICAL_TITLE_TEXT_CHART,
AUTOLAYOUT_VERTICAL_TITLE_VERTICAL_OUTLINE,
AUTOLAYOUT_TITLE_VERTICAL_OUTLINE,
AUTOLAYOUT_TITLE_VERTICAL_OUTLINE_CLIPART
};
enum PageKind
{
PK_STANDARD,
PK_NOTES,
PK_HANDOUT
};
enum EditMode
{
EM_PAGE,
EM_MASTERPAGE
};
enum DocumentType
{
DOCUMENT_TYPE_IMPRESS,
DOCUMENT_TYPE_DRAW
};
enum NavigatorDragType
{
NAVIGATOR_DRAGTYPE_NONE,
NAVIGATOR_DRAGTYPE_URL,
NAVIGATOR_DRAGTYPE_LINK,
NAVIGATOR_DRAGTYPE_EMBEDDED
};
#define NAVIGATOR_DRAGTYPE_COUNT 4
#endif // _PRESENTATION_HXX
<commit_msg>INTEGRATION: CWS impress36 (1.3.736); FILE MERGED 2005/03/02 12:37:33 af 1.3.736.1: #i42583# Added two meta enum entries to AutoLayout for safer iteration.<commit_after>/*************************************************************************
*
* $RCSfile: pres.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2005-03-18 16:44:34 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _PRESENTATION_HXX
#define _PRESENTATION_HXX
enum AutoLayout
{
AUTOLAYOUT__START,
AUTOLAYOUT_TITLE = AUTOLAYOUT__START,
AUTOLAYOUT_ENUM,
AUTOLAYOUT_CHART,
AUTOLAYOUT_2TEXT,
AUTOLAYOUT_TEXTCHART,
AUTOLAYOUT_ORG,
AUTOLAYOUT_TEXTCLIP,
AUTOLAYOUT_CHARTTEXT,
AUTOLAYOUT_TAB,
AUTOLAYOUT_CLIPTEXT,
AUTOLAYOUT_TEXTOBJ,
AUTOLAYOUT_OBJ,
AUTOLAYOUT_TEXT2OBJ,
AUTOLAYOUT_OBJTEXT,
AUTOLAYOUT_OBJOVERTEXT,
AUTOLAYOUT_2OBJTEXT,
AUTOLAYOUT_2OBJOVERTEXT,
AUTOLAYOUT_TEXTOVEROBJ,
AUTOLAYOUT_4OBJ,
AUTOLAYOUT_ONLY_TITLE,
AUTOLAYOUT_NONE,
AUTOLAYOUT_NOTES,
AUTOLAYOUT_HANDOUT1,
AUTOLAYOUT_HANDOUT2,
AUTOLAYOUT_HANDOUT3,
AUTOLAYOUT_HANDOUT4,
AUTOLAYOUT_HANDOUT6,
AUTOLAYOUT_VERTICAL_TITLE_TEXT_CHART,
AUTOLAYOUT_VERTICAL_TITLE_VERTICAL_OUTLINE,
AUTOLAYOUT_TITLE_VERTICAL_OUTLINE,
AUTOLAYOUT_TITLE_VERTICAL_OUTLINE_CLIPART,
AUTOLAYOUT__END,
};
enum PageKind
{
PK_STANDARD,
PK_NOTES,
PK_HANDOUT
};
enum EditMode
{
EM_PAGE,
EM_MASTERPAGE
};
enum DocumentType
{
DOCUMENT_TYPE_IMPRESS,
DOCUMENT_TYPE_DRAW
};
enum NavigatorDragType
{
NAVIGATOR_DRAGTYPE_NONE,
NAVIGATOR_DRAGTYPE_URL,
NAVIGATOR_DRAGTYPE_LINK,
NAVIGATOR_DRAGTYPE_EMBEDDED
};
#define NAVIGATOR_DRAGTYPE_COUNT 4
#endif // _PRESENTATION_HXX
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <cstdio>
#include "../IO/FileAccessException.h"
#include "Throw.h"
#include "TimeOutException.h"
#include "ErrNoException.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Characters;
using namespace Execution;
using Debug::TraceContextBumper;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
/*
********************************************************************************
***************************** errno_ErrorException *****************************
********************************************************************************
*/
errno_ErrorException::errno_ErrorException (Execution::errno_t e)
: Execution::Exception<> (SDKString2Wide (LookupMessage (e)))
, fError (e)
{
}
SDKString errno_ErrorException::LookupMessage (Execution::errno_t e)
{
SDKString justErrnoNumberMessage;
{
SDKChar justNumBuf[2048];
justNumBuf[0] = '\0';
#if qPlatform_Windows
(void)::_stprintf_s (justNumBuf, SDKSTR ("errno: %d"), e);
#else
(void)snprintf (justNumBuf, NEltsOf (justNumBuf), SDKSTR ("errno: %d"), e);
#endif
justErrnoNumberMessage = justNumBuf;
}
SDKChar buf[2048];
buf[0] = '\0';
#if qPlatform_Windows
if (::_tcserror_s (buf, e) == 0) {
return buf + SDKString (SDKSTR (" (") + justErrnoNumberMessage + SDKSTR (")"));
}
#elif qPlatform_Linux
/*
* A bit quirky - GNU-specific and POSIX handle this API fairly differently.
* https://linux.die.net/man/3/strerror_r - in one case returns int and 0 means worked,
* and other case always returns string to use (not in buf)
*/
#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE
// The XSI-compliant strerror_r() function returns 0 on success
if (::strerror_r (e, buf, NEltsOf (buf)) == 0) {
return buf + SDKString (SDKSTR (" (") + justErrnoNumberMessage + SDKSTR (")"));
}
#else
// the GNU-specific strerror_r() functions return the appropriate error description string
// NOTE - this version MAY or MAY NOT modify buf - it sometimes returns static strings!
return ::strerror_r (e, buf, NEltsOf (buf)) + SDKString (SDKSTR (" (") + justErrnoNumberMessage + SDKSTR (")"));
#endif
#elif qPlatform_POSIX
// The XSI-compliant strerror_r() function returns 0 on success
if (::strerror_r (e, buf, NEltsOf (buf)) == 0) {
return buf + SDKString (SDKSTR (" (") + justErrnoNumberMessage + SDKSTR (")"));
}
#else
AssertNotImplemented ();
#endif
return justErrnoNumberMessage;
}
[[noreturn]] void errno_ErrorException::Throw (Execution::errno_t error)
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx{L"errno_ErrorException::Throw", L"error = %d", error};
#endif
#if 1
if (constexpr qPlatform_POSIX) {
// on a POSIX system, treat this as a system error code because it could be an extension code
SystemException::ThrowSystemErrNo (error);
}
else {
// on a NON-POSIX system, nothing we can do but use 'generic' error category
SystemException::ThrowPOSIXErrNo (error);
}
#else
//REVIEW EXCPETIONS ANMD MPAPING - THIS IS NOT GOOD - NOT EVEN CLOSE!!! -- LGP 2011-09-29
switch (error) {
case ENOMEM: {
Execution::Throw (bad_alloc (), "errno_ErrorException::Throw (ENOMEM) - throwing bad_alloc");
}
case ENOENT: {
Execution::Throw (IO::FileAccessException ()); // don't know if they were reading or writing at this level..., and don't know file name...
}
case EACCES: {
Execution::Throw (IO::FileAccessException ()); // don't know if they were reading or writing at this level..., and don't know file name...
}
case ETIMEDOUT: {
Execution::Throw (Execution::TimeOutException::kThe);
}
// If I decide to pursue mapping, this maybe a good place to start
// http://aplawrence.com/Unixart/errors.html
// -- LGP 2009-01-02
#if 0
case EPERM: {
// not sure any point in this unification. Maybe if I added my OWN private 'access denied' exception
// the mapping/unification would make sense.
// -- LGP 2009-01-02
DbgTrace ("errno_ErrorException::Throw (EPERM) - throwing ERROR_ACCESS_DENIED");
throw Win32Exception (ERROR_ACCESS_DENIED);
}
#endif
}
#if qStroika_Foundation_Exection_Throw_TraceThrowpoint
#if qStroika_Foundation_Exection_Throw_TraceThrowpointBacktrace
DbgTrace (L"errno_ErrorException::Throw (%d) - throwing errno_ErrorException '%s' from %s", error, SDKString2Wide (LookupMessage (error)).c_str (), Private_::GetBT_ws ().c_str ());
#else
DbgTrace (L"errno_ErrorException::Throw (%d) - throwing errno_ErrorException '%s'", error, SDKString2Wide (LookupMessage (error)).c_str ());
#endif
#endif
throw errno_ErrorException (error);
#endif
}
<commit_msg>fixed typo<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <cstdio>
#include "../IO/FileAccessException.h"
#include "Throw.h"
#include "TimeOutException.h"
#include "ErrNoException.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Characters;
using namespace Execution;
using Debug::TraceContextBumper;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
/*
********************************************************************************
***************************** errno_ErrorException *****************************
********************************************************************************
*/
errno_ErrorException::errno_ErrorException (Execution::errno_t e)
: Execution::Exception<> (SDKString2Wide (LookupMessage (e)))
, fError (e)
{
}
SDKString errno_ErrorException::LookupMessage (Execution::errno_t e)
{
SDKString justErrnoNumberMessage;
{
SDKChar justNumBuf[2048];
justNumBuf[0] = '\0';
#if qPlatform_Windows
(void)::_stprintf_s (justNumBuf, SDKSTR ("errno: %d"), e);
#else
(void)snprintf (justNumBuf, NEltsOf (justNumBuf), SDKSTR ("errno: %d"), e);
#endif
justErrnoNumberMessage = justNumBuf;
}
SDKChar buf[2048];
buf[0] = '\0';
#if qPlatform_Windows
if (::_tcserror_s (buf, e) == 0) {
return buf + SDKString (SDKSTR (" (") + justErrnoNumberMessage + SDKSTR (")"));
}
#elif qPlatform_Linux
/*
* A bit quirky - GNU-specific and POSIX handle this API fairly differently.
* https://linux.die.net/man/3/strerror_r - in one case returns int and 0 means worked,
* and other case always returns string to use (not in buf)
*/
#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE
// The XSI-compliant strerror_r() function returns 0 on success
if (::strerror_r (e, buf, NEltsOf (buf)) == 0) {
return buf + SDKString (SDKSTR (" (") + justErrnoNumberMessage + SDKSTR (")"));
}
#else
// the GNU-specific strerror_r() functions return the appropriate error description string
// NOTE - this version MAY or MAY NOT modify buf - it sometimes returns static strings!
return ::strerror_r (e, buf, NEltsOf (buf)) + SDKString (SDKSTR (" (") + justErrnoNumberMessage + SDKSTR (")"));
#endif
#elif qPlatform_POSIX
// The XSI-compliant strerror_r() function returns 0 on success
if (::strerror_r (e, buf, NEltsOf (buf)) == 0) {
return buf + SDKString (SDKSTR (" (") + justErrnoNumberMessage + SDKSTR (")"));
}
#else
AssertNotImplemented ();
#endif
return justErrnoNumberMessage;
}
[[noreturn]] void errno_ErrorException::Throw (Execution::errno_t error)
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx{L"errno_ErrorException::Throw", L"error = %d", error};
#endif
#if 1
#if qPlatform_POSIX
// on a POSIX system, treat this as a system error code because it could be an extension code
SystemException::ThrowSystemErrNo (error);
#else
// on a NON-POSIX system, nothing we can do but use 'generic' error category
SystemException::ThrowPOSIXErrNo (error);
#endif
#else
//REVIEW EXCPETIONS ANMD MPAPING - THIS IS NOT GOOD - NOT EVEN CLOSE!!! -- LGP 2011-09-29
switch (error) {
case ENOMEM: {
Execution::Throw (bad_alloc (), "errno_ErrorException::Throw (ENOMEM) - throwing bad_alloc");
}
case ENOENT: {
Execution::Throw (IO::FileAccessException ()); // don't know if they were reading or writing at this level..., and don't know file name...
}
case EACCES: {
Execution::Throw (IO::FileAccessException ()); // don't know if they were reading or writing at this level..., and don't know file name...
}
case ETIMEDOUT: {
Execution::Throw (Execution::TimeOutException::kThe);
}
// If I decide to pursue mapping, this maybe a good place to start
// http://aplawrence.com/Unixart/errors.html
// -- LGP 2009-01-02
#if 0
case EPERM: {
// not sure any point in this unification. Maybe if I added my OWN private 'access denied' exception
// the mapping/unification would make sense.
// -- LGP 2009-01-02
DbgTrace ("errno_ErrorException::Throw (EPERM) - throwing ERROR_ACCESS_DENIED");
throw Win32Exception (ERROR_ACCESS_DENIED);
}
#endif
}
#if qStroika_Foundation_Exection_Throw_TraceThrowpoint
#if qStroika_Foundation_Exection_Throw_TraceThrowpointBacktrace
DbgTrace (L"errno_ErrorException::Throw (%d) - throwing errno_ErrorException '%s' from %s", error, SDKString2Wide (LookupMessage (error)).c_str (), Private_::GetBT_ws ().c_str ());
#else
DbgTrace (L"errno_ErrorException::Throw (%d) - throwing errno_ErrorException '%s'", error, SDKString2Wide (LookupMessage (error)).c_str ());
#endif
#endif
throw errno_ErrorException (error);
#endif
}
<|endoftext|>
|
<commit_before>/*
kopeteaccountmanager.cpp - Kopete Account Manager
Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org>
Copyright (c) 2003-2004 by Olivier Goffart <ogoffart@kde.org>
Kopete (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* 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 "kopeteaccountmanager.h"
#include <QtGui/QApplication>
#include <QtCore/QRegExp>
#include <QtCore/QTimer>
#include <QtCore/QHash>
#include <kconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kplugininfo.h>
#include <kconfiggroup.h>
#include "kopeteaccount.h"
#include "kopeteaway.h"
#include "kopeteprotocol.h"
#include "kopetecontact.h"
#include "kopetecontactlist.h"
#include "kopetepluginmanager.h"
#include "kopeteonlinestatus.h"
#include "kopeteonlinestatusmanager.h"
#include "kopetemetacontact.h"
#include "kopetegroup.h"
namespace Kopete {
static int compareAccountsByPriority( Account *a, Account *b )
{
uint priority1 = a->priority();
uint priority2 = b->priority();
if( a==b ) //two account are equal only if they are equal :-)
return 0; // remember than an account can be only once on the list, but two account may have the same priority when loading
else if( priority1 > priority2 )
return 1;
else
return -1;
}
class AccountManager::Private
{
public:
QList<Account *> accounts;
};
AccountManager * AccountManager::s_self = 0L;
AccountManager * AccountManager::self()
{
if ( !s_self )
s_self = new AccountManager;
return s_self;
}
AccountManager::AccountManager()
: QObject( qApp )
{
setObjectName( "KopeteAccountManager" );
d = new Private;
}
AccountManager::~AccountManager()
{
s_self = 0L;
delete d;
}
bool AccountManager::isAnyAccountConnected()
{
foreach( Account *a , d->accounts )
{
if( a->isConnected() )
return true;
}
return false;
}
void AccountManager::connectAll()
{
setOnlineStatus( OnlineStatusManager::Online );
}
void AccountManager::setAvailableAll( const QString &awayReason )
{
setOnlineStatus( OnlineStatusManager::Online , awayReason );
}
void AccountManager::disconnectAll()
{
setOnlineStatus( OnlineStatusManager::Offline );
}
void AccountManager::setAwayAll( const QString &awayReason, bool away )
{
setOnlineStatus( away ? OnlineStatusManager::Away : OnlineStatusManager::Online , awayReason );
}
void AccountManager::setOnlineStatus( uint category , const QString& awayMessage, uint flags )
{
OnlineStatusManager::Categories katgor=(OnlineStatusManager::Categories)category;
bool anyConnected = isAnyAccountConnected();
foreach( Account *account , d->accounts )
{
Kopete::OnlineStatus status = OnlineStatusManager::self()->onlineStatus(account->protocol() , katgor);
if ( anyConnected )
{
if ( account->isConnected() || ( (flags & ConnectIfOffline) && !account->excludeConnect() ) )
account->setOnlineStatus( status , awayMessage );
}
else
{
if ( !account->excludeConnect() )
account->setOnlineStatus( status , awayMessage );
}
}
}
QColor AccountManager::guessColor( Protocol *protocol ) const
{
// In a perfect wold, we should check if the color is actually not used by the account.
// Anyway, this is not really required, It would be a difficult job for about nothing more.
// -- Olivier
int protocolCount = 0;
for ( QListIterator<Account *> it( d->accounts ); it.hasNext(); )
{
Account *a = it.next();
if ( a->protocol()->pluginId() == protocol->pluginId() )
protocolCount++;
}
// let's figure a color
QColor color;
switch ( protocolCount % 7 )
{
case 0:
color = QColor();
break;
case 1:
color = Qt::red;
break;
case 2:
color = Qt::green;
break;
case 3:
color = Qt::blue;
break;
case 4:
color = Qt::yellow;
break;
case 5:
color = Qt::magenta;
break;
case 6:
color = Qt::cyan;
break;
}
return color;
}
Account* AccountManager::registerAccount( Account *account )
{
if( !account || d->accounts.contains( account ) )
return account;
if( account->accountId().isEmpty() )
{
account->deleteLater();
return 0L;
}
// If this account already exists, do nothing
QListIterator<Account *> it( d->accounts );
while ( it.hasNext() )
{
Account *curracc = it.next();
if ( ( account->protocol() == curracc->protocol() ) && ( account->accountId() == curracc->accountId() ) )
{
account->deleteLater();
return 0L;
}
}
d->accounts.append( account );
qSort( d->accounts.begin(), d->accounts.end(), compareAccountsByPriority );
// Connect to the account's status changed signal
connect(account->myself(), SIGNAL(onlineStatusChanged(Kopete::Contact *,
const Kopete::OnlineStatus &, const Kopete::OnlineStatus &)),
this, SLOT(slotAccountOnlineStatusChanged(Kopete::Contact *,
const Kopete::OnlineStatus &, const Kopete::OnlineStatus &)));
connect(account, SIGNAL(accountDestroyed(const Kopete::Account *)) , this, SLOT( unregisterAccount(const Kopete::Account *) ));
emit accountRegistered( account );
return account;
}
void AccountManager::unregisterAccount( const Account *account )
{
kDebug( 14010 ) << k_funcinfo << "Unregistering account " << account->accountId() << endl;
d->accounts.removeAll( const_cast<Account*>(account) );
emit accountUnregistered( account );
}
const QList<Account *>& AccountManager::accounts() const
{
return d->accounts;
}
QList<Account*> AccountManager::accounts( Protocol* protocol ) const
{
QList<Account*> protocolAccounts;
foreach( Account* acct, d->accounts )
{
if ( acct->protocol() == protocol )
protocolAccounts.append( acct );
}
return protocolAccounts;
}
Account * AccountManager::findAccount( const QString &protocolId, const QString &accountId )
{
for ( QListIterator<Account *> it( d->accounts ); it.hasNext(); )
{
Account *a = it.next();
if ( a->protocol()->pluginId() == protocolId && a->accountId() == accountId )
return a;
}
return 0L;
}
void AccountManager::removeAccount( Account *account )
{
if(!account->removeAccount())
return;
Protocol *protocol = account->protocol();
KConfigGroup *configgroup = account->configGroup();
// Clean up the contact list
const QHash<QString, Kopete::Contact*> contactList = account->contacts();
QHash<QString, Kopete::Contact*>::ConstIterator it, itEnd = contactList.constEnd();
for ( it = contactList.constBegin(); it != itEnd; ++it )
{
Contact* c = it.value();
MetaContact* mc = c->metaContact();
if ( mc == ContactList::self()->myself() )
continue;
mc->removeContact( c );
c->deleteLater();
if ( mc->contacts().count() == 0 ) //we can delete the metacontact
{
//get the first group and it's members
Group* group = mc->groups().first();
MetaContact::List groupMembers = group->members();
ContactList::self()->removeMetaContact( mc );
if ( groupMembers.count() == 1 && groupMembers.indexOf( mc ) != -1 )
ContactList::self()->removeGroup( group );
}
}
// Clean up the account list
d->accounts.removeAll( account );
// Clean up configuration
configgroup->deleteGroup();
configgroup->sync();
delete account;
foreach( Account *account , d->accounts )
{
if( account->protocol() == protocol )
return;
}
//there is nomore account from the protocol, we can unload it
// FIXME: pluginId() should return the internal name and not the class name, so
// we can get rid of this hack - Olivier/Martijn
QString protocolName = protocol->pluginId().remove( QString::fromLatin1( "Protocol" ) ).toLower();
PluginManager::self()->setPluginEnabled( protocolName, false );
PluginManager::self()->unloadPlugin( protocolName );
}
void AccountManager::save()
{
//kDebug( 14010 ) << k_funcinfo << endl;
qSort( d->accounts.begin(), d->accounts.end(), compareAccountsByPriority );
for ( QListIterator<Account *> it( d->accounts ); it.hasNext(); )
{
Account *a = it.next();
KConfigBase *config = a->configGroup();
config->writeEntry( "Protocol", a->protocol()->pluginId() );
config->writeEntry( "AccountId", a->accountId() );
}
KGlobal::config()->sync();
}
void AccountManager::load()
{
connect( PluginManager::self(), SIGNAL( pluginLoaded( Kopete::Plugin * ) ),
this, SLOT( slotPluginLoaded( Kopete::Plugin * ) ) );
// Iterate over all groups that start with "Account_" as those are accounts
// and load the required protocols if the account is enabled.
// Don't try to optimize duplicate calls out, the plugin queue is smart enough
// (and fast enough) to handle that without adding complexity here
KSharedConfig::Ptr config = KGlobal::config();
QStringList accountGroups = config->groupList().filter( QRegExp( QString::fromLatin1( "^Account_" ) ) );
for ( QStringList::Iterator it = accountGroups.begin(); it != accountGroups.end(); ++it )
{
config->setGroup( *it );
QString protocol = config->readEntry( "Protocol", QString() );
if ( protocol.endsWith( QString::fromLatin1( "Protocol" ) ) )
protocol = QString::fromLatin1( "kopete_" ) + protocol.toLower().remove( QString::fromLatin1( "protocol" ) );
if ( config->readEntry( "Enabled", true ) )
PluginManager::self()->loadPlugin( protocol, PluginManager::LoadAsync );
}
}
void AccountManager::slotPluginLoaded( Plugin *plugin )
{
Protocol* protocol = dynamic_cast<Protocol*>( plugin );
if ( !protocol )
return;
// Iterate over all groups that start with "Account_" as those are accounts
// and parse them if they are from this protocol
KSharedConfig::Ptr config = KGlobal::config();
QStringList accountGroups = config->groupList().filter( QRegExp( QString::fromLatin1( "^Account_" ) ) );
for ( QStringList::Iterator it = accountGroups.begin(); it != accountGroups.end(); ++it )
{
config->setGroup( *it );
if ( config->readEntry( "Protocol" ) != protocol->pluginId() )
continue;
// There's no GUI for this, but developers may want to disable an account.
if ( !config->readEntry( "Enabled", true ) )
continue;
QString accountId = config->readEntry( "AccountId", QString() );
if ( accountId.isEmpty() )
{
kWarning( 14010 ) << k_funcinfo <<
"Not creating account for empty accountId." << endl;
continue;
}
kDebug( 14010 ) << k_funcinfo <<
"Creating account for '" << accountId << "'" << endl;
Account *account = 0L;
account = registerAccount( protocol->createNewAccount( accountId ) );
if ( !account )
{
kWarning( 14010 ) << k_funcinfo <<
"Failed to create account for '" << accountId << "'" << endl;
continue;
}
}
}
void AccountManager::slotAccountOnlineStatusChanged(Contact *c,
const OnlineStatus &oldStatus, const OnlineStatus &newStatus)
{
Account *account = c->account();
if (!account)
return;
//kDebug(14010) << k_funcinfo << endl;
emit accountOnlineStatusChanged(account, oldStatus, newStatus);
}
} //END namespace Kopete
#include "kopeteaccountmanager.moc"
// vim: set noet ts=4 sts=4 sw=4:
// kate: tab-width 4; indent-mode csands;
<commit_msg>more porting<commit_after>/*
kopeteaccountmanager.cpp - Kopete Account Manager
Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org>
Copyright (c) 2003-2004 by Olivier Goffart <ogoffart@kde.org>
Kopete (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* 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 "kopeteaccountmanager.h"
#include <QtGui/QApplication>
#include <QtCore/QRegExp>
#include <QtCore/QTimer>
#include <QtCore/QHash>
#include <kconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kplugininfo.h>
#include <kconfiggroup.h>
#include "kopeteaccount.h"
#include "kopeteaway.h"
#include "kopeteprotocol.h"
#include "kopetecontact.h"
#include "kopetecontactlist.h"
#include "kopetepluginmanager.h"
#include "kopeteonlinestatus.h"
#include "kopeteonlinestatusmanager.h"
#include "kopetemetacontact.h"
#include "kopetegroup.h"
namespace Kopete {
static int compareAccountsByPriority( Account *a, Account *b )
{
uint priority1 = a->priority();
uint priority2 = b->priority();
if( a==b ) //two account are equal only if they are equal :-)
return 0; // remember than an account can be only once on the list, but two account may have the same priority when loading
else if( priority1 > priority2 )
return 1;
else
return -1;
}
class AccountManager::Private
{
public:
QList<Account *> accounts;
};
AccountManager * AccountManager::s_self = 0L;
AccountManager * AccountManager::self()
{
if ( !s_self )
s_self = new AccountManager;
return s_self;
}
AccountManager::AccountManager()
: QObject( qApp )
{
setObjectName( "KopeteAccountManager" );
d = new Private;
}
AccountManager::~AccountManager()
{
s_self = 0L;
delete d;
}
bool AccountManager::isAnyAccountConnected()
{
foreach( Account *a , d->accounts )
{
if( a->isConnected() )
return true;
}
return false;
}
void AccountManager::connectAll()
{
setOnlineStatus( OnlineStatusManager::Online );
}
void AccountManager::setAvailableAll( const QString &awayReason )
{
setOnlineStatus( OnlineStatusManager::Online , awayReason );
}
void AccountManager::disconnectAll()
{
setOnlineStatus( OnlineStatusManager::Offline );
}
void AccountManager::setAwayAll( const QString &awayReason, bool away )
{
setOnlineStatus( away ? OnlineStatusManager::Away : OnlineStatusManager::Online , awayReason );
}
void AccountManager::setOnlineStatus( uint category , const QString& awayMessage, uint flags )
{
OnlineStatusManager::Categories katgor=(OnlineStatusManager::Categories)category;
bool anyConnected = isAnyAccountConnected();
foreach( Account *account , d->accounts )
{
Kopete::OnlineStatus status = OnlineStatusManager::self()->onlineStatus(account->protocol() , katgor);
if ( anyConnected )
{
if ( account->isConnected() || ( (flags & ConnectIfOffline) && !account->excludeConnect() ) )
account->setOnlineStatus( status , awayMessage );
}
else
{
if ( !account->excludeConnect() )
account->setOnlineStatus( status , awayMessage );
}
}
}
QColor AccountManager::guessColor( Protocol *protocol ) const
{
// In a perfect wold, we should check if the color is actually not used by the account.
// Anyway, this is not really required, It would be a difficult job for about nothing more.
// -- Olivier
int protocolCount = 0;
for ( QListIterator<Account *> it( d->accounts ); it.hasNext(); )
{
Account *a = it.next();
if ( a->protocol()->pluginId() == protocol->pluginId() )
protocolCount++;
}
// let's figure a color
QColor color;
switch ( protocolCount % 7 )
{
case 0:
color = QColor();
break;
case 1:
color = Qt::red;
break;
case 2:
color = Qt::green;
break;
case 3:
color = Qt::blue;
break;
case 4:
color = Qt::yellow;
break;
case 5:
color = Qt::magenta;
break;
case 6:
color = Qt::cyan;
break;
}
return color;
}
Account* AccountManager::registerAccount( Account *account )
{
if( !account || d->accounts.contains( account ) )
return account;
if( account->accountId().isEmpty() )
{
account->deleteLater();
return 0L;
}
// If this account already exists, do nothing
QListIterator<Account *> it( d->accounts );
while ( it.hasNext() )
{
Account *curracc = it.next();
if ( ( account->protocol() == curracc->protocol() ) && ( account->accountId() == curracc->accountId() ) )
{
account->deleteLater();
return 0L;
}
}
d->accounts.append( account );
qSort( d->accounts.begin(), d->accounts.end(), compareAccountsByPriority );
// Connect to the account's status changed signal
connect(account->myself(), SIGNAL(onlineStatusChanged(Kopete::Contact *,
const Kopete::OnlineStatus &, const Kopete::OnlineStatus &)),
this, SLOT(slotAccountOnlineStatusChanged(Kopete::Contact *,
const Kopete::OnlineStatus &, const Kopete::OnlineStatus &)));
connect(account, SIGNAL(accountDestroyed(const Kopete::Account *)) , this, SLOT( unregisterAccount(const Kopete::Account *) ));
emit accountRegistered( account );
return account;
}
void AccountManager::unregisterAccount( const Account *account )
{
kDebug( 14010 ) << k_funcinfo << "Unregistering account " << account->accountId() << endl;
d->accounts.removeAll( const_cast<Account*>(account) );
emit accountUnregistered( account );
}
const QList<Account *>& AccountManager::accounts() const
{
return d->accounts;
}
QList<Account*> AccountManager::accounts( Protocol* protocol ) const
{
QList<Account*> protocolAccounts;
foreach( Account* acct, d->accounts )
{
if ( acct->protocol() == protocol )
protocolAccounts.append( acct );
}
return protocolAccounts;
}
Account * AccountManager::findAccount( const QString &protocolId, const QString &accountId )
{
for ( QListIterator<Account *> it( d->accounts ); it.hasNext(); )
{
Account *a = it.next();
if ( a->protocol()->pluginId() == protocolId && a->accountId() == accountId )
return a;
}
return 0L;
}
void AccountManager::removeAccount( Account *account )
{
if(!account->removeAccount())
return;
Protocol *protocol = account->protocol();
KConfigGroup *configgroup = account->configGroup();
// Clean up the contact list
const QHash<QString, Kopete::Contact*> contactList = account->contacts();
QHash<QString, Kopete::Contact*>::ConstIterator it, itEnd = contactList.constEnd();
for ( it = contactList.constBegin(); it != itEnd; ++it )
{
Contact* c = it.value();
MetaContact* mc = c->metaContact();
if ( mc == ContactList::self()->myself() )
continue;
mc->removeContact( c );
c->deleteLater();
if ( mc->contacts().count() == 0 ) //we can delete the metacontact
{
//get the first group and it's members
Group* group = mc->groups().first();
MetaContact::List groupMembers = group->members();
ContactList::self()->removeMetaContact( mc );
if ( groupMembers.count() == 1 && groupMembers.indexOf( mc ) != -1 )
ContactList::self()->removeGroup( group );
}
}
// Clean up the account list
d->accounts.removeAll( account );
// Clean up configuration
configgroup->deleteGroup();
configgroup->sync();
delete account;
foreach( Account *account , d->accounts )
{
if( account->protocol() == protocol )
return;
}
//there is nomore account from the protocol, we can unload it
// FIXME: pluginId() should return the internal name and not the class name, so
// we can get rid of this hack - Olivier/Martijn
QString protocolName = protocol->pluginId().remove( QString::fromLatin1( "Protocol" ) ).toLower();
PluginManager::self()->setPluginEnabled( protocolName, false );
PluginManager::self()->unloadPlugin( protocolName );
}
void AccountManager::save()
{
//kDebug( 14010 ) << k_funcinfo << endl;
qSort( d->accounts.begin(), d->accounts.end(), compareAccountsByPriority );
for ( QListIterator<Account *> it( d->accounts ); it.hasNext(); )
{
Account *a = it.next();
KConfigGroup config = a->configGroup();
config.writeEntry( "Protocol", a->protocol()->pluginId() );
config.writeEntry( "AccountId", a->accountId() );
}
KGlobal::config()->sync();
}
void AccountManager::load()
{
connect( PluginManager::self(), SIGNAL( pluginLoaded( Kopete::Plugin * ) ),
this, SLOT( slotPluginLoaded( Kopete::Plugin * ) ) );
// Iterate over all groups that start with "Account_" as those are accounts
// and load the required protocols if the account is enabled.
// Don't try to optimize duplicate calls out, the plugin queue is smart enough
// (and fast enough) to handle that without adding complexity here
KSharedConfig::Ptr config = KGlobal::config();
QStringList accountGroups = config->groupList().filter( QRegExp( QString::fromLatin1( "^Account_" ) ) );
for ( QStringList::Iterator it = accountGroups.begin(); it != accountGroups.end(); ++it )
{
config->setGroup( *it );
QString protocol = config->readEntry( "Protocol", QString() );
if ( protocol.endsWith( QString::fromLatin1( "Protocol" ) ) )
protocol = QString::fromLatin1( "kopete_" ) + protocol.toLower().remove( QString::fromLatin1( "protocol" ) );
if ( config->readEntry( "Enabled", true ) )
PluginManager::self()->loadPlugin( protocol, PluginManager::LoadAsync );
}
}
void AccountManager::slotPluginLoaded( Plugin *plugin )
{
Protocol* protocol = dynamic_cast<Protocol*>( plugin );
if ( !protocol )
return;
// Iterate over all groups that start with "Account_" as those are accounts
// and parse them if they are from this protocol
KSharedConfig::Ptr config = KGlobal::config();
QStringList accountGroups = config->groupList().filter( QRegExp( QString::fromLatin1( "^Account_" ) ) );
for ( QStringList::Iterator it = accountGroups.begin(); it != accountGroups.end(); ++it )
{
config->setGroup( *it );
if ( config->readEntry( "Protocol" ) != protocol->pluginId() )
continue;
// There's no GUI for this, but developers may want to disable an account.
if ( !config->readEntry( "Enabled", true ) )
continue;
QString accountId = config->readEntry( "AccountId", QString() );
if ( accountId.isEmpty() )
{
kWarning( 14010 ) << k_funcinfo <<
"Not creating account for empty accountId." << endl;
continue;
}
kDebug( 14010 ) << k_funcinfo <<
"Creating account for '" << accountId << "'" << endl;
Account *account = 0L;
account = registerAccount( protocol->createNewAccount( accountId ) );
if ( !account )
{
kWarning( 14010 ) << k_funcinfo <<
"Failed to create account for '" << accountId << "'" << endl;
continue;
}
}
}
void AccountManager::slotAccountOnlineStatusChanged(Contact *c,
const OnlineStatus &oldStatus, const OnlineStatus &newStatus)
{
Account *account = c->account();
if (!account)
return;
//kDebug(14010) << k_funcinfo << endl;
emit accountOnlineStatusChanged(account, oldStatus, newStatus);
}
} //END namespace Kopete
#include "kopeteaccountmanager.moc"
// vim: set noet ts=4 sts=4 sw=4:
// kate: tab-width 4; indent-mode csands;
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Controller_widget.cpp : Controller Widget for the controllers
****************************************************************************
* Copyright (C) 2006-2008 the VideoLAN team
* $Id$
*
* Authors: Jean-Baptiste Kempf <jb@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* ( at your option ) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "controller_widget.hpp"
#include "input_manager.hpp" /* Get notification of Volume Change */
#include "util/input_slider.hpp" /* SoundSlider */
#include <vlc_aout.h> /* Volume functions */
#include <QLabel>
#include <QHBoxLayout>
#include <QSpinBox>
SoundWidget::SoundWidget( QWidget *_parent, intf_thread_t * _p_intf,
bool b_shiny )
: QWidget( _parent ), b_my_volume( false )
{
p_intf = _p_intf;
QHBoxLayout *layout = new QHBoxLayout( this );
layout->setSpacing( 0 ); layout->setMargin( 0 );
hVolLabel = new VolumeClickHandler( p_intf, this );
volMuteLabel = new QLabel;
volMuteLabel->setPixmap( QPixmap( ":/volume-medium" ) );
volMuteLabel->installEventFilter( hVolLabel );
layout->addWidget( volMuteLabel );
if( b_shiny )
{
volumeSlider = new SoundSlider( this,
config_GetInt( p_intf, "volume-step" ),
config_GetInt( p_intf, "qt-volume-complete" ),
config_GetPsz( p_intf, "qt-slider-colours" ) );
}
else
{
volumeSlider = new QSlider( this );
volumeSlider->setOrientation( Qt::Horizontal );
}
volumeSlider->setMaximumSize( QSize( 200, 40 ) );
volumeSlider->setMinimumSize( QSize( 85, 30 ) );
volumeSlider->setFocusPolicy( Qt::NoFocus );
layout->addWidget( volumeSlider );
/* Set the volume from the config */
volumeSlider->setValue( ( config_GetInt( p_intf, "volume" ) ) *
VOLUME_MAX / (AOUT_VOLUME_MAX/2) );
/* Force the update at build time in order to have a muted icon if needed */
updateVolume( volumeSlider->value() );
/* Volume control connection */
CONNECT( volumeSlider, valueChanged( int ), this, updateVolume( int ) );
CONNECT( THEMIM, volumeChanged( void ), this, updateVolume( void ) );
}
void SoundWidget::updateVolume( int i_sliderVolume )
{
if( !b_my_volume )
{
int i_res = i_sliderVolume * (AOUT_VOLUME_MAX / 2) / VOLUME_MAX;
aout_VolumeSet( p_intf, i_res );
}
if( i_sliderVolume == 0 )
{
volMuteLabel->setPixmap( QPixmap(":/volume-muted" ) );
volMuteLabel->setToolTip( qtr( "Unmute" ) );
return;
}
if( i_sliderVolume < VOLUME_MAX / 3 )
volMuteLabel->setPixmap( QPixmap( ":/volume-low" ) );
else if( i_sliderVolume > (VOLUME_MAX * 2 / 3 ) )
volMuteLabel->setPixmap( QPixmap( ":/volume-high" ) );
else volMuteLabel->setPixmap( QPixmap( ":/volume-medium" ) );
volMuteLabel->setToolTip( qtr( "Mute" ) );
}
void SoundWidget::updateVolume()
{
/* Audio part */
audio_volume_t i_volume;
aout_VolumeGet( p_intf, &i_volume );
i_volume = ( i_volume * VOLUME_MAX )/ (AOUT_VOLUME_MAX/2);
int i_gauge = volumeSlider->value();
b_my_volume = false;
if( i_volume - i_gauge > 1 || i_gauge - i_volume > 1 )
{
b_my_volume = true;
volumeSlider->setValue( i_volume );
b_my_volume = false;
}
}
void TeletextController::toggleTeletextTransparency( bool b_transparent )
{
telexTransparent->setIcon( b_transparent ? QIcon( ":/tvtelx" )
: QIcon( ":/tvtelx-trans" ) );
}
void TeletextController::enableTeletextButtons( bool b_enabled )
{
telexOn->setChecked( b_enabled );
telexTransparent->setEnabled( b_enabled );
telexPage->setEnabled( b_enabled );
}
void PlayButton::updateButton( bool b_playing )
{
setIcon( b_playing ? QIcon( ":/pause_b" ) : QIcon( ":/play_b" ) );
setToolTip( b_playing ? qtr( "Pause the playback" )
: qtr( I_PLAY_TOOLTIP ) );
}
void AtoB_Button::setIcons( bool timeA, bool timeB )
{
if( !timeA && !timeB)
{
setIcon( QIcon( ":/atob_nob" ) );
setToolTip( qtr( "Loop from point A to point B continuously\n"
"Click to set point A" ) );
}
else if( timeA && !timeB )
{
setIcon( QIcon( ":/atob_noa" ) );
setToolTip( qtr( "Click to set point B" ) );
}
else if( timeA && timeB )
{
setIcon( QIcon( ":/atob" ) );
setToolTip( qtr( "Stop the A to B loop" ) );
}
}
bool VolumeClickHandler::eventFilter( QObject *obj, QEvent *e )
{
VLC_UNUSED( obj );
if (e->type() == QEvent::MouseButtonPress )
{
aout_VolumeMute( p_intf, NULL );
audio_volume_t i_volume;
aout_VolumeGet( p_intf, &i_volume );
// m->updateVolume( i_volume * VOLUME_MAX / (AOUT_VOLUME_MAX/2) );
e->accept();
return true;
}
else
{
e->ignore();
return false;
}
}
<commit_msg>Qt: let the native sound slider manage 200% and 400% of volume.<commit_after>/*****************************************************************************
* Controller_widget.cpp : Controller Widget for the controllers
****************************************************************************
* Copyright (C) 2006-2008 the VideoLAN team
* $Id$
*
* Authors: Jean-Baptiste Kempf <jb@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* ( at your option ) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "controller_widget.hpp"
#include "input_manager.hpp" /* Get notification of Volume Change */
#include "util/input_slider.hpp" /* SoundSlider */
#include <vlc_aout.h> /* Volume functions */
#include <QLabel>
#include <QHBoxLayout>
#include <QSpinBox>
SoundWidget::SoundWidget( QWidget *_parent, intf_thread_t * _p_intf,
bool b_shiny )
: QWidget( _parent ), b_my_volume( false )
{
p_intf = _p_intf;
QHBoxLayout *layout = new QHBoxLayout( this );
layout->setSpacing( 0 ); layout->setMargin( 0 );
hVolLabel = new VolumeClickHandler( p_intf, this );
volMuteLabel = new QLabel;
volMuteLabel->setPixmap( QPixmap( ":/volume-medium" ) );
volMuteLabel->installEventFilter( hVolLabel );
layout->addWidget( volMuteLabel );
if( b_shiny )
{
volumeSlider = new SoundSlider( this,
config_GetInt( p_intf, "volume-step" ),
config_GetInt( p_intf, "qt-volume-complete" ),
config_GetPsz( p_intf, "qt-slider-colours" ) );
}
else
{
volumeSlider = new QSlider( this );
volumeSlider->setOrientation( Qt::Horizontal );
volumeSlider->setMaximum( config_GetInt( p_intf, "qt-volume-complete" )
? 400 : 200 );
}
volumeSlider->setMaximumSize( QSize( 200, 40 ) );
volumeSlider->setMinimumSize( QSize( 85, 30 ) );
volumeSlider->setFocusPolicy( Qt::NoFocus );
layout->addWidget( volumeSlider );
/* Set the volume from the config */
volumeSlider->setValue( ( config_GetInt( p_intf, "volume" ) ) *
VOLUME_MAX / (AOUT_VOLUME_MAX/2) );
/* Force the update at build time in order to have a muted icon if needed */
updateVolume( volumeSlider->value() );
/* Volume control connection */
CONNECT( volumeSlider, valueChanged( int ), this, updateVolume( int ) );
CONNECT( THEMIM, volumeChanged( void ), this, updateVolume( void ) );
}
void SoundWidget::updateVolume( int i_sliderVolume )
{
if( !b_my_volume )
{
int i_res = i_sliderVolume * (AOUT_VOLUME_MAX / 2) / VOLUME_MAX;
aout_VolumeSet( p_intf, i_res );
}
if( i_sliderVolume == 0 )
{
volMuteLabel->setPixmap( QPixmap(":/volume-muted" ) );
volMuteLabel->setToolTip( qtr( "Unmute" ) );
return;
}
if( i_sliderVolume < VOLUME_MAX / 3 )
volMuteLabel->setPixmap( QPixmap( ":/volume-low" ) );
else if( i_sliderVolume > (VOLUME_MAX * 2 / 3 ) )
volMuteLabel->setPixmap( QPixmap( ":/volume-high" ) );
else volMuteLabel->setPixmap( QPixmap( ":/volume-medium" ) );
volMuteLabel->setToolTip( qtr( "Mute" ) );
}
void SoundWidget::updateVolume()
{
/* Audio part */
audio_volume_t i_volume;
aout_VolumeGet( p_intf, &i_volume );
i_volume = ( i_volume * VOLUME_MAX )/ (AOUT_VOLUME_MAX/2);
int i_gauge = volumeSlider->value();
b_my_volume = false;
if( i_volume - i_gauge > 1 || i_gauge - i_volume > 1 )
{
b_my_volume = true;
volumeSlider->setValue( i_volume );
b_my_volume = false;
}
}
void TeletextController::toggleTeletextTransparency( bool b_transparent )
{
telexTransparent->setIcon( b_transparent ? QIcon( ":/tvtelx" )
: QIcon( ":/tvtelx-trans" ) );
}
void TeletextController::enableTeletextButtons( bool b_enabled )
{
telexOn->setChecked( b_enabled );
telexTransparent->setEnabled( b_enabled );
telexPage->setEnabled( b_enabled );
}
void PlayButton::updateButton( bool b_playing )
{
setIcon( b_playing ? QIcon( ":/pause_b" ) : QIcon( ":/play_b" ) );
setToolTip( b_playing ? qtr( "Pause the playback" )
: qtr( I_PLAY_TOOLTIP ) );
}
void AtoB_Button::setIcons( bool timeA, bool timeB )
{
if( !timeA && !timeB)
{
setIcon( QIcon( ":/atob_nob" ) );
setToolTip( qtr( "Loop from point A to point B continuously\n"
"Click to set point A" ) );
}
else if( timeA && !timeB )
{
setIcon( QIcon( ":/atob_noa" ) );
setToolTip( qtr( "Click to set point B" ) );
}
else if( timeA && timeB )
{
setIcon( QIcon( ":/atob" ) );
setToolTip( qtr( "Stop the A to B loop" ) );
}
}
bool VolumeClickHandler::eventFilter( QObject *obj, QEvent *e )
{
VLC_UNUSED( obj );
if (e->type() == QEvent::MouseButtonPress )
{
aout_VolumeMute( p_intf, NULL );
audio_volume_t i_volume;
aout_VolumeGet( p_intf, &i_volume );
// m->updateVolume( i_volume * VOLUME_MAX / (AOUT_VOLUME_MAX/2) );
e->accept();
return true;
}
else
{
e->ignore();
return false;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2011 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Box.h"
#include <jpeglib.h>
#include <png.h>
#include <stdio.h>
#include <GL/gl.h>
#include <boost/bind.hpp>
#include "utf.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
// image/png - 89 50 4E 47 0D 0A 1A 0A
// image/gif - "GIF87a" or "GIF89a"
// image/jpeg - FF D8
// image/bmp - "BM"
// image/vnd.microsoft.icon - 00 00 01 00 (.ico), 00 00 02 00 (.cur)
namespace {
unsigned char* readAsPng(FILE* file, unsigned& width, unsigned& height)
{
png_byte header[8];
if (fread(header, 1, 8, file) != 8 || png_sig_cmp(header, 0, 8))
return 0;
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr)
return 0;
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
return 0;
}
png_infop end_info = png_create_info_struct(png_ptr);
if (!end_info) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return 0;
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return 0;
}
png_init_io(png_ptr, file);
png_set_sig_bytes(png_ptr, 8);
png_read_info(png_ptr, info_ptr);
width = png_get_image_width(png_ptr, info_ptr);
height = png_get_image_height(png_ptr, info_ptr);
unsigned bit_depth = png_get_bit_depth(png_ptr, info_ptr);
unsigned color_type = png_get_color_type(png_ptr, info_ptr);
if (color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png_ptr);
if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png_ptr);
if (bit_depth == 16)
png_set_strip_16(png_ptr);
if (color_type == PNG_COLOR_TYPE_RGB)
png_set_filler(png_ptr, 0xff, PNG_FILLER_BEFORE);
png_set_interlace_handling(png_ptr);
png_read_update_info(png_ptr, info_ptr);
unsigned rowbytes = png_get_rowbytes(png_ptr, info_ptr);
png_bytep data = (png_bytep) malloc(rowbytes * height);
png_bytep* row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height);
for (unsigned i = 0; i < height; i++)
row_pointers[i] = &data[rowbytes * i];
png_read_image(png_ptr, row_pointers);
free(row_pointers);
png_read_end(png_ptr, end_info);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return data;
}
unsigned char* readAsJpeg(FILE* file, unsigned& width, unsigned& height, unsigned& format)
{
unsigned char sig[2];
if (fread(sig, 1, 2, file) != 2 || sig[0] != 0xFF || sig[1] != 0xD8)
return 0;
rewind(file);
JSAMPARRAY img;
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr); // TODO: set our own error handdler
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, file);
jpeg_read_header(&cinfo, true);
width = cinfo.image_width;
height = cinfo.image_height;
jpeg_start_decompress(&cinfo);
unsigned char* data = (unsigned char*) malloc(height * width * cinfo.out_color_components);
img = (JSAMPARRAY) malloc(sizeof(JSAMPROW) * height);
for (unsigned i = 0; i < height; ++i)
img[i] = (JSAMPROW) &data[cinfo.out_color_components * width * i];
while(cinfo.output_scanline < cinfo.output_height)
jpeg_read_scanlines(&cinfo,
img + cinfo.output_scanline,
cinfo.output_height - cinfo.output_scanline);
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
free(img);
if (cinfo.out_color_components == 1)
format = GL_LUMINANCE;
else
format = GL_RGB;
return data;
}
} // namespace
BoxImage::BoxImage(Box* box) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(0),
format(GL_RGBA),
img(static_cast<html::HTMLImageElement*>(0) /* nullptr */)
{
}
BoxImage::BoxImage(Box* box, const std::u16string& base, const std::u16string& url, unsigned repeat) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(repeat),
format(GL_RGBA),
img(static_cast<html::HTMLImageElement*>(0) /* nullptr */),
request(base)
{
open(url);
}
BoxImage::BoxImage(Box* box, const std::u16string& base, html::HTMLImageElement& img) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(0),
format(GL_RGBA),
img(img),
request(base)
{
open(img.getSrc());
}
void BoxImage::open(const std::u16string& url)
{
request.open(u"GET", url);
request.setHanndler(boost::bind(&BoxImage::notify, this));
request.send();
state = Sent;
if (request.getReadyState() != HttpRequest::DONE)
return;
if (request.getErrorFlag()) {
state = Broken;
return;
}
FILE* file = request.openFile();
if (!file) {
state = Broken;
return;
}
pixels = readAsPng(file, naturalWidth, naturalHeight);
if (!pixels) {
rewind(file);
pixels = readAsJpeg(file, naturalWidth, naturalHeight, format);
}
if (pixels)
state = CompletelyAvailable;
else
state = Broken;
fclose(file);
}
void BoxImage::notify()
{
if (state == Sent) {
// TODO: update render tree!!
box->flags = 1;
}
}
}}}} // org::w3c::dom::bootstrap
<commit_msg>(BoxImage::notify) : Fix not to send requests repeatedly.<commit_after>/*
* Copyright 2011 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Box.h"
#include <jpeglib.h>
#include <png.h>
#include <stdio.h>
#include <GL/gl.h>
#include <boost/bind.hpp>
#include "utf.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
// image/png - 89 50 4E 47 0D 0A 1A 0A
// image/gif - "GIF87a" or "GIF89a"
// image/jpeg - FF D8
// image/bmp - "BM"
// image/vnd.microsoft.icon - 00 00 01 00 (.ico), 00 00 02 00 (.cur)
namespace {
unsigned char* readAsPng(FILE* file, unsigned& width, unsigned& height)
{
png_byte header[8];
if (fread(header, 1, 8, file) != 8 || png_sig_cmp(header, 0, 8))
return 0;
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr)
return 0;
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
return 0;
}
png_infop end_info = png_create_info_struct(png_ptr);
if (!end_info) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return 0;
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return 0;
}
png_init_io(png_ptr, file);
png_set_sig_bytes(png_ptr, 8);
png_read_info(png_ptr, info_ptr);
width = png_get_image_width(png_ptr, info_ptr);
height = png_get_image_height(png_ptr, info_ptr);
unsigned bit_depth = png_get_bit_depth(png_ptr, info_ptr);
unsigned color_type = png_get_color_type(png_ptr, info_ptr);
if (color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png_ptr);
if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png_ptr);
if (bit_depth == 16)
png_set_strip_16(png_ptr);
if (color_type == PNG_COLOR_TYPE_RGB)
png_set_filler(png_ptr, 0xff, PNG_FILLER_BEFORE);
png_set_interlace_handling(png_ptr);
png_read_update_info(png_ptr, info_ptr);
unsigned rowbytes = png_get_rowbytes(png_ptr, info_ptr);
png_bytep data = (png_bytep) malloc(rowbytes * height);
png_bytep* row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height);
for (unsigned i = 0; i < height; i++)
row_pointers[i] = &data[rowbytes * i];
png_read_image(png_ptr, row_pointers);
free(row_pointers);
png_read_end(png_ptr, end_info);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return data;
}
unsigned char* readAsJpeg(FILE* file, unsigned& width, unsigned& height, unsigned& format)
{
unsigned char sig[2];
if (fread(sig, 1, 2, file) != 2 || sig[0] != 0xFF || sig[1] != 0xD8)
return 0;
rewind(file);
JSAMPARRAY img;
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr); // TODO: set our own error handdler
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, file);
jpeg_read_header(&cinfo, true);
width = cinfo.image_width;
height = cinfo.image_height;
jpeg_start_decompress(&cinfo);
unsigned char* data = (unsigned char*) malloc(height * width * cinfo.out_color_components);
img = (JSAMPARRAY) malloc(sizeof(JSAMPROW) * height);
for (unsigned i = 0; i < height; ++i)
img[i] = (JSAMPROW) &data[cinfo.out_color_components * width * i];
while(cinfo.output_scanline < cinfo.output_height)
jpeg_read_scanlines(&cinfo,
img + cinfo.output_scanline,
cinfo.output_height - cinfo.output_scanline);
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
free(img);
if (cinfo.out_color_components == 1)
format = GL_LUMINANCE;
else
format = GL_RGB;
return data;
}
} // namespace
BoxImage::BoxImage(Box* box) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(0),
format(GL_RGBA),
img(static_cast<html::HTMLImageElement*>(0) /* nullptr */)
{
}
BoxImage::BoxImage(Box* box, const std::u16string& base, const std::u16string& url, unsigned repeat) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(repeat),
format(GL_RGBA),
img(static_cast<html::HTMLImageElement*>(0) /* nullptr */),
request(base)
{
open(url);
}
BoxImage::BoxImage(Box* box, const std::u16string& base, html::HTMLImageElement& img) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(0),
format(GL_RGBA),
img(img),
request(base)
{
open(img.getSrc());
}
void BoxImage::open(const std::u16string& url)
{
request.open(u"GET", url);
request.setHanndler(boost::bind(&BoxImage::notify, this));
request.send();
state = Sent;
if (request.getReadyState() != HttpRequest::DONE)
return;
if (request.getErrorFlag()) {
state = Broken;
return;
}
FILE* file = request.openFile();
if (!file) {
state = Broken;
return;
}
pixels = readAsPng(file, naturalWidth, naturalHeight);
if (!pixels) {
rewind(file);
pixels = readAsJpeg(file, naturalWidth, naturalHeight, format);
}
if (pixels)
state = CompletelyAvailable;
else
state = Broken;
fclose(file);
}
void BoxImage::notify()
{
if (state == Sent) {
if (request.getStatus() == 200)
box->flags = 1; // for updating render tree.
else
state = Unavailable;
}
}
}}}} // org::w3c::dom::bootstrap
<|endoftext|>
|
<commit_before><commit_msg>introduced Date::IsValidDate() and Date::Normalize()<commit_after><|endoftext|>
|
<commit_before><commit_msg>Remove some unused macros<commit_after><|endoftext|>
|
<commit_before>#include <cstring>
#include <Bull/Core/IO/InStringStream.hpp>
namespace Bull
{
InStringStream::InStringStream(const String& string) :
m_cursor(0),
m_string(string)
{
/// Nothing
}
ByteArray InStringStream::read(std::size_t length)
{
ByteArray bytes(length);
std::memcpy(&bytes[0], &m_string[m_cursor], length);
m_cursor += length;
return bytes;
}
void InStringStream::skip(std::size_t length)
{
m_cursor += length;
}
size_t InStringStream::getSize() const
{
return m_string.getSize();
}
bool InStringStream::isAtEnd() const
{
return m_cursor < m_string.getSize();
}
}<commit_msg>[Core/InStringStream] Fix isAtEnd method<commit_after>#include <cstring>
#include <Bull/Core/IO/InStringStream.hpp>
namespace Bull
{
InStringStream::InStringStream(const String& string) :
m_cursor(0),
m_string(string)
{
/// Nothing
}
ByteArray InStringStream::read(std::size_t length)
{
ByteArray bytes = ByteArray::memoryCopy(&m_string[m_cursor], length);
m_cursor += length;
return bytes;
}
void InStringStream::skip(std::size_t length)
{
m_cursor += length;
}
size_t InStringStream::getSize() const
{
return m_string.getSize();
}
bool InStringStream::isAtEnd() const
{
return m_cursor >= getSize();
}
}<|endoftext|>
|
<commit_before>#pragma once
#include <array>
#include <algorithm>
#include <initializer_list>
#include <cassert>
#include "But/Mpl/SizeTypeFor.hpp"
namespace But
{
namespace Container
{
/** @brief simple std::array<> replacement, that keeps number of elements. this way
* container can appear to be resizing, even though the maximum number of elements
* is predefined with N.
*
* @note elements T must be default-constructible, just like in regular std::array<>
*
* @note when element is removed, it is internally overwritten with a default-value.
*/
template<typename T, size_t N>
class ArrayWithSize final
{
using Container = std::array<T,N>;
public:
using difference_type = typename Container::difference_type;
using size_type = typename Mpl::SizeTypeFor<N>::type;
using value_type = typename Container::value_type;
using iterator = typename Container::iterator;
using const_iterator = typename Container::const_iterator;
ArrayWithSize() = default;
ArrayWithSize(std::initializer_list<T> lst)
{
assert( lst.size() <= N && "too many arguments for a given type" );
for(auto& e: lst)
push_back(e);
}
ArrayWithSize(ArrayWithSize const& other)
{
for(auto const& e: other)
push_back(e);
}
ArrayWithSize& operator=(ArrayWithSize const& other)
{
copyOrMove(other);
return *this;
}
ArrayWithSize(ArrayWithSize&& other)
{
for(auto&& e: other)
push_back( std::move(e) );
other.size_ = 0u;
}
ArrayWithSize& operator=(ArrayWithSize&& other)
{
if( copyOrMove( std::move(other) ) )
other.size_ = 0u;
return *this;
}
bool empty() const { return size() == 0u; }
size_type size() const { return size_; }
constexpr size_t max_size() const { return N; }
template<typename ...Args>
void emplace_back(Args&&... args)
{
push_back( value_type{ std::forward<Args>(args)... } );
}
void push_back(value_type const& vt)
{
assert( size() < max_size() && "overflow detected" );
c_[size_] = vt;
++size_;
}
void push_back(value_type&& vt)
{
assert( size() < max_size() && "overflow detected" );
c_[size_] = std::move(vt);
++size_;
}
void pop_back()
{
assert( not empty() );
--size_;
c_[size_] = value_type{};
}
value_type const& operator[](const size_type pos) const
{
assert( pos < size() && "index out of bound" );
return c_[pos];
}
value_type& operator[](const size_type pos)
{
assert( pos < size() && "index out of bound" );
return c_[pos];
}
void clear()
{
while( not empty() )
pop_back();
}
const_iterator cbegin() const { using std::begin; return begin(c_); }
const_iterator cend() const { return cbegin() + size_; }
const_iterator begin() const { return cbegin(); }
const_iterator end() const { return begin() + size_; }
iterator begin() { using std::begin; return begin(c_); }
iterator end() { return begin() + size_; }
private:
template<typename Other>
bool copyOrMove(Other&& other)
{
if(this==&other)
return false;
clear();
for(auto&& e: other)
push_back( std::move(e) );
return true;
}
Container c_;
size_type size_{0};
};
template<typename T, size_t N>
bool operator==(ArrayWithSize<T,N> const& lhs, ArrayWithSize<T,N> const& rhs)
{
if( lhs.size() != rhs.size() )
return false;
for(typename ArrayWithSize<T,N>::size_type i=0; i<lhs.size(); ++i)
if( lhs[i] != rhs[i] )
return false;
return true;
}
template<typename T, size_t N>
bool operator!=(ArrayWithSize<T,N> const& lhs, ArrayWithSize<T,N> const& rhs)
{
return not ( lhs == rhs );
}
template<typename T, size_t N>
bool operator<(ArrayWithSize<T,N> const& lhs, ArrayWithSize<T,N> const& rhs)
{
return std::lexicographical_compare( lhs.begin(), lhs.end(), rhs.begin(), rhs.end() );
}
template<typename T, size_t N>
bool operator<=(ArrayWithSize<T,N> const& lhs, ArrayWithSize<T,N> const& rhs)
{
return lhs == rhs || lhs < rhs;
}
template<typename T, size_t N>
bool operator>(ArrayWithSize<T,N> const& lhs, ArrayWithSize<T,N> const& rhs)
{
return not ( lhs <= rhs );
}
template<typename T, size_t N>
bool operator>=(ArrayWithSize<T,N> const& lhs, ArrayWithSize<T,N> const& rhs)
{
return not ( lhs < rhs );
}
}
}
<commit_msg>comparison for ArrayWithSize simplified<commit_after>#pragma once
#include <array>
#include <algorithm>
#include <initializer_list>
#include <cassert>
#include "But/Mpl/SizeTypeFor.hpp"
namespace But
{
namespace Container
{
/** @brief simple std::array<> replacement, that keeps number of elements. this way
* container can appear to be resizing, even though the maximum number of elements
* is predefined with N.
*
* @note elements T must be default-constructible, just like in regular std::array<>
*
* @note when element is removed, it is internally overwritten with a default-value.
*/
template<typename T, size_t N>
class ArrayWithSize final
{
using Container = std::array<T,N>;
public:
using difference_type = typename Container::difference_type;
using size_type = typename Mpl::SizeTypeFor<N>::type;
using value_type = typename Container::value_type;
using iterator = typename Container::iterator;
using const_iterator = typename Container::const_iterator;
ArrayWithSize() = default;
ArrayWithSize(std::initializer_list<T> lst)
{
assert( lst.size() <= N && "too many arguments for a given type" );
for(auto& e: lst)
push_back(e);
}
ArrayWithSize(ArrayWithSize const& other)
{
for(auto const& e: other)
push_back(e);
}
ArrayWithSize& operator=(ArrayWithSize const& other)
{
copyOrMove(other);
return *this;
}
ArrayWithSize(ArrayWithSize&& other)
{
for(auto&& e: other)
push_back( std::move(e) );
other.size_ = 0u;
}
ArrayWithSize& operator=(ArrayWithSize&& other)
{
if( copyOrMove( std::move(other) ) )
other.size_ = 0u;
return *this;
}
bool empty() const { return size() == 0u; }
size_type size() const { return size_; }
constexpr size_t max_size() const { return N; }
template<typename ...Args>
void emplace_back(Args&&... args)
{
push_back( value_type{ std::forward<Args>(args)... } );
}
void push_back(value_type const& vt)
{
assert( size() < max_size() && "overflow detected" );
c_[size_] = vt;
++size_;
}
void push_back(value_type&& vt)
{
assert( size() < max_size() && "overflow detected" );
c_[size_] = std::move(vt);
++size_;
}
void pop_back()
{
assert( not empty() );
--size_;
c_[size_] = value_type{};
}
value_type const& operator[](const size_type pos) const
{
assert( pos < size() && "index out of bound" );
return c_[pos];
}
value_type& operator[](const size_type pos)
{
assert( pos < size() && "index out of bound" );
return c_[pos];
}
void clear()
{
while( not empty() )
pop_back();
}
const_iterator cbegin() const { using std::begin; return begin(c_); }
const_iterator cend() const { return cbegin() + size_; }
const_iterator begin() const { return cbegin(); }
const_iterator end() const { return begin() + size_; }
iterator begin() { using std::begin; return begin(c_); }
iterator end() { return begin() + size_; }
private:
template<typename Other>
bool copyOrMove(Other&& other)
{
if(this==&other)
return false;
clear();
for(auto&& e: other)
push_back( std::move(e) );
return true;
}
Container c_;
size_type size_{0};
};
template<typename T, size_t N>
bool operator==(ArrayWithSize<T,N> const& lhs, ArrayWithSize<T,N> const& rhs)
{
using std::begin;
using std::end;
return std::equal( begin(lhs), end(lhs), begin(rhs), end(rhs) );
}
template<typename T, size_t N>
bool operator!=(ArrayWithSize<T,N> const& lhs, ArrayWithSize<T,N> const& rhs)
{
return not ( lhs == rhs );
}
template<typename T, size_t N>
bool operator<(ArrayWithSize<T,N> const& lhs, ArrayWithSize<T,N> const& rhs)
{
return std::lexicographical_compare( lhs.begin(), lhs.end(), rhs.begin(), rhs.end() );
}
template<typename T, size_t N>
bool operator<=(ArrayWithSize<T,N> const& lhs, ArrayWithSize<T,N> const& rhs)
{
return lhs == rhs || lhs < rhs;
}
template<typename T, size_t N>
bool operator>(ArrayWithSize<T,N> const& lhs, ArrayWithSize<T,N> const& rhs)
{
return not ( lhs <= rhs );
}
template<typename T, size_t N>
bool operator>=(ArrayWithSize<T,N> const& lhs, ArrayWithSize<T,N> const& rhs)
{
return not ( lhs < rhs );
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2011, 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 <object/finalizable.hh>
#include <object/formatter.hh>
#include <object/format-info.hh>
#include <object/input-stream.hh>
#include <object/output-stream.hh>
#include <urbi/object/barrier.hh>
#include <urbi/object/code.hh>
#include <urbi/object/date.hh>
#include <urbi/object/dictionary.hh>
#include <urbi/object/directory.hh>
#include <urbi/object/duration.hh>
#include <urbi/object/event-handler.hh>
#include <urbi/object/file.hh>
#include <urbi/object/location.hh>
#include <object/logger.hh>
#include <object/process.hh>
#include <object/regexp.hh>
#include <object/socket.hh>
#include <object/semaphore.hh>
#include <object/uconnection.hh>
#include <object/uvalue.hh>
#include <object/uvar.hh>
namespace urbi
{
namespace object
{
# define URBI_OBJECT_UNION_FIELD(Class) char Class ## _[sizeof(Class)],
union ObjectSize
{
APPLY_ON_ALL_OBJECTS(URBI_OBJECT_UNION_FIELD)
};
# undef URBI_OBJECT_UNION_FIELD
const size_t Object::allocator_static_max_size = sizeof(ObjectSize);
}
}
<commit_msg>build: fix.<commit_after>/*
* Copyright (C) 2011, 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 <object/finalizable.hh>
#include <object/format-info.hh>
#include <object/formatter.hh>
#include <object/input-stream.hh>
#include <object/logger.hh>
#include <object/output-stream.hh>
#include <object/process.hh>
#include <object/regexp.hh>
#include <object/semaphore.hh>
#include <object/socket.hh>
#include <object/uconnection.hh>
#include <object/uvalue.hh>
#include <object/uvar.hh>
#include <urbi/object/barrier.hh>
#include <urbi/object/code.hh>
#include <urbi/object/date.hh>
#include <urbi/object/dictionary.hh>
#include <urbi/object/directory.hh>
#include <urbi/object/duration.hh>
#include <urbi/object/event-handler.hh>
#include <urbi/object/file.hh>
#include <urbi/object/job.hh>
#include <urbi/object/location.hh>
namespace urbi
{
namespace object
{
# define URBI_OBJECT_UNION_FIELD(Class) char Class ## _[sizeof(Class)]
union ObjectSize
{
APPLY_ON_ALL_OBJECTS(URBI_OBJECT_UNION_FIELD)
};
# undef URBI_OBJECT_UNION_FIELD
const size_t Object::allocator_static_max_size = sizeof(ObjectSize);
}
}
<|endoftext|>
|
<commit_before>#include "ssaorenderpass.hpp"
#include "../../engine.hpp"
#include <random>
#include <world/component/transformcomponent.hpp>
SSAORenderSystem::SSAORenderSystem(int width, int height)
{
shaderProgram
.attach("assets/shaders/ssao.vert", ShaderType::vertex)
.attach("assets/shaders/ssao.frag", ShaderType::fragment)
.finalize();
shaderProgram
.addUniform("positionMap")
.addUniform("normalMap")
.addUniform("noiseMap")
.addUniform("noiseScale")
.addUniform("nrOfSamples")
.addUniform("sampleRadius")
.addUniform("sampleBias")
.addUniform("samplePoints")
.addUniform("viewMatrix")
.addUniform("projectionMatrix");
gBuffer.attachTexture(0, width, height, GL_RED, GL_FLOAT, 1);
shaderProgram.bind();
generateUniformData(width, height);
}
float SSAORenderSystem::lerp(float a, float b, float f)
{
return a + f * (b - a);
}
void SSAORenderSystem::generateUniformData(int width, int height)
{
std::uniform_real_distribution<GLfloat> randomFlaots(0.0, 1.0);
std::default_random_engine generator;
std::vector<glm::vec3> samplePoints;
for (size_t i = 0; i < 64; i++)
{
glm::vec3 samplePoint = {
randomFlaots(generator) * 2.0 - 1.0,
randomFlaots(generator) * 2.0 - 1.0,
randomFlaots(generator)
};
samplePoint = glm::normalize(samplePoint);
samplePoint *= randomFlaots(generator);
float scale = float(i) / 64.0;
scale = lerp(0.1, 1.0, scale * scale);
samplePoint *= scale;
samplePoints.push_back(samplePoint);
}
shaderProgram.setUniformArray("samplePoints", samplePoints);
std::vector<glm::vec3> noiseData;
for (size_t i = 0; i < 16; i++)
{
glm::vec3 noise = {
randomFlaots(generator) * 2.0 - 1.0,
randomFlaots(generator) * 2.0 - 1.0,
0.0
};
noiseData.push_back(noise);
}
noiseMap = std::make_shared<Texture>(width, height, GL_RGB32F, GL_RGB, GL_FLOAT, &noiseData[0]);
noiseMap->bind()
.setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST)
.setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST)
.setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT)
.setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);
attachInputTexture(3, noiseMap);
shaderProgram.setUniform("noiseMap", 3);
glm::vec2 noiseScale = { width / 4.0, height / 4.0 };
shaderProgram.setUniform("noiseScale", noiseScale);
}
void SSAORenderSystem::render(World & world)
{
CameraEntity & camera = *Engine::getInstance().getCamera();
shaderProgram.bind();
shaderProgram.setUniform("viewMatrix", camera.getComponent<TransformComponent>()->rotation);
shaderProgram.setUniform("projectionMatrix", camera.getComponent<TransformComponent>()->rotation);
}
<commit_msg>formating<commit_after>#include "ssaorenderpass.hpp"
#include "../../engine.hpp"
#include <random>
#include <world/component/transformcomponent.hpp>
SSAORenderSystem::SSAORenderSystem(int width, int height)
{
shaderProgram
.attach("assets/shaders/ssao.vert", ShaderType::vertex)
.attach("assets/shaders/ssao.frag", ShaderType::fragment)
.finalize();
shaderProgram
.addUniform("positionMap")
.addUniform("normalMap")
.addUniform("noiseMap")
.addUniform("noiseScale")
.addUniform("nrOfSamples")
.addUniform("sampleRadius")
.addUniform("sampleBias")
.addUniform("samplePoints")
.addUniform("viewMatrix")
.addUniform("projectionMatrix");
gBuffer.attachTexture(0, width, height, GL_RED, GL_FLOAT, 1);
shaderProgram.bind();
generateUniformData(width, height);
}
float SSAORenderSystem::lerp(float a, float b, float f)
{
return a + f * (b - a);
}
void SSAORenderSystem::generateUniformData(int width, int height)
{
shaderProgram.setUniform("positionMap", 0);
shaderProgram.setUniform("normalMap", 1);
shaderProgram.setUniform("normalMap", 2);
std::uniform_real_distribution<GLfloat> randomFlaots(0.0, 1.0);
std::default_random_engine generator;
std::vector<glm::vec3> samplePoints;
for (size_t i = 0; i < 64; i++)
{
glm::vec3 samplePoint = {
randomFlaots(generator) * 2.0 - 1.0,
randomFlaots(generator) * 2.0 - 1.0,
randomFlaots(generator)
};
samplePoint = glm::normalize(samplePoint);
samplePoint *= randomFlaots(generator);
float scale = float(i) / 64.0;
scale = lerp(0.1, 1.0, scale * scale);
samplePoint *= scale;
samplePoints.push_back(samplePoint);
}
shaderProgram.setUniformArray("samplePoints", samplePoints);
std::vector<glm::vec3> noiseData;
for (size_t i = 0; i < 16; i++)
{
glm::vec3 noise = {
randomFlaots(generator) * 2.0 - 1.0,
randomFlaots(generator) * 2.0 - 1.0,
0.0
};
noiseData.push_back(noise);
}
noiseMap = std::make_shared<Texture>(width, height, GL_RGB32F, GL_RGB, GL_FLOAT, &noiseData[0]);
noiseMap->bind()
.setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST)
.setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST)
.setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT)
.setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);
attachInputTexture(2, noiseMap);
glm::vec2 noiseScale = { width / 4.0, height / 4.0 };
shaderProgram.setUniform("noiseScale", noiseScale);
}
void SSAORenderSystem::render(World & world)
{
CameraEntity & camera = *Engine::getInstance().getCamera();
shaderProgram.bind();
shaderProgram.setUniform("viewMatrix", camera.getComponent<TransformComponent>()->rotation);
shaderProgram.setUniform("projectionMatrix", camera.getComponent<TransformComponent>()->rotation);
}
<|endoftext|>
|
<commit_before>/**
* @file x_tre_split.hpp
* @author Andrew Wells
*
* Defintion of the XTreeSplit class, a class that splits the nodes of an X
* tree, starting at a leaf node and moving upwards if necessary.
*
* This is known to have a bug: see #368.
*/
#ifndef __MLPACK_CORE_TREE_RECTANGLE_TREE_X_TREE_SPLIT_HPP
#define __MLPACK_CORE_TREE_RECTANGLE_TREE_X_TREE_SPLIT_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace tree /** Trees and tree-building procedures. */ {
/**
* The X-tree paper says that a maximum allowable overlap of 20% works well.
*
* This code should eventually be refactored so as to avoid polluting
* mlpack::tree with this random double.
*/
const double MAX_OVERLAP = 0.2;
/**
* A Rectangle Tree has new points inserted at the bottom. When these
* nodes overflow, we split them, moving up the tree and splitting nodes
* as necessary.
*/
template<typename DescentType,
typename StatisticType,
typename MatType>
class XTreeSplit
{
public:
/**
* Split a leaf node using the algorithm described in "The R*-tree: An Efficient and Robust Access method
* for Points and Rectangles." If necessary, this split will propagate
* upwards through the tree.
*/
static void SplitLeafNode(RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* tree, std::vector<bool>& relevels);
/**
* Split a non-leaf node using the "default" algorithm. If this is a root node, the
* tree increases in depth.
*/
static bool SplitNonLeafNode(RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* tree, std::vector<bool>& relevels);
private:
/**
* Class to allow for faster sorting.
*/
class sortStruct {
public:
double d;
int n;
};
/**
* Comparator for sorting with sortStruct.
*/
static bool structComp(const sortStruct& s1, const sortStruct& s2) {
return s1.d < s2.d;
}
/**
* Insert a node into another node.
*/
static void InsertNodeIntoTree(
RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* destTree,
RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* srcNode);
};
}; // namespace tree
}; // namespace mlpack
// Include implementation
#include "x_tree_split_impl.hpp"
#endif
<commit_msg>Tabs to spaces (trivial commit; testing gitdub email notifier).<commit_after>/**
* @file x_tre_split.hpp
* @author Andrew Wells
*
* Defintion of the XTreeSplit class, a class that splits the nodes of an X
* tree, starting at a leaf node and moving upwards if necessary.
*
* This is known to have a bug: see #368.
*/
#ifndef __MLPACK_CORE_TREE_RECTANGLE_TREE_X_TREE_SPLIT_HPP
#define __MLPACK_CORE_TREE_RECTANGLE_TREE_X_TREE_SPLIT_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace tree /** Trees and tree-building procedures. */ {
/**
* The X-tree paper says that a maximum allowable overlap of 20% works well.
*
* This code should eventually be refactored so as to avoid polluting
* mlpack::tree with this random double.
*/
const double MAX_OVERLAP = 0.2;
/**
* A Rectangle Tree has new points inserted at the bottom. When these
* nodes overflow, we split them, moving up the tree and splitting nodes
* as necessary.
*/
template<typename DescentType,
typename StatisticType,
typename MatType>
class XTreeSplit
{
public:
/**
* Split a leaf node using the algorithm described in "The R*-tree: An Efficient and Robust Access method
* for Points and Rectangles." If necessary, this split will propagate
* upwards through the tree.
*/
static void SplitLeafNode(RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* tree, std::vector<bool>& relevels);
/**
* Split a non-leaf node using the "default" algorithm. If this is a root node, the
* tree increases in depth.
*/
static bool SplitNonLeafNode(RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* tree, std::vector<bool>& relevels);
private:
/**
* Class to allow for faster sorting.
*/
class sortStruct {
public:
double d;
int n;
};
/**
* Comparator for sorting with sortStruct.
*/
static bool structComp(const sortStruct& s1, const sortStruct& s2) {
return s1.d < s2.d;
}
/**
* Insert a node into another node.
*/
static void InsertNodeIntoTree(
RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* destTree,
RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* srcNode);
};
}; // namespace tree
}; // namespace mlpack
// Include implementation
#include "x_tree_split_impl.hpp"
#endif
<|endoftext|>
|
<commit_before>/*
color_master.cpp
This file is part of:
GAME PENCIL ENGINE
https://create.pawbyte.com
Copyright (c) 2014-2018 Nathan Hurde, Chase Lee.
Copyright (c) 2014-2018 PawByte.
Copyright (c) 2014-2018 Game Pencil Engine contributors ( Contributors Page )
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.
-Game Pencil Engine <https://create.pawbyte.com>
*/
#include "GPE_Color_Master.h"
GPE_Color_Master * MASTER_OF_COLORS = new GPE_Color_Master();
<commit_msg>Delete GPE_Color_Master.cpp<commit_after><|endoftext|>
|
<commit_before>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
// (c) 2009-2017 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
// HTTP/1 transport protocol tests
#include <xzero/http/http1/ConnectionFactory.h>
#include <xzero/http/HttpRequest.h>
#include <xzero/http/HttpResponse.h>
#include <xzero/executor/LocalExecutor.h>
#include <xzero/logging/LogTarget.h>
#include <xzero/net/Server.h>
#include <xzero/net/LocalConnector.h>
#include <xzero/Buffer.h>
#include <xzero/testing.h>
#include <xzero/http/http1/Parser.h>
#include <xzero/http/HttpListener.h>
#include <xzero/HugeBuffer.h>
using namespace xzero;
using namespace xzero::http;
using namespace xzero::http::http1;
// FIXME HTTP/1.1 with keep-alive) SEGV's on LocalEndPoint.
//
// TODO test that userapp cannot add invalid headers
// (e.g. connection level headers, such as Connection, TE,
// Transfer-Encoding, Keep-Alive)
// - this is actually a semantic check,
// http1::Channel should prohibit such things
class ResponseParser : public HttpListener { // {{{
public:
ResponseParser();
size_t parse(const BufferRef& response);
const HttpResponseInfo& responseInfo() const { return responseInfo_; };
const HugeBuffer& responseBody() const { return responseBody_; }
private:
void onMessageBegin(HttpVersion version, HttpStatus code,
const BufferRef& text) override;
void onMessageHeader(const BufferRef& name, const BufferRef& value) override;
void onMessageHeaderEnd() override;
void onMessageContent(const BufferRef& chunk) override;
void onMessageContent(FileView&& chunk) override;
void onMessageEnd() override;
void onError(std::error_code ec) override;
private:
HttpResponseInfo responseInfo_;
HugeBuffer responseBody_;
};
ResponseParser::ResponseParser()
: responseInfo_(),
responseBody_(1024) {
}
size_t ResponseParser::parse(const BufferRef& response) {
http1::Parser parser(Parser::RESPONSE, this);
responseInfo_.reset();
responseBody_.reset();
return parser.parseFragment(response);
}
void ResponseParser::onMessageBegin(HttpVersion version, HttpStatus code,
const BufferRef& text) {
responseInfo_.setVersion(version);
responseInfo_.setStatus(code);
responseInfo_.setReason(text.str());
}
void ResponseParser::onMessageHeader(const BufferRef& name, const BufferRef& value) {
responseInfo_.headers().push_back(name.str(), value.str());
}
void ResponseParser::onMessageHeaderEnd() {
}
void ResponseParser::onMessageContent(const BufferRef& chunk) {
responseBody_.write(chunk);
}
void ResponseParser::onMessageContent(FileView&& chunk) {
responseBody_.write(std::move(chunk));
}
void ResponseParser::onMessageEnd() {
responseInfo_.setContentLength(responseBody_.size());
// promise_->success(this);
}
void ResponseParser::onError(std::error_code ec) {
// TODO promise_->failure(Status::ForeignError);
}
// }}}
class ScopedLogger { // {{{
public:
ScopedLogger() {
// xzero::LogAggregator::get().setLogLevel(xzero::LogLevel::Trace);
// xzero::LogAggregator::get().setLogTarget(xzero::LogTarget::console());
}
~ScopedLogger() {
// xzero::LogAggregator::get().setLogLevel(xzero::LogLevel::None);
// xzero::LogAggregator::get().setLogTarget(nullptr);
}
};
// }}}
static const size_t requestHeaderBufferSize = 8 * 1024;
static const size_t requestBodyBufferSize = 8 * 1024;
static const size_t maxRequestUriLength = 64;
static const size_t maxRequestBodyLength = 128;
static const size_t maxRequestCount = 5;
static const Duration maxKeepAlive = 30_seconds;
#define SCOPED_LOGGER() ScopedLogger _scoped_logger_;
#define MOCK_HTTP1_SERVER(server, localConnector, executor) \
xzero::Server server; \
xzero::LocalExecutor executor(false); \
auto localConnector = server.addConnector<xzero::LocalConnector>(&executor); \
auto http = std::make_unique<xzero::http::http1::ConnectionFactory>( \
requestHeaderBufferSize, requestBodyBufferSize, \
maxRequestUriLength, maxRequestBodyLength, maxRequestCount, \
maxKeepAlive, false, false); \
http->setHandler([&](HttpRequest* request, HttpResponse* response) { \
response->setStatus(HttpStatus::Ok); \
response->setContentLength(request->path().size() + 1); \
response->setHeader("Content-Type", "text/plain"); \
response->write(Buffer(request->path() + "\n"), \
std::bind(&HttpResponse::completed, response)); \
}); \
localConnector->addConnectionFactory(http->protocolName(), \
std::bind(&HttpConnectionFactory::create, http.get(), \
std::placeholders::_1, \
std::placeholders::_2)); \
server.start();
TEST(http_http1_Connection, ConnectionClose_1_1) {
MOCK_HTTP1_SERVER(server, connector, executor);
xzero::RefPtr<LocalEndPoint> ep;
executor.execute([&] {
ep = connector->createClient("GET / HTTP/1.1\r\n"
"Host: test\r\n"
"Connection: close\r\n"
"\r\n");
});
Buffer output = ep->output();
ResponseParser resp;
resp.parse(output);
EXPECT_EQ(HttpVersion::VERSION_1_1, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::Ok, resp.responseInfo().status());
EXPECT_EQ("close", resp.responseInfo().getHeader("Connection"));
}
TEST(http_http1_Connection, ConnectionClose_1_0) {
MOCK_HTTP1_SERVER(server, connector, executor);
xzero::RefPtr<LocalEndPoint> ep;
executor.execute([&] {
ep = connector->createClient("GET / HTTP/1.0\r\n"
"\r\n");
});
Buffer output = ep->output();
ResponseParser resp;
resp.parse(output);
EXPECT_EQ(HttpVersion::VERSION_1_0, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::Ok, resp.responseInfo().status());
EXPECT_EQ("close", resp.responseInfo().getHeader("Connection"));
}
// sends one single request
TEST(http_http1_Connection, ConnectionKeepAlive_1_0) {
MOCK_HTTP1_SERVER(server, connector, executor);
xzero::RefPtr<LocalEndPoint> ep;
executor.execute([&] {
ep = connector->createClient("GET /hello HTTP/1.0\r\n"
"Connection: Keep-Alive\r\n"
"\r\n");
});
Buffer output = ep->output();
ResponseParser resp;
size_t n = resp.parse(output);
EXPECT_EQ(HttpVersion::VERSION_1_0, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::Ok, resp.responseInfo().status());
EXPECT_EQ("Keep-Alive", resp.responseInfo().getHeader("Connection"));
EXPECT_EQ("/hello\n", resp.responseBody().getBuffer());
}
// sends one single request
TEST(http_http1_Connection, ConnectionKeepAlive_1_1) {
MOCK_HTTP1_SERVER(server, connector, executor);
xzero::RefPtr<LocalEndPoint> ep;
executor.execute([&] {
ep = connector->createClient("GET /hello HTTP/1.1\r\n"
"Host: test\r\n"
"\r\n");
//printf("%s\n", ep->output().str().c_str());
});
Buffer output = ep->output();
ResponseParser resp;
size_t n = resp.parse(output);
EXPECT_EQ(HttpVersion::VERSION_1_1, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::Ok, resp.responseInfo().status());
EXPECT_EQ("Keep-Alive", resp.responseInfo().getHeader("Connection"));
EXPECT_EQ("/hello\n", resp.responseBody().getBuffer());
}
// sends single request, gets response, sends another one on the same line.
// TEST(http_http1_Connection, ConnectionKeepAlive2) { TODO
// }
// sends 3 requests pipelined all at once. receives responses in order
TEST(http_http1_Connection, ConnectionKeepAlive3_pipelined) {
//SCOPED_LOGGER();
MOCK_HTTP1_SERVER(server, connector, executor);
xzero::RefPtr<LocalEndPoint> ep;
executor.execute([&] {
ep = connector->createClient("GET /one HTTP/1.1\r\nHost: test\r\n\r\n"
"GET /two HTTP/1.1\r\nHost: test\r\n\r\n"
"GET /three HTTP/1.1\r\nHost: test\r\n\r\n");
});
Buffer output = ep->output();
ResponseParser resp;
size_t n = resp.parse(output);
EXPECT_EQ(HttpVersion::VERSION_1_1, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::Ok, resp.responseInfo().status());
EXPECT_EQ("Keep-Alive", resp.responseInfo().getHeader("Connection"));
EXPECT_EQ("/one\n", resp.responseBody().getBuffer());
n += resp.parse(output.ref(n));
EXPECT_EQ(HttpVersion::VERSION_1_1, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::Ok, resp.responseInfo().status());
EXPECT_EQ("Keep-Alive", resp.responseInfo().getHeader("Connection"));
EXPECT_EQ("/two\n", resp.responseBody().getBuffer());
n += resp.parse(output.ref(n));
EXPECT_EQ(HttpVersion::VERSION_1_1, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::Ok, resp.responseInfo().status());
EXPECT_EQ("Keep-Alive", resp.responseInfo().getHeader("Connection"));
EXPECT_EQ("/three\n", resp.responseBody().getBuffer());
// no garbage should have been generated at the end
ASSERT_EQ(n, output.size());
}
// ensure proper error code on bad request line
TEST(http_http1_Connection, protocolErrorShouldRaise400) {
// SCOPED_LOGGER();
MOCK_HTTP1_SERVER(server, connector, executor);
xzero::RefPtr<LocalEndPoint> ep;
executor.execute([&] {
// FIXME HTTP/1.1 (due to keep-alive) SEGV's on LocalEndPoint.
ep = connector->createClient("GET\r\n\r\n");
});
Buffer output = ep->output();
ResponseParser resp;
resp.parse(output);
EXPECT_EQ(HttpVersion::VERSION_0_9, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::BadRequest, resp.responseInfo().status());
}
<commit_msg>[test] adapted to past code changes<commit_after>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
// (c) 2009-2017 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
// HTTP/1 transport protocol tests
#include <xzero/http/http1/ConnectionFactory.h>
#include <xzero/http/HttpRequest.h>
#include <xzero/http/HttpResponse.h>
#include <xzero/executor/LocalExecutor.h>
#include <xzero/logging/LogTarget.h>
#include <xzero/net/Server.h>
#include <xzero/net/LocalConnector.h>
#include <xzero/Buffer.h>
#include <xzero/testing.h>
#include <xzero/http/http1/Parser.h>
#include <xzero/http/HttpListener.h>
#include <xzero/HugeBuffer.h>
using namespace xzero;
using namespace xzero::http;
using namespace xzero::http::http1;
// FIXME HTTP/1.1 with keep-alive) SEGV's on LocalEndPoint.
//
// TODO test that userapp cannot add invalid headers
// (e.g. connection level headers, such as Connection, TE,
// Transfer-Encoding, Keep-Alive)
// - this is actually a semantic check,
// http1::Channel should prohibit such things
class ResponseParser : public HttpListener { // {{{
public:
ResponseParser();
size_t parse(const BufferRef& response);
const HttpResponseInfo& responseInfo() const { return responseInfo_; };
const HugeBuffer& responseBody() const { return responseBody_; }
private:
void onMessageBegin(HttpVersion version, HttpStatus code,
const BufferRef& text) override;
void onMessageHeader(const BufferRef& name, const BufferRef& value) override;
void onMessageHeaderEnd() override;
void onMessageContent(const BufferRef& chunk) override;
void onMessageContent(FileView&& chunk) override;
void onMessageEnd() override;
void onError(std::error_code ec) override;
private:
HttpResponseInfo responseInfo_;
HugeBuffer responseBody_;
};
ResponseParser::ResponseParser()
: responseInfo_(),
responseBody_(1024) {
}
size_t ResponseParser::parse(const BufferRef& response) {
http1::Parser parser(Parser::RESPONSE, this);
responseInfo_.reset();
responseBody_.clear();
return parser.parseFragment(response);
}
void ResponseParser::onMessageBegin(HttpVersion version, HttpStatus code,
const BufferRef& text) {
responseInfo_.setVersion(version);
responseInfo_.setStatus(code);
responseInfo_.setReason(text.str());
}
void ResponseParser::onMessageHeader(const BufferRef& name, const BufferRef& value) {
responseInfo_.headers().push_back(name.str(), value.str());
}
void ResponseParser::onMessageHeaderEnd() {
}
void ResponseParser::onMessageContent(const BufferRef& chunk) {
responseBody_.write(chunk);
}
void ResponseParser::onMessageContent(FileView&& chunk) {
responseBody_.write(std::move(chunk));
}
void ResponseParser::onMessageEnd() {
responseInfo_.setContentLength(responseBody_.size());
// promise_->success(this);
}
void ResponseParser::onError(std::error_code ec) {
// TODO promise_->failure(Status::ForeignError);
}
// }}}
class ScopedLogger { // {{{
public:
ScopedLogger() {
// xzero::LogAggregator::get().setLogLevel(xzero::LogLevel::Trace);
// xzero::LogAggregator::get().setLogTarget(xzero::LogTarget::console());
}
~ScopedLogger() {
// xzero::LogAggregator::get().setLogLevel(xzero::LogLevel::None);
// xzero::LogAggregator::get().setLogTarget(nullptr);
}
};
// }}}
static const size_t requestHeaderBufferSize = 8 * 1024;
static const size_t requestBodyBufferSize = 8 * 1024;
static const size_t maxRequestUriLength = 64;
static const size_t maxRequestBodyLength = 128;
static const size_t maxRequestCount = 5;
static const Duration maxKeepAlive = 30_seconds;
#define SCOPED_LOGGER() ScopedLogger _scoped_logger_;
#define MOCK_HTTP1_SERVER(server, localConnector, executor) \
xzero::Server server; \
xzero::LocalExecutor executor(false); \
auto localConnector = server.addConnector<xzero::LocalConnector>(&executor); \
auto http = std::make_unique<xzero::http::http1::ConnectionFactory>( \
requestHeaderBufferSize, requestBodyBufferSize, \
maxRequestUriLength, maxRequestBodyLength, maxRequestCount, \
maxKeepAlive, false, false); \
http->setHandler([&](HttpRequest* request, HttpResponse* response) { \
response->setStatus(HttpStatus::Ok); \
response->setContentLength(request->path().size() + 1); \
response->setHeader("Content-Type", "text/plain"); \
response->write(Buffer(request->path() + "\n"), \
std::bind(&HttpResponse::completed, response)); \
}); \
localConnector->addConnectionFactory(http->protocolName(), \
std::bind(&HttpConnectionFactory::create, http.get(), \
std::placeholders::_1, \
std::placeholders::_2)); \
server.start();
TEST(http_http1_Connection, ConnectionClose_1_1) {
MOCK_HTTP1_SERVER(server, connector, executor);
xzero::RefPtr<LocalEndPoint> ep;
executor.execute([&] {
ep = connector->createClient("GET / HTTP/1.1\r\n"
"Host: test\r\n"
"Connection: close\r\n"
"\r\n");
});
Buffer output = ep->output();
ResponseParser resp;
resp.parse(output);
EXPECT_EQ(HttpVersion::VERSION_1_1, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::Ok, resp.responseInfo().status());
EXPECT_EQ("close", resp.responseInfo().getHeader("Connection"));
}
TEST(http_http1_Connection, ConnectionClose_1_0) {
MOCK_HTTP1_SERVER(server, connector, executor);
xzero::RefPtr<LocalEndPoint> ep;
executor.execute([&] {
ep = connector->createClient("GET / HTTP/1.0\r\n"
"\r\n");
});
Buffer output = ep->output();
ResponseParser resp;
resp.parse(output);
EXPECT_EQ(HttpVersion::VERSION_1_0, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::Ok, resp.responseInfo().status());
EXPECT_EQ("close", resp.responseInfo().getHeader("Connection"));
}
// sends one single request
TEST(http_http1_Connection, ConnectionKeepAlive_1_0) {
MOCK_HTTP1_SERVER(server, connector, executor);
xzero::RefPtr<LocalEndPoint> ep;
executor.execute([&] {
ep = connector->createClient("GET /hello HTTP/1.0\r\n"
"Connection: Keep-Alive\r\n"
"\r\n");
});
Buffer output = ep->output();
ResponseParser resp;
size_t n = resp.parse(output);
EXPECT_EQ(HttpVersion::VERSION_1_0, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::Ok, resp.responseInfo().status());
EXPECT_EQ("Keep-Alive", resp.responseInfo().getHeader("Connection"));
EXPECT_EQ("/hello\n", resp.responseBody().getBuffer());
}
// sends one single request
TEST(http_http1_Connection, ConnectionKeepAlive_1_1) {
MOCK_HTTP1_SERVER(server, connector, executor);
xzero::RefPtr<LocalEndPoint> ep;
executor.execute([&] {
ep = connector->createClient("GET /hello HTTP/1.1\r\n"
"Host: test\r\n"
"\r\n");
//printf("%s\n", ep->output().str().c_str());
});
Buffer output = ep->output();
ResponseParser resp;
size_t n = resp.parse(output);
EXPECT_EQ(HttpVersion::VERSION_1_1, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::Ok, resp.responseInfo().status());
EXPECT_EQ("Keep-Alive", resp.responseInfo().getHeader("Connection"));
EXPECT_EQ("/hello\n", resp.responseBody().getBuffer());
}
// sends single request, gets response, sends another one on the same line.
// TEST(http_http1_Connection, ConnectionKeepAlive2) { TODO
// }
// sends 3 requests pipelined all at once. receives responses in order
TEST(http_http1_Connection, ConnectionKeepAlive3_pipelined) {
//SCOPED_LOGGER();
MOCK_HTTP1_SERVER(server, connector, executor);
xzero::RefPtr<LocalEndPoint> ep;
executor.execute([&] {
ep = connector->createClient("GET /one HTTP/1.1\r\nHost: test\r\n\r\n"
"GET /two HTTP/1.1\r\nHost: test\r\n\r\n"
"GET /three HTTP/1.1\r\nHost: test\r\n\r\n");
});
Buffer output = ep->output();
ResponseParser resp;
size_t n = resp.parse(output);
EXPECT_EQ(HttpVersion::VERSION_1_1, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::Ok, resp.responseInfo().status());
EXPECT_EQ("Keep-Alive", resp.responseInfo().getHeader("Connection"));
EXPECT_EQ("/one\n", resp.responseBody().getBuffer());
n += resp.parse(output.ref(n));
EXPECT_EQ(HttpVersion::VERSION_1_1, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::Ok, resp.responseInfo().status());
EXPECT_EQ("Keep-Alive", resp.responseInfo().getHeader("Connection"));
EXPECT_EQ("/two\n", resp.responseBody().getBuffer());
n += resp.parse(output.ref(n));
EXPECT_EQ(HttpVersion::VERSION_1_1, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::Ok, resp.responseInfo().status());
EXPECT_EQ("Keep-Alive", resp.responseInfo().getHeader("Connection"));
EXPECT_EQ("/three\n", resp.responseBody().getBuffer());
// no garbage should have been generated at the end
ASSERT_EQ(n, output.size());
}
// ensure proper error code on bad request line
TEST(http_http1_Connection, protocolErrorShouldRaise400) {
// SCOPED_LOGGER();
MOCK_HTTP1_SERVER(server, connector, executor);
xzero::RefPtr<LocalEndPoint> ep;
executor.execute([&] {
// FIXME HTTP/1.1 (due to keep-alive) SEGV's on LocalEndPoint.
ep = connector->createClient("GET\r\n\r\n");
});
Buffer output = ep->output();
ResponseParser resp;
resp.parse(output);
EXPECT_EQ(HttpVersion::VERSION_0_9, resp.responseInfo().version());
EXPECT_EQ(HttpStatus::BadRequest, resp.responseInfo().status());
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "opendocumentsfilter.h"
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <utils/fileutils.h>
#include <QFileInfo>
using namespace Core;
using namespace Core;
using namespace Core::Internal;
using namespace Utils;
OpenDocumentsFilter::OpenDocumentsFilter()
{
setId("Open documents");
setDisplayName(tr("Open Documents"));
setShortcutString(QString(QLatin1Char('o')));
setIncludedByDefault(true);
connect(EditorManager::instance(), SIGNAL(editorOpened(Core::IEditor*)),
this, SLOT(refreshInternally()));
connect(EditorManager::instance(), SIGNAL(editorsClosed(QList<Core::IEditor*>)),
this, SLOT(refreshInternally()));
}
QList<LocatorFilterEntry> OpenDocumentsFilter::matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry_)
{
QList<LocatorFilterEntry> goodEntries;
QList<LocatorFilterEntry> betterEntries;
QString entry = entry_;
const QString lineNoSuffix = EditorManager::splitLineNumber(&entry);
const QChar asterisk = QLatin1Char('*');
QString pattern = QString(asterisk);
pattern += entry;
pattern += asterisk;
QRegExp regexp(pattern, Qt::CaseInsensitive, QRegExp::Wildcard);
if (!regexp.isValid())
return goodEntries;
const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(entry);
foreach (const DocumentModel::Entry &editorEntry, m_editors) {
if (future.isCanceled())
break;
QString fileName = editorEntry.fileName();
if (fileName.isEmpty())
continue;
QString displayName = editorEntry.displayName();
if (regexp.exactMatch(displayName)) {
QFileInfo fi(fileName);
LocatorFilterEntry fiEntry(this, fi.fileName(), QString(fileName + lineNoSuffix));
fiEntry.extraInfo = FileUtils::shortNativePath(FileName(fi));
fiEntry.fileName = fileName;
QList<LocatorFilterEntry> &category = displayName.startsWith(entry, caseSensitivityForPrefix)
? betterEntries : goodEntries;
category.append(fiEntry);
}
}
betterEntries.append(goodEntries);
return betterEntries;
}
void OpenDocumentsFilter::refreshInternally()
{
m_editors.clear();
foreach (DocumentModel::Entry *e, EditorManager::documentModel()->documents()) {
DocumentModel::Entry entry;
// create copy with only the information relevant to use
// to avoid model deleting entries behind our back
entry.m_displayName = e->displayName();
entry.m_fileName = e->fileName();
m_editors.append(entry);
}
}
void OpenDocumentsFilter::refresh(QFutureInterface<void> &future)
{
Q_UNUSED(future)
QMetaObject::invokeMethod(this, "refreshInternally", Qt::BlockingQueuedConnection);
}
void OpenDocumentsFilter::accept(LocatorFilterEntry selection) const
{
EditorManager::openEditor(selection.internalData.toString(), Id(),
EditorManager::CanContainLineNumber);
}
<commit_msg>Locator: Use display name for open documents entries<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "opendocumentsfilter.h"
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <utils/fileutils.h>
#include <QFileInfo>
using namespace Core;
using namespace Core;
using namespace Core::Internal;
using namespace Utils;
OpenDocumentsFilter::OpenDocumentsFilter()
{
setId("Open documents");
setDisplayName(tr("Open Documents"));
setShortcutString(QString(QLatin1Char('o')));
setIncludedByDefault(true);
connect(EditorManager::instance(), SIGNAL(editorOpened(Core::IEditor*)),
this, SLOT(refreshInternally()));
connect(EditorManager::instance(), SIGNAL(editorsClosed(QList<Core::IEditor*>)),
this, SLOT(refreshInternally()));
}
QList<LocatorFilterEntry> OpenDocumentsFilter::matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry_)
{
QList<LocatorFilterEntry> goodEntries;
QList<LocatorFilterEntry> betterEntries;
QString entry = entry_;
const QString lineNoSuffix = EditorManager::splitLineNumber(&entry);
const QChar asterisk = QLatin1Char('*');
QString pattern = QString(asterisk);
pattern += entry;
pattern += asterisk;
QRegExp regexp(pattern, Qt::CaseInsensitive, QRegExp::Wildcard);
if (!regexp.isValid())
return goodEntries;
const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(entry);
foreach (const DocumentModel::Entry &editorEntry, m_editors) {
if (future.isCanceled())
break;
QString fileName = editorEntry.fileName();
if (fileName.isEmpty())
continue;
QString displayName = editorEntry.displayName();
if (regexp.exactMatch(displayName)) {
QFileInfo fi(fileName);
LocatorFilterEntry fiEntry(this, displayName, QString(fileName + lineNoSuffix));
fiEntry.extraInfo = FileUtils::shortNativePath(FileName(fi));
fiEntry.fileName = fileName;
QList<LocatorFilterEntry> &category = displayName.startsWith(entry, caseSensitivityForPrefix)
? betterEntries : goodEntries;
category.append(fiEntry);
}
}
betterEntries.append(goodEntries);
return betterEntries;
}
void OpenDocumentsFilter::refreshInternally()
{
m_editors.clear();
foreach (DocumentModel::Entry *e, EditorManager::documentModel()->documents()) {
DocumentModel::Entry entry;
// create copy with only the information relevant to use
// to avoid model deleting entries behind our back
entry.m_displayName = e->displayName();
entry.m_fileName = e->fileName();
m_editors.append(entry);
}
}
void OpenDocumentsFilter::refresh(QFutureInterface<void> &future)
{
Q_UNUSED(future)
QMetaObject::invokeMethod(this, "refreshInternally", Qt::BlockingQueuedConnection);
}
void OpenDocumentsFilter::accept(LocatorFilterEntry selection) const
{
EditorManager::openEditor(selection.internalData.toString(), Id(),
EditorManager::CanContainLineNumber);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: uidl_tok.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:07:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef ADC_UIDL_TOK_HXX
#define ADC_UIDL_TOK_HXX
// USED SERVICES
// BASE CLASSES
#include <tokens/token2.hxx>
// COMPONENTS
// PARAMETERS
class ParserInfo;
namespace csi
{
namespace uidl
{
class TokenInterpreter;
class Token : public TextToken
{
public:
// LIFECYCLE
virtual ~Token() {}
// OPERATIONS
virtual void Trigger(
TokenInterpreter & io_rInterpreter ) const = 0;
};
} // namespace uidl
} // namespace csi
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.80); FILE MERGED 2008/03/28 16:03:00 rt 1.3.80.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: uidl_tok.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef ADC_UIDL_TOK_HXX
#define ADC_UIDL_TOK_HXX
// USED SERVICES
// BASE CLASSES
#include <tokens/token2.hxx>
// COMPONENTS
// PARAMETERS
class ParserInfo;
namespace csi
{
namespace uidl
{
class TokenInterpreter;
class Token : public TextToken
{
public:
// LIFECYCLE
virtual ~Token() {}
// OPERATIONS
virtual void Trigger(
TokenInterpreter & io_rInterpreter ) const = 0;
};
} // namespace uidl
} // namespace csi
#endif
<|endoftext|>
|
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 *
* (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/component/misc/InputEventReader.h>
#include <sofa/core/ObjectFactory.h>
#include <linux/input.h>
#include <poll.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
namespace sofa
{
namespace component
{
namespace misc
{
SOFA_DECL_CLASS(InputEventReader)
// Register in the Factory
int InputEventReaderClass = core::RegisterObject("Read events from file")
.add< InputEventReader >();
InputEventReader::InputEventReader()
: filename( initData(&filename, std::string("/dev/input/mouse2"), "filename", "input events file name"))
//, timeout( initData(&timeout, 0, "timeout", "time out to get an event from file" ))
, fd(-1)
, deplX(0), deplY(0)
{
}
void InputEventReader::init()
{
if((fd = open(filename.getValue().c_str(), O_RDONLY)) < 0)
std::cout << "ERROR: impossible to open the file: " << filename.getValue() << std::endl;
}
InputEventReader::~InputEventReader()
{
if (fd >= 0)
close(fd);
}
void InputEventReader::getInputEvents()
{
if (fd < 0) return;
pollfd pfd;
pfd.fd = fd;
pfd.events = POLLIN;
pfd.revents = 0;
while (poll(&pfd, 1, 0 /*timeout.getValue()*/)>0 && (pfd.revents & POLLIN))
{
input_event ev;
read(fd, &ev, sizeof(input_event));
// std::cout << "event type 0x" << std::hex << ev.type << std::dec << " code 0x" << std::hex << ev.code << std::dec << " value " << ev.value << std::endl;
if (ev.type == EV_REL)
{
switch (ev.code)
{
case REL_X: deplX += ev.value; break;
case REL_Y: deplY += ev.value; break;
}
}
}
}
void InputEventReader::handleEvent(core::objectmodel::Event *event)
{
if (dynamic_cast<sofa::simulation::AnimateBeginEvent *>(event))
{
getInputEvents();
if (deplX || deplY)
{
sofa::core::objectmodel::MouseEvent mouseEvent(sofa::core::objectmodel::MouseEvent::Move, deplX, deplY);
deplX = 0;
deplY = 0;
getContext()->propagateEvent(&mouseEvent);
}
}
}
} // namespace misc
} // namespace component
} // namespace sofa
<commit_msg>r3171/sofa-dev : Fix:compilation for windows & mac os x (inputeventreader is only compatible with linux)<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 *
* (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/component/misc/InputEventReader.h>
#include <sofa/core/ObjectFactory.h>
#include <poll.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef __linux__
#include <linux/input.h>
#endif
namespace sofa
{
namespace component
{
namespace misc
{
SOFA_DECL_CLASS(InputEventReader)
// Register in the Factory
int InputEventReaderClass = core::RegisterObject("Read events from file")
.add< InputEventReader >();
InputEventReader::InputEventReader()
: filename( initData(&filename, std::string("/dev/input/mouse2"), "filename", "input events file name"))
//, timeout( initData(&timeout, 0, "timeout", "time out to get an event from file" ))
, fd(-1)
, deplX(0), deplY(0)
{
}
void InputEventReader::init()
{
if((fd = open(filename.getValue().c_str(), O_RDONLY)) < 0)
std::cout << "ERROR: impossible to open the file: " << filename.getValue() << std::endl;
}
InputEventReader::~InputEventReader()
{
if (fd >= 0)
close(fd);
}
void InputEventReader::getInputEvents()
{
if (fd < 0) return;
pollfd pfd;
pfd.fd = fd;
pfd.events = POLLIN;
pfd.revents = 0;
#ifdef __linux__
while (poll(&pfd, 1, 0 /*timeout.getValue()*/)>0 && (pfd.revents & POLLIN))
{
input_event ev;
read(fd, &ev, sizeof(input_event));
// std::cout << "event type 0x" << std::hex << ev.type << std::dec << " code 0x" << std::hex << ev.code << std::dec << " value " << ev.value << std::endl;
if (ev.type == EV_REL)
{
switch (ev.code)
{
case REL_X: deplX += ev.value; break;
case REL_Y: deplY += ev.value; break;
}
}
}
#endif
}
void InputEventReader::handleEvent(core::objectmodel::Event *event)
{
if (dynamic_cast<sofa::simulation::AnimateBeginEvent *>(event))
{
getInputEvents();
if (deplX || deplY)
{
sofa::core::objectmodel::MouseEvent mouseEvent(sofa::core::objectmodel::MouseEvent::Move, deplX, deplY);
deplX = 0;
deplY = 0;
getContext()->propagateEvent(&mouseEvent);
}
}
}
} // namespace misc
} // namespace component
} // namespace sofa
<|endoftext|>
|
<commit_before>#ifndef PLUS_ONE_TO_NUMBER_AS_ARRAY_HPP
#define PLUS_ONE_TO_NUMBER_AS_ARRAY_HPP
// https://leetcode.com/problems/plus-one/description/
// Given a non-negative integer represented as a non-empty array of digits,
// plus one to the integer.
// You may assume the integer do not contain any leading zero, except the
// number 0 itself.
// The digits are stored such that the most significant digit is at the head
// of the list.
#include <vector>
namespace PlusOne {
class Solution {
public:
std::vector<int> plusOne(std::vector<int>& digits) {
if (digits.empty()) {
return std::vector<int>();
}
bool carry = false;
for (size_t i = digits.size() - 1; ; --i) {
if (digits[i] == 9) {
digits[i] = 0;
carry = true;
}
else {
digits[i] += 1;
carry = false;
break;
}
if (i == 0) {
break;
}
}
std::vector<int> result;
if (carry) {
result.push_back(1);
result.insert(result.end(), digits.begin(), digits.end());
}
else {
result = digits;
}
return result;
}
};
}
#endif // PLUS_ONE_TO_NUMBER_AS_ARRAY_HPP
<commit_msg>Simplify solution for algorithm: add one to number which is represented as array<commit_after>#ifndef PLUS_ONE_TO_NUMBER_AS_ARRAY_HPP
#define PLUS_ONE_TO_NUMBER_AS_ARRAY_HPP
// https://leetcode.com/problems/plus-one/description/
// Given a non-negative integer represented as a non-empty array of digits,
// plus one to the integer.
// You may assume the integer do not contain any leading zero, except the
// number 0 itself.
// The digits are stored such that the most significant digit is at the head
// of the list.
#include <vector>
namespace PlusOne {
class Solution {
public:
std::vector<int> plusOne(std::vector<int>& digits) {
if (digits.empty()) {
return std::vector<int>();
}
int carry = 1;
for (size_t i = digits.size() - 1; ; --i) {
if (digits[i] == 9) {
digits[i] = 0;
}
else {
digits[i] += carry--;
break;
}
if (i == 0) {
break;
}
}
if (carry > 0) {
digits.insert(digits.begin(), carry);
}
return digits;
}
};
}
#endif // PLUS_ONE_TO_NUMBER_AS_ARRAY_HPP
<|endoftext|>
|
<commit_before>/*=========================================================================
File: vtkReplayImageVideoSource.cxx
Author: Chris Wedlake <cwedlake@robarts.ca>
Language: C++
Description:
=========================================================================
Copyright (c) Chris Wedlake, cwedlake@robarts.ca
Use, modification and redistribution of the software, in source or
binary forms, are permitted provided that the following terms and
conditions are met:
1) Redistribution of the source code, in verbatim or modified
form, must retain the above copyright notice, this license,
the following disclaimer, and any notices that refer to this
license and/or the following disclaimer.
2) Redistribution in binary form must include the above copyright
notice, a copy of this license and the following disclaimer
in the documentation or with other materials provided with the
distribution.
3) Modified copies of the source code must be clearly marked as such,
and must not be misrepresented as verbatim copies of the source code.
THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS"
WITHOUT EXPRESSED OR IMPLIED WARRANTY INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. IN NO EVENT SHALL ANY COPYRIGHT HOLDER OR OTHER PARTY WHO MAY
MODIFY AND/OR REDISTRIBUTE THE SOFTWARE UNDER THE TERMS OF THIS LICENSE
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, LOSS OF DATA OR DATA BECOMING INACCURATE
OR LOSS OF PROFIT OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF
THE USE OR INABILITY TO USE THE SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
=========================================================================*/
#include "vtkReplayImageVideoSource.h"
#include "vtkTimerLog.h"
#include "vtkObjectFactory.h"
#include "vtkCriticalSection.h"
#include "vtkUnsignedCharArray.h"
#include "vtkMutexLock.h"
#include "vtkSmartPointer.h"
#include "vtkJPEGReader.h"
#include "vtkJPEGWriter.h"
#include "vtkPNGReader.h"
#include "vtkBMPReader.h"
#include "vtkTIFFReader.h"
#include "vtkImageData.h"
#include "vtkPointData.h"
#include "vtkImageFlip.h"
#include <string>
#include <algorithm>
// #include <windows.h>
// #include <tchar.h>
#include <stdio.h>
//#include <strsafe.h>
#include <vtkDirectory.h>
#include <vtkSortFileNames.h>
#include <vtkStringArray.h>
#include <vtkVersion.h> //for VTK_MAJOR_VERSION
//#pragma comment(lib, "User32.lib")
vtkReplayImageVideoSource* vtkReplayImageVideoSource::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkReplayImageVideoSource");
if(ret)
{
return (vtkReplayImageVideoSource*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkReplayImageVideoSource;
}
//----------------------------------------------------------------------------
vtkReplayImageVideoSource::vtkReplayImageVideoSource()
{
this->Initialized = 0;
this->pauseFeed = 0;
this->currentLength = 0;
this->vtkVideoSource::SetOutputFormat(VTK_RGB);
this->vtkVideoSource::SetFrameBufferSize( 54 );
this->vtkVideoSource::SetFrameRate( 15.0f );
this->SetFrameSize(1680,1048,1);
this->SetFrameSizeAutomatically = true;
this->imageIndex=-1;
}
//----------------------------------------------------------------------------
vtkReplayImageVideoSource::~vtkReplayImageVideoSource()
{
this->vtkReplayImageVideoSource::ReleaseSystemResources();
for (unsigned int i = 0; i < this->loadedData.size(); i++) {
this->loadedData[i]->Delete();
}
this->loadedData.clear();
}
//----------------------------------------------------------------------------
void vtkReplayImageVideoSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
//----------------------------------------------------------------------------
void vtkReplayImageVideoSource::Initialize()
{
if (this->Initialized)
{
return;
}
// Initialization worked
this->Initialized = 1;
// Update frame buffer to reflect any changes
this->UpdateFrameBuffer();
}
//----------------------------------------------------------------------------
void vtkReplayImageVideoSource::ReleaseSystemResources()
{
this->Initialized = 0;
}
void vtkReplayImageVideoSource::InternalGrab()
{
if (this->loadedData.size() == 0)
{
return;
}
// get a thread lock on the frame buffer
this->FrameBufferMutex->Lock();
if (this->AutoAdvance)
{
this->AdvanceFrameBuffer(1);
if (this->FrameIndex + 1 < this->FrameBufferSize)
{
this->FrameIndex++;
}
}
int index = this->FrameBufferIndex % this->FrameBufferSize;
while (index < 0)
{
index += this->FrameBufferSize;
}
this->imageIndex = ++this->imageIndex % this->loadedData.size();
void *buffer = this->loadedData[this->imageIndex]->GetScalarPointer();
unsigned char *ptr = reinterpret_cast<vtkUnsignedCharArray *>(this->FrameBuffer[index])->GetPointer(0);
//int ImageSize = (this->FrameBufferExtent[1]-this->FrameBufferExtent[0])*(this->FrameBufferExtent[3]-this->FrameBufferExtent[2]);
memcpy(ptr, buffer, this->NumberOfScalarComponents*(this->FrameSize[0]-1)*(this->FrameSize[1]-1));
this->FrameBufferTimeStamps[index] = vtkTimerLog::GetUniversalTime();
if (this->FrameCount++ == 0)
{
this->StartTimeStamp = this->FrameBufferTimeStamps[index];
}
this->Modified();
this->FrameBufferMutex->Unlock();
}
//----------------------------------------------------------------------------
// platform-independent sleep function
static inline void vtkSleep(double duration)
{
duration = duration; // avoid warnings
// sleep according to OS preference
#ifdef _WIN32
Sleep((int)(1000*duration));
#elif defined(__FreeBSD__) || defined(__linux__) || defined(sgi)
struct timespec sleep_time, dummy;
sleep_time.tv_sec = (int)duration;
sleep_time.tv_nsec = (int)(1000000000*(duration-sleep_time.tv_sec));
nanosleep(&sleep_time,&dummy);
#endif
}
//----------------------------------------------------------------------------
// Sleep until the specified absolute time has arrived.
// You must pass a handle to the current thread.
// If '0' is returned, then the thread was aborted before or during the wait.
static int vtkThreadSleep(vtkMultiThreader::ThreadInfo *data, double time)
{
// loop either until the time has arrived or until the thread is ended
for (int i = 0;; i++)
{
double remaining = time - vtkTimerLog::GetUniversalTime();
// check to see if we have reached the specified time
if (remaining <= 0)
{
if (i == 0)
{
vtkGenericWarningMacro("Dropped a video frame.");
}
return 1;
}
// check the ActiveFlag at least every 0.1 seconds
if (remaining > 0.1)
{
remaining = 0.1;
}
// check to see if we are being told to quit
data->ActiveFlagLock->Lock();
int activeFlag = *(data->ActiveFlag);
data->ActiveFlagLock->Unlock();
if (activeFlag == 0)
{
break;
}
vtkSleep(remaining);
}
return 0;
}
//----------------------------------------------------------------------------
// this function runs in an alternate thread to asyncronously grab frames
static void *vtkReplayImageVideoSourceRecordThread(vtkMultiThreader::ThreadInfo *data)
{
vtkReplayImageVideoSource *self = (vtkReplayImageVideoSource *)(data->UserData);
double startTime = vtkTimerLog::GetUniversalTime();
double rate = self->GetFrameRate();
int frame = 0;
do
{
self->InternalGrab();
frame++;
}
while (vtkThreadSleep(data, startTime + frame/rate));
return NULL;
}
//----------------------------------------------------------------------------
// Set the source to grab frames continuously.
// You should override this as appropriate for your device.
void vtkReplayImageVideoSource::Record()
{
// We don't actually record data.
return;
}
//----------------------------------------------------------------------------
// this function runs in an alternate thread to 'play the tape' at the
// specified frame rate.
static void *vtkReplayImageVideoSourcePlayThread(vtkMultiThreader::ThreadInfo *data)
{
vtkVideoSource *self = (vtkVideoSource *)(data->UserData);
double startTime = vtkTimerLog::GetUniversalTime();
double rate = self->GetFrameRate();
int frame = 0;
do
{
self->Seek(1);
frame++;
}
while (vtkThreadSleep(data, startTime + frame/rate));
return NULL;
}
//----------------------------------------------------------------------------
// Set the source to play back recorded frames.
// You should override this as appropriate for your device.
void vtkReplayImageVideoSource::Play()
{
if (this->Recording)
{
this->Stop();
}
if (!this->Playing)
{
this->Initialize();
this->Playing = 1;
this->Modified();
this->PlayerThreadId =
this->PlayerThreader->SpawnThread((vtkThreadFunctionType)\
&vtkReplayImageVideoSourcePlayThread,this);
}
}
//----------------------------------------------------------------------------
// Stop continuous grabbing or playback. You will have to override this
// if your class overrides Play() and Record()
void vtkReplayImageVideoSource::Stop()
{
if (this->Playing || this->Recording)
{
this->PlayerThreader->TerminateThread(this->PlayerThreadId);
this->PlayerThreadId = -1;
this->Playing = 0;
this->Recording = 0;
this->Modified();
}
}
void vtkReplayImageVideoSource::Pause() {
this->pauseFeed = 1;
}
void vtkReplayImageVideoSource::UnPause() {
this->pauseFeed = 0;
}
void vtkReplayImageVideoSource::Restart() {
this->imageIndex = -1;
}
void vtkReplayImageVideoSource::LoadFile(char * filename)
{
bool applyFlip = false;
std::string str(filename);
std::string ext = "";
for(unsigned int i=0; i<str.length(); i++)
{
if(str[i] == '.')
{
for(unsigned int j = i; j<str.length(); j++)
{
ext += str[j];
}
break;
}
}
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
vtkImageData * data = vtkImageData::New();
vtkSmartPointer<vtkImageReader2> reader;
if (ext == ".jpg")
{
reader = vtkSmartPointer<vtkJPEGReader>::New();
}
else if (ext == ".png")
{
reader = vtkSmartPointer<vtkPNGReader>::New();
}
else if (ext == ".bmp")
{
reader = vtkSmartPointer<vtkBMPReader>::New();
}
else if (ext == ".tif")
{
reader = vtkSmartPointer<vtkTIFFReader>::New();
applyFlip = true;
}
else
{
return;
}
if (reader->CanReadFile(filename))
{
reader->SetFileName(filename);
reader->Update();
reader->Modified();
#if (VTK_MAJOR_VERSION <= 5)
reader->GetOutput()->Update();
#else
reader->Update();
#endif
}
else
{
cerr << "Unable To Read File:" << filename << endl;
return;
}
int extents[6];
reader->GetOutput()->GetExtent(extents);
if (extents[1]-extents[0]+1 != this->FrameSize[0] ||
extents[3]-extents[2]+1 != this->FrameSize[1] ||
extents[5]-extents[4]+1 != this->FrameSize[2] )
{
if (this->SetFrameSizeAutomatically)
{
this->SetFrameSize(extents[1]-extents[0]+1, extents[3]-extents[2]+1,extents[5]-extents[4]+1);
this->SetFrameSizeAutomatically = false;
}
else
{
vtkErrorMacro("Unable to open file as size doesn't match video source");
return;
}
}
if (applyFlip == true)
{
vtkSmartPointer<vtkImageFlip> flip = vtkSmartPointer<vtkImageFlip>::New();
flip->SetInputConnection(reader->GetOutputPort());
flip->SetFilteredAxis(1);
flip->Modified();
flip->Update();
data->DeepCopy(flip->GetOutput());
}
else
{
data->DeepCopy(reader->GetOutput());
}
this->loadedData.push_back(data);
}
int vtkReplayImageVideoSource::LoadFolder(char * folder, char * filetype)
{
char* fullPath = new char[1024];
vtkSmartPointer<vtkDirectory> dir = vtkSmartPointer<vtkDirectory>::New();
fullPath = strncpy( fullPath, folder,1024);
fullPath = strncat( fullPath, "/",1024);
int hFind = dir->Open(fullPath);
if(hFind != 1){
return -1;
}
vtkSmartPointer<vtkSortFileNames> sort = vtkSmartPointer<vtkSortFileNames>::New();
sort->SetInputFileNames(dir->GetFiles());
sort->SkipDirectoriesOn();
sort->NumericSortOn();
for(int i = 0; i < sort->GetFileNames()->GetNumberOfValues(); i++){
char *file = new char[1024];
file = strncpy(file, fullPath,1024);
file = strncat(file, sort->GetFileNames()->GetValue(i),1024);
//std::cout << file << std::endl;
this->LoadFile(file);
}
return 0;
}
void vtkReplayImageVideoSource::Clear()
{
}
void vtkReplayImageVideoSource::SetClipRegion(int x0, int x1, int y0, int y1,
int z0, int z1)
{
vtkVideoSource::SetClipRegion(x0,x1,y0,y1,z0,z1);
//return;
}
<commit_msg>fix on RobartsVideo<commit_after>/*=========================================================================
File: vtkReplayImageVideoSource.cxx
Author: Chris Wedlake <cwedlake@robarts.ca>
Language: C++
Description:
=========================================================================
Copyright (c) Chris Wedlake, cwedlake@robarts.ca
Use, modification and redistribution of the software, in source or
binary forms, are permitted provided that the following terms and
conditions are met:
1) Redistribution of the source code, in verbatim or modified
form, must retain the above copyright notice, this license,
the following disclaimer, and any notices that refer to this
license and/or the following disclaimer.
2) Redistribution in binary form must include the above copyright
notice, a copy of this license and the following disclaimer
in the documentation or with other materials provided with the
distribution.
3) Modified copies of the source code must be clearly marked as such,
and must not be misrepresented as verbatim copies of the source code.
THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS"
WITHOUT EXPRESSED OR IMPLIED WARRANTY INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. IN NO EVENT SHALL ANY COPYRIGHT HOLDER OR OTHER PARTY WHO MAY
MODIFY AND/OR REDISTRIBUTE THE SOFTWARE UNDER THE TERMS OF THIS LICENSE
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, LOSS OF DATA OR DATA BECOMING INACCURATE
OR LOSS OF PROFIT OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF
THE USE OR INABILITY TO USE THE SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
=========================================================================*/
#include "vtkReplayImageVideoSource.h"
#include "vtkTimerLog.h"
#include "vtkObjectFactory.h"
#include "vtkCriticalSection.h"
#include "vtkUnsignedCharArray.h"
#include "vtkMutexLock.h"
#include "vtkSmartPointer.h"
#include "vtkJPEGReader.h"
#include "vtkJPEGWriter.h"
#include "vtkPNGReader.h"
#include "vtkBMPReader.h"
#include "vtkTIFFReader.h"
#include "vtkImageData.h"
#include "vtkPointData.h"
#include "vtkImageFlip.h"
#include <string>
#include <algorithm>
// #include <windows.h>
// #include <tchar.h>
#include <stdio.h>
//#include <strsafe.h>
#include <vtkDirectory.h>
#include <vtkSortFileNames.h>
#include <vtkStringArray.h>
#include <vtkVersion.h> //for VTK_MAJOR_VERSION
//#pragma comment(lib, "User32.lib")
vtkReplayImageVideoSource* vtkReplayImageVideoSource::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkReplayImageVideoSource");
if(ret)
{
return (vtkReplayImageVideoSource*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkReplayImageVideoSource;
}
//----------------------------------------------------------------------------
vtkReplayImageVideoSource::vtkReplayImageVideoSource()
{
this->Initialized = 0;
this->pauseFeed = 0;
this->currentLength = 0;
this->vtkVideoSource::SetOutputFormat(VTK_RGB);
this->vtkVideoSource::SetFrameBufferSize( 54 );
this->vtkVideoSource::SetFrameRate( 15.0f );
this->SetFrameSize(1680,1048,1);
this->SetFrameSizeAutomatically = true;
this->imageIndex=-1;
}
//----------------------------------------------------------------------------
vtkReplayImageVideoSource::~vtkReplayImageVideoSource()
{
this->vtkReplayImageVideoSource::ReleaseSystemResources();
for (unsigned int i = 0; i < this->loadedData.size(); i++) {
this->loadedData[i]->Delete();
}
this->loadedData.clear();
}
//----------------------------------------------------------------------------
void vtkReplayImageVideoSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
//----------------------------------------------------------------------------
void vtkReplayImageVideoSource::Initialize()
{
if (this->Initialized)
{
return;
}
// Initialization worked
this->Initialized = 1;
// Update frame buffer to reflect any changes
this->UpdateFrameBuffer();
}
//----------------------------------------------------------------------------
void vtkReplayImageVideoSource::ReleaseSystemResources()
{
this->Initialized = 0;
}
void vtkReplayImageVideoSource::InternalGrab()
{
if (this->loadedData.size() == 0)
{
return;
}
// get a thread lock on the frame buffer
this->FrameBufferMutex->Lock();
if (this->AutoAdvance)
{
this->AdvanceFrameBuffer(1);
if (this->FrameIndex + 1 < this->FrameBufferSize)
{
this->FrameIndex++;
}
}
int index = this->FrameBufferIndex % this->FrameBufferSize;
while (index < 0)
{
index += this->FrameBufferSize;
}
this->imageIndex = ++this->imageIndex % this->loadedData.size();
void *buffer = this->loadedData[this->imageIndex]->GetScalarPointer();
unsigned char *ptr = reinterpret_cast<vtkUnsignedCharArray *>(this->FrameBuffer[index])->GetPointer(0);
//int ImageSize = (this->FrameBufferExtent[1]-this->FrameBufferExtent[0])*(this->FrameBufferExtent[3]-this->FrameBufferExtent[2]);
memcpy(ptr, buffer, this->NumberOfScalarComponents*(this->FrameSize[0]-1)*(this->FrameSize[1]-1));
this->FrameBufferTimeStamps[index] = vtkTimerLog::GetUniversalTime();
if (this->FrameCount++ == 0)
{
this->StartTimeStamp = this->FrameBufferTimeStamps[index];
}
this->Modified();
this->FrameBufferMutex->Unlock();
}
//----------------------------------------------------------------------------
// platform-independent sleep function
static inline void vtkSleep(double duration)
{
duration = duration; // avoid warnings
// sleep according to OS preference
#ifdef _WIN32
Sleep((int)(1000*duration));
#elif defined(__FreeBSD__) || defined(__linux__) || defined(sgi)
struct timespec sleep_time, dummy;
sleep_time.tv_sec = (int)duration;
sleep_time.tv_nsec = (int)(1000000000*(duration-sleep_time.tv_sec));
nanosleep(&sleep_time,&dummy);
#endif
}
//----------------------------------------------------------------------------
// Sleep until the specified absolute time has arrived.
// You must pass a handle to the current thread.
// If '0' is returned, then the thread was aborted before or during the wait.
static int vtkThreadSleep(vtkMultiThreader::ThreadInfo *data, double time)
{
// loop either until the time has arrived or until the thread is ended
for (int i = 0;; i++)
{
double remaining = time - vtkTimerLog::GetUniversalTime();
// check to see if we have reached the specified time
if (remaining <= 0)
{
if (i == 0)
{
vtkGenericWarningMacro("Dropped a video frame.");
}
return 1;
}
// check the ActiveFlag at least every 0.1 seconds
if (remaining > 0.1)
{
remaining = 0.1;
}
// check to see if we are being told to quit
data->ActiveFlagLock->Lock();
int activeFlag = *(data->ActiveFlag);
data->ActiveFlagLock->Unlock();
if (activeFlag == 0)
{
break;
}
vtkSleep(remaining);
}
return 0;
}
//----------------------------------------------------------------------------
// this function runs in an alternate thread to asyncronously grab frames
static void *vtkReplayImageVideoSourceRecordThread(vtkMultiThreader::ThreadInfo *data)
{
vtkReplayImageVideoSource *self = (vtkReplayImageVideoSource *)(data->UserData);
double startTime = vtkTimerLog::GetUniversalTime();
double rate = self->GetFrameRate();
int frame = 0;
do
{
self->InternalGrab();
frame++;
}
while (vtkThreadSleep(data, startTime + frame/rate));
return NULL;
}
//----------------------------------------------------------------------------
// Set the source to grab frames continuously.
// You should override this as appropriate for your device.
void vtkReplayImageVideoSource::Record()
{
// We don't actually record data.
return;
}
//----------------------------------------------------------------------------
// this function runs in an alternate thread to 'play the tape' at the
// specified frame rate.
static void *vtkReplayImageVideoSourcePlayThread(vtkMultiThreader::ThreadInfo *data)
{
vtkVideoSource *self = (vtkVideoSource *)(data->UserData);
double startTime = vtkTimerLog::GetUniversalTime();
double rate = self->GetFrameRate();
int frame = 0;
do
{
self->Seek(1);
frame++;
}
while (vtkThreadSleep(data, startTime + frame/rate));
return NULL;
}
//----------------------------------------------------------------------------
// Set the source to play back recorded frames.
// You should override this as appropriate for your device.
void vtkReplayImageVideoSource::Play()
{
if (this->Recording)
{
this->Stop();
}
if (!this->Playing)
{
this->Initialize();
this->Playing = 1;
this->Modified();
this->PlayerThreadId =
this->PlayerThreader->SpawnThread((vtkThreadFunctionType)\
&vtkReplayImageVideoSourcePlayThread,this);
}
}
//----------------------------------------------------------------------------
// Stop continuous grabbing or playback. You will have to override this
// if your class overrides Play() and Record()
void vtkReplayImageVideoSource::Stop()
{
if (this->Playing || this->Recording)
{
this->PlayerThreader->TerminateThread(this->PlayerThreadId);
this->PlayerThreadId = -1;
this->Playing = 0;
this->Recording = 0;
this->Modified();
}
}
void vtkReplayImageVideoSource::Pause() {
this->pauseFeed = 1;
}
void vtkReplayImageVideoSource::UnPause() {
this->pauseFeed = 0;
}
void vtkReplayImageVideoSource::Restart() {
this->imageIndex = -1;
}
void vtkReplayImageVideoSource::LoadFile(char * filename)
{
bool applyFlip = false;
std::string str(filename);
std::string ext = "";
for(unsigned int i=0; i<str.length(); i++)
{
if(str[i] == '.')
{
for(unsigned int j = i; j<str.length(); j++)
{
ext += str[j];
}
break;
}
}
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
vtkImageData * data = vtkImageData::New();
vtkSmartPointer<vtkImageReader2> reader;
if (ext == ".jpg")
{
reader = vtkSmartPointer<vtkJPEGReader>::New();
}
else if (ext == ".png")
{
reader = vtkSmartPointer<vtkPNGReader>::New();
}
else if (ext == ".bmp")
{
reader = vtkSmartPointer<vtkBMPReader>::New();
}
else if (ext == ".tif")
{
reader = vtkSmartPointer<vtkTIFFReader>::New();
applyFlip = true;
}
else
{
return;
}
if (reader->CanReadFile(filename))
{
reader->SetFileName(filename);
reader->Update();
reader->Modified();
#if (VTK_MAJOR_VERSION <= 5)
reader->GetOutput()->Update();
#endif
}
else
{
cerr << "Unable To Read File:" << filename << endl;
return;
}
int extents[6];
reader->GetOutput()->GetExtent(extents);
if (extents[1]-extents[0]+1 != this->FrameSize[0] ||
extents[3]-extents[2]+1 != this->FrameSize[1] ||
extents[5]-extents[4]+1 != this->FrameSize[2] )
{
if (this->SetFrameSizeAutomatically)
{
this->SetFrameSize(extents[1]-extents[0]+1, extents[3]-extents[2]+1,extents[5]-extents[4]+1);
this->SetFrameSizeAutomatically = false;
}
else
{
vtkErrorMacro("Unable to open file as size doesn't match video source");
return;
}
}
if (applyFlip == true)
{
vtkSmartPointer<vtkImageFlip> flip = vtkSmartPointer<vtkImageFlip>::New();
flip->SetInputConnection(reader->GetOutputPort());
flip->SetFilteredAxis(1);
flip->Modified();
flip->Update();
data->DeepCopy(flip->GetOutput());
}
else
{
data->DeepCopy(reader->GetOutput());
}
this->loadedData.push_back(data);
}
int vtkReplayImageVideoSource::LoadFolder(char * folder, char * filetype)
{
char* fullPath = new char[1024];
vtkSmartPointer<vtkDirectory> dir = vtkSmartPointer<vtkDirectory>::New();
fullPath = strncpy( fullPath, folder,1024);
fullPath = strncat( fullPath, "/",1024);
int hFind = dir->Open(fullPath);
if(hFind != 1){
return -1;
}
vtkSmartPointer<vtkSortFileNames> sort = vtkSmartPointer<vtkSortFileNames>::New();
sort->SetInputFileNames(dir->GetFiles());
sort->SkipDirectoriesOn();
sort->NumericSortOn();
for(int i = 0; i < sort->GetFileNames()->GetNumberOfValues(); i++){
char *file = new char[1024];
file = strncpy(file, fullPath,1024);
file = strncat(file, sort->GetFileNames()->GetValue(i),1024);
//std::cout << file << std::endl;
this->LoadFile(file);
}
return 0;
}
void vtkReplayImageVideoSource::Clear()
{
}
void vtkReplayImageVideoSource::SetClipRegion(int x0, int x1, int y0, int y1,
int z0, int z1)
{
vtkVideoSource::SetClipRegion(x0,x1,y0,y1,z0,z1);
//return;
}
<|endoftext|>
|
<commit_before><commit_msg>const_cast: convert some C-style casts and remove some redundant ones<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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 <graphene/chain/protocol/asset.hpp>
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
namespace graphene { namespace chain {
typedef boost::multiprecision::uint128_t uint128_t;
typedef boost::multiprecision::int128_t int128_t;
bool operator == ( const price& a, const price& b )
{
if( std::tie( a.base.asset_id, a.quote.asset_id ) != std::tie( b.base.asset_id, b.quote.asset_id ) )
return false;
const auto amult = uint128_t( b.quote.amount.value ) * a.base.amount.value;
const auto bmult = uint128_t( a.quote.amount.value ) * b.base.amount.value;
return amult == bmult;
}
bool operator < ( const price& a, const price& b )
{
if( a.base.asset_id < b.base.asset_id ) return true;
if( a.base.asset_id > b.base.asset_id ) return false;
if( a.quote.asset_id < b.quote.asset_id ) return true;
if( a.quote.asset_id > b.quote.asset_id ) return false;
const auto amult = uint128_t( b.quote.amount.value ) * a.base.amount.value;
const auto bmult = uint128_t( a.quote.amount.value ) * b.base.amount.value;
return amult < bmult;
}
asset operator * ( const asset& a, const price& b )
{
if( a.asset_id == b.base.asset_id )
{
FC_ASSERT( b.base.amount.value > 0 );
uint128_t result = (uint128_t(a.amount.value) * b.quote.amount.value)/b.base.amount.value;
FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );
return asset( result.convert_to<int64_t>(), b.quote.asset_id );
}
else if( a.asset_id == b.quote.asset_id )
{
FC_ASSERT( b.quote.amount.value > 0 );
uint128_t result = (uint128_t(a.amount.value) * b.base.amount.value)/b.quote.amount.value;
FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );
return asset( result.convert_to<int64_t>(), b.base.asset_id );
}
FC_THROW_EXCEPTION( fc::assert_exception, "invalid asset * price", ("asset",a)("price",b) );
}
asset asset::multiply_and_round_up( const price& b )const
{
const asset& a = *this;
if( a.asset_id == b.base.asset_id )
{
FC_ASSERT( b.base.amount.value > 0 );
uint128_t result = (uint128_t(a.amount.value) * b.quote.amount.value + b.base.amount.value - 1)/b.base.amount.value;
FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );
return asset( result.convert_to<int64_t>(), b.quote.asset_id );
}
else if( a.asset_id == b.quote.asset_id )
{
FC_ASSERT( b.quote.amount.value > 0 );
uint128_t result = (uint128_t(a.amount.value) * b.base.amount.value + b.quote.amount.value - 1)/b.quote.amount.value;
FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );
return asset( result.convert_to<int64_t>(), b.base.asset_id );
}
FC_THROW_EXCEPTION( fc::assert_exception, "invalid asset::multiply_and_round_up(price)", ("asset",a)("price",b) );
}
price operator / ( const asset& base, const asset& quote )
{ try {
FC_ASSERT( base.asset_id != quote.asset_id );
return price{base,quote};
} FC_CAPTURE_AND_RETHROW( (base)(quote) ) }
price price::max( asset_id_type base, asset_id_type quote ) { return asset( share_type(GRAPHENE_MAX_SHARE_SUPPLY), base ) / asset( share_type(1), quote); }
price price::min( asset_id_type base, asset_id_type quote ) { return asset( 1, base ) / asset( GRAPHENE_MAX_SHARE_SUPPLY, quote); }
price operator * ( const price& p, const ratio_type& r )
{ try {
p.validate();
FC_ASSERT( r.numerator() > 0 && r.denominator() > 0 );
if( r.numerator() == r.denominator() ) return p;
boost::rational<int128_t> p128( p.base.amount.value, p.quote.amount.value );
boost::rational<int128_t> r128( r.numerator(), r.denominator() );
auto cp = p128 * r128;
auto ocp = cp;
bool shrinked = false;
bool using_max = false;
static const int128_t max( GRAPHENE_MAX_SHARE_SUPPLY );
while( cp.numerator() > max || cp.denominator() > max )
{
if( cp.numerator() == 1 )
{
cp = boost::rational<int128_t>( 1, max );
using_max = true;
break;
}
else if( cp.denominator() == 1 )
{
cp = boost::rational<int128_t>( max, 1 );
using_max = true;
break;
}
else
{
cp = boost::rational<int128_t>( cp.numerator() >> 1, cp.denominator() >> 1 );
shrinked = true;
}
}
if( shrinked ) // maybe not accurate enough due to rounding, do additional checks here
{
int128_t num = ocp.numerator();
int128_t den = ocp.denominator();
if( num > den )
{
num /= den;
if( num > max )
num = max;
den = 1;
}
else
{
den /= num;
if( den > max )
den = max;
num = 1;
}
boost::rational<int128_t> ncp( num, den );
if( num == max || den == max ) // it's on the edge, we know it's accurate enough
cp = ncp;
else
{
// from the accurate ocp, now we have ncp and cp. use the one which is closer to ocp.
// TODO improve performance
auto diff1 = abs( ncp - ocp );
auto diff2 = abs( cp - ocp );
if( diff1 < diff2 ) cp = ncp;
}
}
price np = asset( cp.numerator().convert_to<int64_t>(), p.base.asset_id )
/ asset( cp.denominator().convert_to<int64_t>(), p.quote.asset_id );
if( shrinked || using_max )
{
if( ( r.numerator() > r.denominator() && np < p )
|| ( r.numerator() < r.denominator() && np > p ) )
// even with an accurate result, if p is out of valid range, return it
np = p;
}
np.validate();
return np;
} FC_CAPTURE_AND_RETHROW( (p)(r.numerator())(r.denominator()) ) }
price operator / ( const price& p, const ratio_type& r )
{ try {
return p * ratio_type( r.denominator(), r.numerator() );
} FC_CAPTURE_AND_RETHROW( (p)(r.numerator())(r.denominator()) ) }
/**
* The black swan price is defined as debt/collateral, we want to perform a margin call
* before debt == collateral. Given a debt/collateral ratio of 1 USD / CORE and
* a maintenance collateral requirement of 2x we can define the call price to be
* 2 USD / CORE.
*
* This method divides the collateral by the maintenance collateral ratio to derive
* a call price for the given black swan ratio.
*
* There exists some cases where the debt and collateral values are so small that
* dividing by the collateral ratio will result in a 0 price or really poor
* rounding errors. No matter what the collateral part of the price ratio can
* never go to 0 and the debt can never go more than GRAPHENE_MAX_SHARE_SUPPLY
*
* CR * DEBT/COLLAT or DEBT/(COLLAT/CR)
*/
price price::call_price( const asset& debt, const asset& collateral, uint16_t collateral_ratio)
{ try {
// TODO replace the calculation with new operator*() and/or operator/(), could be a hardfork change due to edge cases
boost::rational<int128_t> swan(debt.amount.value,collateral.amount.value);
boost::rational<int128_t> ratio( collateral_ratio, GRAPHENE_COLLATERAL_RATIO_DENOM );
auto cp = swan * ratio;
while( cp.numerator() > GRAPHENE_MAX_SHARE_SUPPLY || cp.denominator() > GRAPHENE_MAX_SHARE_SUPPLY )
cp = boost::rational<int128_t>( (cp.numerator() >> 1)+1, (cp.denominator() >> 1)+1 );
return ( asset( cp.denominator().convert_to<int64_t>(), collateral.asset_id )
/ asset( cp.numerator().convert_to<int64_t>(), debt.asset_id ) );
} FC_CAPTURE_AND_RETHROW( (debt)(collateral)(collateral_ratio) ) }
bool price::is_null() const
{
// Effectively same as "return *this == price();" but perhaps faster
return ( base.asset_id == asset_id_type() && quote.asset_id == asset_id_type() );
}
void price::validate() const
{ try {
FC_ASSERT( base.amount > share_type(0) );
FC_ASSERT( quote.amount > share_type(0) );
FC_ASSERT( base.asset_id != quote.asset_id );
} FC_CAPTURE_AND_RETHROW( (base)(quote) ) }
void price_feed::validate() const
{ try {
if( !settlement_price.is_null() )
settlement_price.validate();
FC_ASSERT( maximum_short_squeeze_ratio >= GRAPHENE_MIN_COLLATERAL_RATIO );
FC_ASSERT( maximum_short_squeeze_ratio <= GRAPHENE_MAX_COLLATERAL_RATIO );
FC_ASSERT( maintenance_collateral_ratio >= GRAPHENE_MIN_COLLATERAL_RATIO );
FC_ASSERT( maintenance_collateral_ratio <= GRAPHENE_MAX_COLLATERAL_RATIO );
// Note: there was code here calling `max_short_squeeze_price();` before core-1270 hard fork,
// in order to make sure that it doesn't overflow,
// but the code doesn't actually check overflow, and it won't overflow, so the code is removed.
// Note: not checking `maintenance_collateral_ratio >= maximum_short_squeeze_ratio` since launch
} FC_CAPTURE_AND_RETHROW( (*this) ) }
bool price_feed::is_for( asset_id_type asset_id ) const
{
try
{
if( !settlement_price.is_null() )
return (settlement_price.base.asset_id == asset_id);
if( !core_exchange_rate.is_null() )
return (core_exchange_rate.base.asset_id == asset_id);
// (null, null) is valid for any feed
return true;
}
FC_CAPTURE_AND_RETHROW( (*this) )
}
// This function is kept here due to potential different behavior in edge cases.
// TODO check after core-1270 hard fork to see if we can safely remove it
price price_feed::max_short_squeeze_price_before_hf_1270()const
{
// settlement price is in debt/collateral
boost::rational<int128_t> sp( settlement_price.base.amount.value, settlement_price.quote.amount.value );
boost::rational<int128_t> ratio( GRAPHENE_COLLATERAL_RATIO_DENOM, maximum_short_squeeze_ratio );
auto cp = sp * ratio;
while( cp.numerator() > GRAPHENE_MAX_SHARE_SUPPLY || cp.denominator() > GRAPHENE_MAX_SHARE_SUPPLY )
cp = boost::rational<int128_t>( (cp.numerator() >> 1)+(cp.numerator()&1),
(cp.denominator() >> 1)+(cp.denominator()&1) );
return ( asset( cp.numerator().convert_to<int64_t>(), settlement_price.base.asset_id )
/ asset( cp.denominator().convert_to<int64_t>(), settlement_price.quote.asset_id ) );
}
price price_feed::max_short_squeeze_price()const
{
// settlement price is in debt/collateral
return settlement_price * ratio_type( GRAPHENE_COLLATERAL_RATIO_DENOM, maximum_short_squeeze_ratio );
}
price price_feed::maintenance_collateralization()const
{
if( settlement_price.is_null() )
return price();
return ~settlement_price * ratio_type( maintenance_collateral_ratio, GRAPHENE_COLLATERAL_RATIO_DENOM );
}
// compile-time table of powers of 10 using template metaprogramming
template< int N >
struct p10
{
static const int64_t v = 10 * p10<N-1>::v;
};
template<>
struct p10<0>
{
static const int64_t v = 1;
};
const int64_t scaled_precision_lut[19] =
{
p10< 0 >::v, p10< 1 >::v, p10< 2 >::v, p10< 3 >::v,
p10< 4 >::v, p10< 5 >::v, p10< 6 >::v, p10< 7 >::v,
p10< 8 >::v, p10< 9 >::v, p10< 10 >::v, p10< 11 >::v,
p10< 12 >::v, p10< 13 >::v, p10< 14 >::v, p10< 15 >::v,
p10< 16 >::v, p10< 17 >::v, p10< 18 >::v
};
} } // graphene::chain
<commit_msg>Updated comment in price::call_price()<commit_after>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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 <graphene/chain/protocol/asset.hpp>
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
namespace graphene { namespace chain {
typedef boost::multiprecision::uint128_t uint128_t;
typedef boost::multiprecision::int128_t int128_t;
bool operator == ( const price& a, const price& b )
{
if( std::tie( a.base.asset_id, a.quote.asset_id ) != std::tie( b.base.asset_id, b.quote.asset_id ) )
return false;
const auto amult = uint128_t( b.quote.amount.value ) * a.base.amount.value;
const auto bmult = uint128_t( a.quote.amount.value ) * b.base.amount.value;
return amult == bmult;
}
bool operator < ( const price& a, const price& b )
{
if( a.base.asset_id < b.base.asset_id ) return true;
if( a.base.asset_id > b.base.asset_id ) return false;
if( a.quote.asset_id < b.quote.asset_id ) return true;
if( a.quote.asset_id > b.quote.asset_id ) return false;
const auto amult = uint128_t( b.quote.amount.value ) * a.base.amount.value;
const auto bmult = uint128_t( a.quote.amount.value ) * b.base.amount.value;
return amult < bmult;
}
asset operator * ( const asset& a, const price& b )
{
if( a.asset_id == b.base.asset_id )
{
FC_ASSERT( b.base.amount.value > 0 );
uint128_t result = (uint128_t(a.amount.value) * b.quote.amount.value)/b.base.amount.value;
FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );
return asset( result.convert_to<int64_t>(), b.quote.asset_id );
}
else if( a.asset_id == b.quote.asset_id )
{
FC_ASSERT( b.quote.amount.value > 0 );
uint128_t result = (uint128_t(a.amount.value) * b.base.amount.value)/b.quote.amount.value;
FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );
return asset( result.convert_to<int64_t>(), b.base.asset_id );
}
FC_THROW_EXCEPTION( fc::assert_exception, "invalid asset * price", ("asset",a)("price",b) );
}
asset asset::multiply_and_round_up( const price& b )const
{
const asset& a = *this;
if( a.asset_id == b.base.asset_id )
{
FC_ASSERT( b.base.amount.value > 0 );
uint128_t result = (uint128_t(a.amount.value) * b.quote.amount.value + b.base.amount.value - 1)/b.base.amount.value;
FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );
return asset( result.convert_to<int64_t>(), b.quote.asset_id );
}
else if( a.asset_id == b.quote.asset_id )
{
FC_ASSERT( b.quote.amount.value > 0 );
uint128_t result = (uint128_t(a.amount.value) * b.base.amount.value + b.quote.amount.value - 1)/b.quote.amount.value;
FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );
return asset( result.convert_to<int64_t>(), b.base.asset_id );
}
FC_THROW_EXCEPTION( fc::assert_exception, "invalid asset::multiply_and_round_up(price)", ("asset",a)("price",b) );
}
price operator / ( const asset& base, const asset& quote )
{ try {
FC_ASSERT( base.asset_id != quote.asset_id );
return price{base,quote};
} FC_CAPTURE_AND_RETHROW( (base)(quote) ) }
price price::max( asset_id_type base, asset_id_type quote ) { return asset( share_type(GRAPHENE_MAX_SHARE_SUPPLY), base ) / asset( share_type(1), quote); }
price price::min( asset_id_type base, asset_id_type quote ) { return asset( 1, base ) / asset( GRAPHENE_MAX_SHARE_SUPPLY, quote); }
price operator * ( const price& p, const ratio_type& r )
{ try {
p.validate();
FC_ASSERT( r.numerator() > 0 && r.denominator() > 0 );
if( r.numerator() == r.denominator() ) return p;
boost::rational<int128_t> p128( p.base.amount.value, p.quote.amount.value );
boost::rational<int128_t> r128( r.numerator(), r.denominator() );
auto cp = p128 * r128;
auto ocp = cp;
bool shrinked = false;
bool using_max = false;
static const int128_t max( GRAPHENE_MAX_SHARE_SUPPLY );
while( cp.numerator() > max || cp.denominator() > max )
{
if( cp.numerator() == 1 )
{
cp = boost::rational<int128_t>( 1, max );
using_max = true;
break;
}
else if( cp.denominator() == 1 )
{
cp = boost::rational<int128_t>( max, 1 );
using_max = true;
break;
}
else
{
cp = boost::rational<int128_t>( cp.numerator() >> 1, cp.denominator() >> 1 );
shrinked = true;
}
}
if( shrinked ) // maybe not accurate enough due to rounding, do additional checks here
{
int128_t num = ocp.numerator();
int128_t den = ocp.denominator();
if( num > den )
{
num /= den;
if( num > max )
num = max;
den = 1;
}
else
{
den /= num;
if( den > max )
den = max;
num = 1;
}
boost::rational<int128_t> ncp( num, den );
if( num == max || den == max ) // it's on the edge, we know it's accurate enough
cp = ncp;
else
{
// from the accurate ocp, now we have ncp and cp. use the one which is closer to ocp.
// TODO improve performance
auto diff1 = abs( ncp - ocp );
auto diff2 = abs( cp - ocp );
if( diff1 < diff2 ) cp = ncp;
}
}
price np = asset( cp.numerator().convert_to<int64_t>(), p.base.asset_id )
/ asset( cp.denominator().convert_to<int64_t>(), p.quote.asset_id );
if( shrinked || using_max )
{
if( ( r.numerator() > r.denominator() && np < p )
|| ( r.numerator() < r.denominator() && np > p ) )
// even with an accurate result, if p is out of valid range, return it
np = p;
}
np.validate();
return np;
} FC_CAPTURE_AND_RETHROW( (p)(r.numerator())(r.denominator()) ) }
price operator / ( const price& p, const ratio_type& r )
{ try {
return p * ratio_type( r.denominator(), r.numerator() );
} FC_CAPTURE_AND_RETHROW( (p)(r.numerator())(r.denominator()) ) }
/**
* The black swan price is defined as debt/collateral, we want to perform a margin call
* before debt == collateral. Given a debt/collateral ratio of 1 USD / CORE and
* a maintenance collateral requirement of 2x we can define the call price to be
* 2 USD / CORE.
*
* This method divides the collateral by the maintenance collateral ratio to derive
* a call price for the given black swan ratio.
*
* There exists some cases where the debt and collateral values are so small that
* dividing by the collateral ratio will result in a 0 price or really poor
* rounding errors. No matter what the collateral part of the price ratio can
* never go to 0 and the debt can never go more than GRAPHENE_MAX_SHARE_SUPPLY
*
* CR * DEBT/COLLAT or DEBT/(COLLAT/CR)
*
* Note: this function is only used before core-1270 hard fork.
*/
price price::call_price( const asset& debt, const asset& collateral, uint16_t collateral_ratio)
{ try {
boost::rational<int128_t> swan(debt.amount.value,collateral.amount.value);
boost::rational<int128_t> ratio( collateral_ratio, GRAPHENE_COLLATERAL_RATIO_DENOM );
auto cp = swan * ratio;
while( cp.numerator() > GRAPHENE_MAX_SHARE_SUPPLY || cp.denominator() > GRAPHENE_MAX_SHARE_SUPPLY )
cp = boost::rational<int128_t>( (cp.numerator() >> 1)+1, (cp.denominator() >> 1)+1 );
return ( asset( cp.denominator().convert_to<int64_t>(), collateral.asset_id )
/ asset( cp.numerator().convert_to<int64_t>(), debt.asset_id ) );
} FC_CAPTURE_AND_RETHROW( (debt)(collateral)(collateral_ratio) ) }
bool price::is_null() const
{
// Effectively same as "return *this == price();" but perhaps faster
return ( base.asset_id == asset_id_type() && quote.asset_id == asset_id_type() );
}
void price::validate() const
{ try {
FC_ASSERT( base.amount > share_type(0) );
FC_ASSERT( quote.amount > share_type(0) );
FC_ASSERT( base.asset_id != quote.asset_id );
} FC_CAPTURE_AND_RETHROW( (base)(quote) ) }
void price_feed::validate() const
{ try {
if( !settlement_price.is_null() )
settlement_price.validate();
FC_ASSERT( maximum_short_squeeze_ratio >= GRAPHENE_MIN_COLLATERAL_RATIO );
FC_ASSERT( maximum_short_squeeze_ratio <= GRAPHENE_MAX_COLLATERAL_RATIO );
FC_ASSERT( maintenance_collateral_ratio >= GRAPHENE_MIN_COLLATERAL_RATIO );
FC_ASSERT( maintenance_collateral_ratio <= GRAPHENE_MAX_COLLATERAL_RATIO );
// Note: there was code here calling `max_short_squeeze_price();` before core-1270 hard fork,
// in order to make sure that it doesn't overflow,
// but the code doesn't actually check overflow, and it won't overflow, so the code is removed.
// Note: not checking `maintenance_collateral_ratio >= maximum_short_squeeze_ratio` since launch
} FC_CAPTURE_AND_RETHROW( (*this) ) }
bool price_feed::is_for( asset_id_type asset_id ) const
{
try
{
if( !settlement_price.is_null() )
return (settlement_price.base.asset_id == asset_id);
if( !core_exchange_rate.is_null() )
return (core_exchange_rate.base.asset_id == asset_id);
// (null, null) is valid for any feed
return true;
}
FC_CAPTURE_AND_RETHROW( (*this) )
}
// This function is kept here due to potential different behavior in edge cases.
// TODO check after core-1270 hard fork to see if we can safely remove it
price price_feed::max_short_squeeze_price_before_hf_1270()const
{
// settlement price is in debt/collateral
boost::rational<int128_t> sp( settlement_price.base.amount.value, settlement_price.quote.amount.value );
boost::rational<int128_t> ratio( GRAPHENE_COLLATERAL_RATIO_DENOM, maximum_short_squeeze_ratio );
auto cp = sp * ratio;
while( cp.numerator() > GRAPHENE_MAX_SHARE_SUPPLY || cp.denominator() > GRAPHENE_MAX_SHARE_SUPPLY )
cp = boost::rational<int128_t>( (cp.numerator() >> 1)+(cp.numerator()&1),
(cp.denominator() >> 1)+(cp.denominator()&1) );
return ( asset( cp.numerator().convert_to<int64_t>(), settlement_price.base.asset_id )
/ asset( cp.denominator().convert_to<int64_t>(), settlement_price.quote.asset_id ) );
}
price price_feed::max_short_squeeze_price()const
{
// settlement price is in debt/collateral
return settlement_price * ratio_type( GRAPHENE_COLLATERAL_RATIO_DENOM, maximum_short_squeeze_ratio );
}
price price_feed::maintenance_collateralization()const
{
if( settlement_price.is_null() )
return price();
return ~settlement_price * ratio_type( maintenance_collateral_ratio, GRAPHENE_COLLATERAL_RATIO_DENOM );
}
// compile-time table of powers of 10 using template metaprogramming
template< int N >
struct p10
{
static const int64_t v = 10 * p10<N-1>::v;
};
template<>
struct p10<0>
{
static const int64_t v = 1;
};
const int64_t scaled_precision_lut[19] =
{
p10< 0 >::v, p10< 1 >::v, p10< 2 >::v, p10< 3 >::v,
p10< 4 >::v, p10< 5 >::v, p10< 6 >::v, p10< 7 >::v,
p10< 8 >::v, p10< 9 >::v, p10< 10 >::v, p10< 11 >::v,
p10< 12 >::v, p10< 13 >::v, p10< 14 >::v, p10< 15 >::v,
p10< 16 >::v, p10< 17 >::v, p10< 18 >::v
};
} } // graphene::chain
<|endoftext|>
|
<commit_before>///
/// @file
/// @copyright Copyright (C) 2017, Jonathan Bryan Schmalhofer
///
/// @brief Node to calculate the trajectory to be followed.
///
#include <string>
#include <ros/ros.h>
#include <js_messages/Trajectory3D.h>
#include "js_trajectory_planning_node/rtrrtstar_class.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "trajectory_planning_node");
ros::NodeHandle node_handle;
ros::Publisher trajectory3d_publisher = node_handle.advertise<js_messages::Trajectory3D>("/trajectory_planning/trajectory3d", 1000);
js_trajectory_planning_node::RTRRTStarClass planner;
ROS_INFO("Starting trajectory planning node");
ros::Rate node_rate(200.0f); // 2.0 hz
while (ros::ok())
{
//ROS_INFO("Update step");
/* Todo: change update functions
tree<js_trajectory_planning_node::NodeData> x_0;
tree<js_trajectory_planning_node::NodeData> x_goal;
tree<js_trajectory_planning_node::NodeData> x_agent;
planner.UpdateX0(x_0.begin());
planner.UpdateXGoal(x_goal.begin());
planner.UpdateXAgent(x_agent.begin());*/
planner.UpdateXiObs();
//ROS_INFO("Planning step");
planner.PerformPlanningCycleOnce();
//ROS_INFO("Publish step");
js_messages::Trajectory3D trajectory3d_message;
trajectory3d_publisher.publish(trajectory3d_message);
ros::spinOnce();
node_rate.sleep();
}
return 0;
}
<commit_msg>fixed typo in frequency<commit_after>///
/// @file
/// @copyright Copyright (C) 2017, Jonathan Bryan Schmalhofer
///
/// @brief Node to calculate the trajectory to be followed.
///
#include <string>
#include <ros/ros.h>
#include <js_messages/Trajectory3D.h>
#include "js_trajectory_planning_node/rtrrtstar_class.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "trajectory_planning_node");
ros::NodeHandle node_handle;
ros::Publisher trajectory3d_publisher = node_handle.advertise<js_messages::Trajectory3D>("/trajectory_planning/trajectory3d", 1000);
js_trajectory_planning_node::RTRRTStarClass planner;
ROS_INFO("Starting trajectory planning node");
ros::Rate node_rate(2.0f); // 2.0 hz
while (ros::ok())
{
//ROS_INFO("Update step");
/* Todo: change update functions
tree<js_trajectory_planning_node::NodeData> x_0;
tree<js_trajectory_planning_node::NodeData> x_goal;
tree<js_trajectory_planning_node::NodeData> x_agent;
planner.UpdateX0(x_0.begin());
planner.UpdateXGoal(x_goal.begin());
planner.UpdateXAgent(x_agent.begin());*/
planner.UpdateXiObs();
//ROS_INFO("Planning step");
planner.PerformPlanningCycleOnce();
//ROS_INFO("Publish step");
js_messages::Trajectory3D trajectory3d_message;
trajectory3d_publisher.publish(trajectory3d_message);
ros::spinOnce();
node_rate.sleep();
}
return 0;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qml.h"
#include "qmlviewer.h"
#include <QWidget>
#include <QDir>
#include <QApplication>
#include <QTranslator>
#include <QDebug>
QT_USE_NAMESPACE
#if defined (Q_OS_SYMBIAN)
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void myMessageOutput(QtMsgType type, const char *msg)
{
static int fd = -1;
if (fd == -1)
fd = ::open("E:\\qmlviewer.log", O_WRONLY | O_CREAT);
::write(fd, msg, strlen(msg));
::write(fd, "\n", 1);
::fsync(fd);
switch (type) {
case QtFatalMsg:
abort();
}
}
#endif
void usage()
{
qWarning("Usage: qmlviewer [options] <filename>");
qWarning(" ");
qWarning(" options:");
qWarning(" -v, -version ............................. display version");
qWarning(" -frameless ............................... run with no window frame");
qWarning(" -maximized................................ run maximized");
qWarning(" -fullscreen............................... run fullscreen");
qWarning(" -stayontop................................ keep viewer window on top");
qWarning(" -skin <qvfbskindir> ...................... run with a skin window frame");
qWarning(" \"list\" for a list of built-ins");
qWarning(" -resizeview .............................. resize the view, not the skin");
qWarning(" -qmlbrowser .............................. use a QML-based file browser");
qWarning(" -recordfile <output> ..................... set video recording file");
qWarning(" - ImageMagick 'convert' for GIF)");
qWarning(" - png file for raw frames");
qWarning(" - 'ffmpeg' for other formats");
qWarning(" -recorddither ordered|threshold|floyd .... set GIF dither recording mode");
qWarning(" -recordrate <fps> ........................ set recording frame rate");
qWarning(" -record arg .............................. add a recording process argument");
qWarning(" -autorecord [from-]<tomilliseconds> ...... set recording to start and stop");
qWarning(" -devicekeys .............................. use numeric keys (see F1)");
qWarning(" -netcache <size> ......................... set disk cache to size bytes");
qWarning(" -translation <translationfile> ........... set the language to run in");
qWarning(" -L <directory> ........................... prepend to the library search path");
qWarning(" -opengl .................................. use a QGLWidget for the viewport");
qWarning(" -script <path> ........................... set the script to use");
qWarning(" -scriptopts <options>|help ............... set the script options to use");
qWarning(" ");
qWarning(" Press F1 for interactive help");
exit(1);
}
void scriptOptsUsage()
{
qWarning("Usage: qmlviewer -scriptopts <option>[,<option>...] ...");
qWarning(" options:");
qWarning(" record ................................... record a new script");
qWarning(" play ..................................... playback an existing script");
qWarning(" testimages ............................... record images or compare images on playback");
qWarning(" testerror ................................ test 'error' property of root item on playback");
qWarning(" exitoncomplete ........................... cleanly exit the viewer on script completion");
qWarning(" exitonfailure ............................ immediately exit the viewer on script failure");
qWarning(" saveonexit ............................... save recording on viewer exit");
qWarning(" ");
qWarning(" One of record, play or both must be specified.");
exit(1);
}
int main(int argc, char ** argv)
{
#if defined (Q_OS_SYMBIAN)
qInstallMsgHandler(myMessageOutput);
#endif
#if defined (Q_WS_X11)
//### default to using raster graphics backend for now
bool gsSpecified = false;
for (int i = 0; i < argc; ++i) {
QString arg = argv[i];
if (arg == "-graphicssystem") {
gsSpecified = true;
break;
}
}
if (!gsSpecified)
QApplication::setGraphicsSystem("raster");
#endif
QApplication app(argc, argv);
app.setApplicationName("viewer");
app.setOrganizationName("Nokia");
app.setOrganizationDomain("nokia.com");
bool frameless = false;
bool resizeview = false;
QString fileName;
double fps = 0;
int autorecord_from = 0;
int autorecord_to = 0;
QString dither = "none";
QString recordfile;
QStringList recordargs;
QStringList libraries;
QString skin;
QString script;
QString scriptopts;
bool runScript = false;
bool devkeys = false;
int cache = 0;
QString translationFile;
bool useGL = false;
bool fullScreen = false;
bool stayOnTop = false;
bool maximized = false;
bool useNativeFileBrowser = true;
#if defined(Q_OS_SYMBIAN)
maximized = true;
useNativeFileBrowser = false;
#endif
for (int i = 1; i < argc; ++i) {
bool lastArg = (i == argc - 1);
QString arg = argv[i];
if (arg == "-frameless") {
frameless = true;
} else if (arg == "-maximized") {
maximized = true;
} else if (arg == "-fullscreen") {
fullScreen = true;
} else if (arg == "-stayontop") {
stayOnTop = true;
} else if (arg == "-skin") {
if (lastArg) usage();
skin = QString(argv[++i]);
} else if (arg == "-resizeview") {
resizeview = true;
} else if (arg == "-netcache") {
if (lastArg) usage();
cache = QString(argv[++i]).toInt();
} else if (arg == "-recordrate") {
if (lastArg) usage();
fps = QString(argv[++i]).toDouble();
} else if (arg == "-recordfile") {
if (lastArg) usage();
recordfile = QString(argv[++i]);
} else if (arg == "-record") {
if (lastArg) usage();
recordargs << QString(argv[++i]);
} else if (arg == "-recorddither") {
if (lastArg) usage();
dither = QString(argv[++i]);
} else if (arg == "-autorecord") {
if (lastArg) usage();
QString range = QString(argv[++i]);
int dash = range.indexOf('-');
if (dash > 0)
autorecord_from = range.left(dash).toInt();
autorecord_to = range.mid(dash+1).toInt();
} else if (arg == "-devicekeys") {
devkeys = true;
} else if (arg == QLatin1String("-v") || arg == QLatin1String("-version")) {
fprintf(stderr, "Qt Declarative UI Viewer version %s\n", QT_VERSION_STR);
return 0;
} else if (arg == "-translation") {
if (lastArg) usage();
translationFile = argv[++i];
} else if (arg == "-opengl") {
useGL = true;
} else if (arg == "-qmlbrowser") {
useNativeFileBrowser = false;
} else if (arg == "-L") {
if (lastArg) usage();
libraries << QString(argv[++i]);
} else if (arg == "-script") {
if (lastArg) usage();
script = QString(argv[++i]);
} else if (arg == "-scriptopts") {
if (lastArg) usage();
scriptopts = QString(argv[++i]);
} else if (arg == "-savescript") {
if (lastArg) usage();
script = QString(argv[++i]);
runScript = false;
} else if (arg == "-playscript") {
if (lastArg) usage();
script = QString(argv[++i]);
runScript = true;
} else if (arg[0] != '-') {
fileName = arg;
} else if (1 || arg == "-help") {
usage();
}
}
QTranslator qmlTranslator;
if (!translationFile.isEmpty()) {
qmlTranslator.load(translationFile);
app.installTranslator(&qmlTranslator);
}
Qt::WFlags wflags = (frameless ? Qt::FramelessWindowHint : Qt::Widget);
if (stayOnTop)
wflags |= Qt::WindowStaysOnTopHint;
QmlViewer viewer(0, wflags);
if (!scriptopts.isEmpty()) {
QStringList options =
scriptopts.split(QLatin1Char(','), QString::SkipEmptyParts);
QmlViewer::ScriptOptions scriptOptions = 0;
for (int i = 0; i < options.count(); ++i) {
const QString &option = options.at(i);
if (option == QLatin1String("help")) {
scriptOptsUsage();
} else if (option == QLatin1String("play")) {
scriptOptions |= QmlViewer::Play;
} else if (option == QLatin1String("record")) {
scriptOptions |= QmlViewer::Record;
} else if (option == QLatin1String("testimages")) {
scriptOptions |= QmlViewer::TestImages;
} else if (option == QLatin1String("testerror")) {
scriptOptions |= QmlViewer::TestErrorProperty;
} else if (option == QLatin1String("exitoncomplete")) {
scriptOptions |= QmlViewer::ExitOnComplete;
} else if (option == QLatin1String("exitonfailure")) {
scriptOptions |= QmlViewer::ExitOnFailure;
} else if (option == QLatin1String("saveonexit")) {
scriptOptions |= QmlViewer::SaveOnExit;
} else {
scriptOptsUsage();
}
}
if (script.isEmpty())
usage();
if (!(scriptOptions & QmlViewer::Record) && !(scriptOptions & QmlViewer::Play))
scriptOptsUsage();
viewer.setScriptOptions(scriptOptions);
viewer.setScript(script);
} else if (!script.isEmpty()) {
usage();
}
foreach (QString lib, libraries)
viewer.addLibraryPath(lib);
viewer.setNetworkCacheSize(cache);
viewer.setRecordFile(recordfile);
if (resizeview)
viewer.setScaleView();
if (fps>0)
viewer.setRecordRate(fps);
if (autorecord_to)
viewer.setAutoRecord(autorecord_from,autorecord_to);
if (!skin.isEmpty()) {
if (skin == "list") {
foreach (QString s, viewer.builtinSkins())
qWarning(s.toUtf8());
exit(0);
} else {
viewer.setSkin(skin);
}
}
if (devkeys)
viewer.setDeviceKeys(true);
viewer.setRecordDither(dither);
if (recordargs.count())
viewer.setRecordArgs(recordargs);
viewer.setUseNativeFileBrowser(useNativeFileBrowser);
if (fullScreen && maximized)
qWarning() << "Both -fullscreen and -maximized specified. Using -fullscreen.";
if (!fileName.isEmpty()) {
viewer.open(fileName);
fullScreen ? viewer.showFullScreen() : maximized ? viewer.showMaximized() : viewer.show();
} else {
if (!useNativeFileBrowser)
viewer.openFile();
fullScreen ? viewer.showFullScreen() : maximized ? viewer.showMaximized() : viewer.show();
if (useNativeFileBrowser)
viewer.openFile();
}
viewer.setUseGL(useGL);
viewer.raise();
return app.exec();
}
<commit_msg>Add support for startDragDistance in qmlviewer.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qml.h"
#include "qmlviewer.h"
#include <QWidget>
#include <QDir>
#include <QApplication>
#include <QTranslator>
#include <QDebug>
QT_USE_NAMESPACE
#if defined (Q_OS_SYMBIAN)
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void myMessageOutput(QtMsgType type, const char *msg)
{
static int fd = -1;
if (fd == -1)
fd = ::open("E:\\qmlviewer.log", O_WRONLY | O_CREAT);
::write(fd, msg, strlen(msg));
::write(fd, "\n", 1);
::fsync(fd);
switch (type) {
case QtFatalMsg:
abort();
}
}
#endif
void usage()
{
qWarning("Usage: qmlviewer [options] <filename>");
qWarning(" ");
qWarning(" options:");
qWarning(" -v, -version ............................. display version");
qWarning(" -frameless ............................... run with no window frame");
qWarning(" -maximized................................ run maximized");
qWarning(" -fullscreen............................... run fullscreen");
qWarning(" -stayontop................................ keep viewer window on top");
qWarning(" -skin <qvfbskindir> ...................... run with a skin window frame");
qWarning(" \"list\" for a list of built-ins");
qWarning(" -resizeview .............................. resize the view, not the skin");
qWarning(" -qmlbrowser .............................. use a QML-based file browser");
qWarning(" -recordfile <output> ..................... set video recording file");
qWarning(" - ImageMagick 'convert' for GIF)");
qWarning(" - png file for raw frames");
qWarning(" - 'ffmpeg' for other formats");
qWarning(" -recorddither ordered|threshold|floyd .... set GIF dither recording mode");
qWarning(" -recordrate <fps> ........................ set recording frame rate");
qWarning(" -record arg .............................. add a recording process argument");
qWarning(" -autorecord [from-]<tomilliseconds> ...... set recording to start and stop");
qWarning(" -devicekeys .............................. use numeric keys (see F1)");
qWarning(" -dragthreshold <size> .................... set mouse drag threshold size");
qWarning(" -netcache <size> ......................... set disk cache to size bytes");
qWarning(" -translation <translationfile> ........... set the language to run in");
qWarning(" -L <directory> ........................... prepend to the library search path");
qWarning(" -opengl .................................. use a QGLWidget for the viewport");
qWarning(" -script <path> ........................... set the script to use");
qWarning(" -scriptopts <options>|help ............... set the script options to use");
qWarning(" ");
qWarning(" Press F1 for interactive help");
exit(1);
}
void scriptOptsUsage()
{
qWarning("Usage: qmlviewer -scriptopts <option>[,<option>...] ...");
qWarning(" options:");
qWarning(" record ................................... record a new script");
qWarning(" play ..................................... playback an existing script");
qWarning(" testimages ............................... record images or compare images on playback");
qWarning(" testerror ................................ test 'error' property of root item on playback");
qWarning(" exitoncomplete ........................... cleanly exit the viewer on script completion");
qWarning(" exitonfailure ............................ immediately exit the viewer on script failure");
qWarning(" saveonexit ............................... save recording on viewer exit");
qWarning(" ");
qWarning(" One of record, play or both must be specified.");
exit(1);
}
int main(int argc, char ** argv)
{
#if defined (Q_OS_SYMBIAN)
qInstallMsgHandler(myMessageOutput);
#endif
#if defined (Q_WS_X11)
//### default to using raster graphics backend for now
bool gsSpecified = false;
for (int i = 0; i < argc; ++i) {
QString arg = argv[i];
if (arg == "-graphicssystem") {
gsSpecified = true;
break;
}
}
if (!gsSpecified)
QApplication::setGraphicsSystem("raster");
#endif
QApplication app(argc, argv);
app.setApplicationName("viewer");
app.setOrganizationName("Nokia");
app.setOrganizationDomain("nokia.com");
bool frameless = false;
bool resizeview = false;
QString fileName;
double fps = 0;
int autorecord_from = 0;
int autorecord_to = 0;
QString dither = "none";
QString recordfile;
QStringList recordargs;
QStringList libraries;
QString skin;
QString script;
QString scriptopts;
bool runScript = false;
bool devkeys = false;
int cache = 0;
QString translationFile;
bool useGL = false;
bool fullScreen = false;
bool stayOnTop = false;
bool maximized = false;
bool useNativeFileBrowser = true;
#if defined(Q_OS_SYMBIAN)
maximized = true;
useNativeFileBrowser = false;
#endif
for (int i = 1; i < argc; ++i) {
bool lastArg = (i == argc - 1);
QString arg = argv[i];
if (arg == "-frameless") {
frameless = true;
} else if (arg == "-maximized") {
maximized = true;
} else if (arg == "-fullscreen") {
fullScreen = true;
} else if (arg == "-stayontop") {
stayOnTop = true;
} else if (arg == "-skin") {
if (lastArg) usage();
skin = QString(argv[++i]);
} else if (arg == "-resizeview") {
resizeview = true;
} else if (arg == "-netcache") {
if (lastArg) usage();
cache = QString(argv[++i]).toInt();
} else if (arg == "-recordrate") {
if (lastArg) usage();
fps = QString(argv[++i]).toDouble();
} else if (arg == "-recordfile") {
if (lastArg) usage();
recordfile = QString(argv[++i]);
} else if (arg == "-record") {
if (lastArg) usage();
recordargs << QString(argv[++i]);
} else if (arg == "-recorddither") {
if (lastArg) usage();
dither = QString(argv[++i]);
} else if (arg == "-autorecord") {
if (lastArg) usage();
QString range = QString(argv[++i]);
int dash = range.indexOf('-');
if (dash > 0)
autorecord_from = range.left(dash).toInt();
autorecord_to = range.mid(dash+1).toInt();
} else if (arg == "-devicekeys") {
devkeys = true;
} else if (arg == "-dragthreshold") {
if (lastArg) usage();
app.setStartDragDistance(QString(argv[++i]).toInt());
} else if (arg == QLatin1String("-v") || arg == QLatin1String("-version")) {
fprintf(stderr, "Qt Declarative UI Viewer version %s\n", QT_VERSION_STR);
return 0;
} else if (arg == "-translation") {
if (lastArg) usage();
translationFile = argv[++i];
} else if (arg == "-opengl") {
useGL = true;
} else if (arg == "-qmlbrowser") {
useNativeFileBrowser = false;
} else if (arg == "-L") {
if (lastArg) usage();
libraries << QString(argv[++i]);
} else if (arg == "-script") {
if (lastArg) usage();
script = QString(argv[++i]);
} else if (arg == "-scriptopts") {
if (lastArg) usage();
scriptopts = QString(argv[++i]);
} else if (arg == "-savescript") {
if (lastArg) usage();
script = QString(argv[++i]);
runScript = false;
} else if (arg == "-playscript") {
if (lastArg) usage();
script = QString(argv[++i]);
runScript = true;
} else if (arg[0] != '-') {
fileName = arg;
} else if (1 || arg == "-help") {
usage();
}
}
QTranslator qmlTranslator;
if (!translationFile.isEmpty()) {
qmlTranslator.load(translationFile);
app.installTranslator(&qmlTranslator);
}
Qt::WFlags wflags = (frameless ? Qt::FramelessWindowHint : Qt::Widget);
if (stayOnTop)
wflags |= Qt::WindowStaysOnTopHint;
QmlViewer viewer(0, wflags);
if (!scriptopts.isEmpty()) {
QStringList options =
scriptopts.split(QLatin1Char(','), QString::SkipEmptyParts);
QmlViewer::ScriptOptions scriptOptions = 0;
for (int i = 0; i < options.count(); ++i) {
const QString &option = options.at(i);
if (option == QLatin1String("help")) {
scriptOptsUsage();
} else if (option == QLatin1String("play")) {
scriptOptions |= QmlViewer::Play;
} else if (option == QLatin1String("record")) {
scriptOptions |= QmlViewer::Record;
} else if (option == QLatin1String("testimages")) {
scriptOptions |= QmlViewer::TestImages;
} else if (option == QLatin1String("testerror")) {
scriptOptions |= QmlViewer::TestErrorProperty;
} else if (option == QLatin1String("exitoncomplete")) {
scriptOptions |= QmlViewer::ExitOnComplete;
} else if (option == QLatin1String("exitonfailure")) {
scriptOptions |= QmlViewer::ExitOnFailure;
} else if (option == QLatin1String("saveonexit")) {
scriptOptions |= QmlViewer::SaveOnExit;
} else {
scriptOptsUsage();
}
}
if (script.isEmpty())
usage();
if (!(scriptOptions & QmlViewer::Record) && !(scriptOptions & QmlViewer::Play))
scriptOptsUsage();
viewer.setScriptOptions(scriptOptions);
viewer.setScript(script);
} else if (!script.isEmpty()) {
usage();
}
foreach (QString lib, libraries)
viewer.addLibraryPath(lib);
viewer.setNetworkCacheSize(cache);
viewer.setRecordFile(recordfile);
if (resizeview)
viewer.setScaleView();
if (fps>0)
viewer.setRecordRate(fps);
if (autorecord_to)
viewer.setAutoRecord(autorecord_from,autorecord_to);
if (!skin.isEmpty()) {
if (skin == "list") {
foreach (QString s, viewer.builtinSkins())
qWarning(s.toUtf8());
exit(0);
} else {
viewer.setSkin(skin);
}
}
if (devkeys)
viewer.setDeviceKeys(true);
viewer.setRecordDither(dither);
if (recordargs.count())
viewer.setRecordArgs(recordargs);
viewer.setUseNativeFileBrowser(useNativeFileBrowser);
if (fullScreen && maximized)
qWarning() << "Both -fullscreen and -maximized specified. Using -fullscreen.";
if (!fileName.isEmpty()) {
viewer.open(fileName);
fullScreen ? viewer.showFullScreen() : maximized ? viewer.showMaximized() : viewer.show();
} else {
if (!useNativeFileBrowser)
viewer.openFile();
fullScreen ? viewer.showFullScreen() : maximized ? viewer.showMaximized() : viewer.show();
if (useNativeFileBrowser)
viewer.openFile();
}
viewer.setUseGL(useGL);
viewer.raise();
return app.exec();
}
<|endoftext|>
|
<commit_before>/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
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 "regex_feature_extractor.hpp"
#include <fstream>
#include <iostream>
namespace resembla {
RegexFeatureExtractor::RegexFeatureExtractor(const std::initializer_list<std::pair<Feature::real_type, std::string>>& patterns)
{
construct(patterns);
}
RegexFeatureExtractor::RegexFeatureExtractor(const std::string file_path)
{
construct(load(file_path));
}
Feature::real_type RegexFeatureExtractor::match(const string_type& text) const
{
for(const auto& i: re_all){
if(std::regex_match(text, i.second)){
#ifdef DEBUG
std::cerr << "regex detector: evidence found, text=" << cast_string<std::string>(text) << ", score=" << i.first << std::endl;
#endif
return i.first;
}
}
return 0.0;
}
std::vector<std::pair<double, std::string>> RegexFeatureExtractor::load(const std::string file_path)
{
std::ifstream ifs(file_path);
if(ifs.fail()){
throw std::runtime_error("input file is not available: " + file_path);
}
const auto delimiter = column_delimiter<>();
std::vector<std::pair<double, std::string>> patterns;
while(ifs.good()){
std::string line;
std::getline(ifs, line);
if(ifs.eof() || line.length() == 0){
break;
}
size_t i = line.find(delimiter);
if(i != std::string::npos){
patterns.push_back(std::make_pair(std::stod(line.substr(0, i)), line.substr(i + 1)));
}
}
return patterns;
}
Feature::text_type RegexFeatureExtractor::operator()(const string_type& text) const
{
return Feature::toText(match(text));
}
}
<commit_msg>use constexpr<commit_after>/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
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 "regex_feature_extractor.hpp"
#include <fstream>
#include <iostream>
namespace resembla {
RegexFeatureExtractor::RegexFeatureExtractor(const std::initializer_list<std::pair<Feature::real_type, std::string>>& patterns)
{
construct(patterns);
}
RegexFeatureExtractor::RegexFeatureExtractor(const std::string file_path)
{
construct(load(file_path));
}
Feature::real_type RegexFeatureExtractor::match(const string_type& text) const
{
for(const auto& i: re_all){
if(std::regex_match(text, i.second)){
#ifdef DEBUG
std::cerr << "regex detector: evidence found, text=" << cast_string<std::string>(text) << ", score=" << i.first << std::endl;
#endif
return i.first;
}
}
return 0.0;
}
std::vector<std::pair<double, std::string>> RegexFeatureExtractor::load(const std::string file_path)
{
std::ifstream ifs(file_path);
if(ifs.fail()){
throw std::runtime_error("input file is not available: " + file_path);
}
std::vector<std::pair<double, std::string>> patterns;
while(ifs.good()){
std::string line;
std::getline(ifs, line);
if(ifs.eof() || line.length() == 0){
break;
}
size_t i = line.find(column_delimiter<>());
if(i != std::string::npos){
patterns.push_back(std::make_pair(std::stod(line.substr(0, i)), line.substr(i + 1)));
}
}
return patterns;
}
Feature::text_type RegexFeatureExtractor::operator()(const string_type& text) const
{
return Feature::toText(match(text));
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <cmath>
#include "../../include/boids2D/MovableBoid.hpp"
#include "../../include/Utils.hpp"
// TODO : steering + solver. The force send should be only normalize in the end
MovableBoid::MovableBoid(glm::vec3 location, BoidType t)
: MovableBoid(location, glm::vec3(0,0,0), t)
{
}
MovableBoid::MovableBoid(glm::vec3 location, glm::vec3 velocity, BoidType t)
: MovableBoid(location, velocity, 0.05f, t)
{
}
MovableBoid::MovableBoid(glm::vec3 location, glm::vec3 velocity, float mass, BoidType t)
: MovableBoid(location, velocity, mass, 3*M_PI/4, 1.0f, 2.0f, t)
{
}
MovableBoid::MovableBoid(glm::vec3 location, glm::vec3 velocity, float mass,
float angleView, float distViewSeparate, float distViewCohesion, BoidType t)
: MovableBoid(location, velocity, mass, angleView, distViewSeparate, distViewCohesion, 3.5f, 2.0f, t)
{
}
MovableBoid::MovableBoid(glm::vec3 location, glm::vec3 velocity, float mass,
float angleView, float distViewSeparate, float distViewCohesion, float maxSpeed,
float maxForce, BoidType t)
: Boid(location, t), m_velocity(velocity),
m_acceleration(glm::vec3(0,0,0)), m_mass(mass),
m_angleView(angleView), m_distViewSeparate(distViewSeparate),
m_distViewCohesion(distViewCohesion),
m_maxSpeed(maxSpeed), m_maxForce(maxForce)
{
}
bool MovableBoid::canSee(Boid b, float distView) {
return (glm::distance(m_location, b.getLocation()) < distView) && (angleVision(b));
}
bool MovableBoid::angleVision (Boid b) {
glm::vec3 diffPos = b.getLocation() - m_location;
float comparativeValue = acos(glm::dot(glm::normalize(m_velocity), glm::normalize(diffPos)));
if (m_angleView <= M_PI) {
return (0 <= comparativeValue) && (comparativeValue <= m_angleView/2);
} else {
diffPos = - diffPos;
comparativeValue = - comparativeValue;
return !((0 <= comparativeValue) && (comparativeValue <= M_PI - m_angleView/2));
}
}
void MovableBoid::computeNextStep(float dt) {
m_velocity = limitVec3(m_velocity + (dt / m_mass) * limitVec3(m_acceleration, m_maxForce), m_maxSpeed);
setAngle(atan2(m_velocity.y, m_velocity.x));
m_location += dt * m_velocity;
}
glm::vec3 MovableBoid::getVelocity(){
return m_velocity;
}
float MovableBoid::getMass() {
return m_mass;
}
glm::vec3 MovableBoid::computeAcceleration (std::vector<MovableBoidPtr> mvB) {
// Reset acceleration
m_acceleration = glm::vec3(0, 0, 0);
if (getTarget().x == 0) {
glm::vec3 wanderVec = 4.0f * wander();
glm::vec3 separateVec = 16.0f * separate(mvB);
glm::vec3 alignVec = 16.0f * align(mvB);
glm::vec3 cohesionVec = 16.0f * cohesion(mvB);
glm::vec3 stayWithinWallsVec = 48.0f * ruleStayWithinWalls();
m_acceleration = wanderVec + separateVec + alignVec + cohesionVec + stayWithinWallsVec;
} else {
glm::vec3 seek = 1.0f * arrive(glm::vec3(getTarget().x, getTarget().y, 2));
glm::vec3 separateVec = 16.0f * separate(mvB);
m_acceleration = seek + separateVec;
}
}
glm::vec3 MovableBoid::ruleStayWithinWalls() {
glm::vec3 steer(0, 0, 0);
float distToWall = 20.0f;
if (m_location.x < -distToWall) {
glm::vec3 desired(m_maxSpeed, m_velocity.y, 0);
steer = desired - m_velocity;
} else if (m_location.x > distToWall) {
glm::vec3 desired(-m_maxSpeed, m_velocity.y, 0);
steer = desired - m_velocity ;
}
if (m_location.y < -distToWall) {
glm::vec3 desired(m_velocity.x, m_maxSpeed, 0);
steer += desired - m_velocity;
} else if (m_location.y > distToWall) {
glm::vec3 desired(m_velocity.x, -m_maxSpeed, 0);
steer += desired - m_velocity;
}
steer = limitVec3(steer, m_maxForce);
return steer;
}
glm::vec3 MovableBoid::wander() {
float randomVal = random(0.0f, 2*M_PI);
glm::vec3 randomVec3(cos(randomVal), sin(randomVal), 0);
glm::vec3 desiredTarget = m_location + distToCircle*m_velocity + rCircleWander*randomVec3;
return arrive(desiredTarget);
}
glm::vec3 MovableBoid::separate(std::vector<MovableBoidPtr> mvB) {
glm::vec3 sum;
int count = 0;
for(MovableBoidPtr m : mvB) {
float d = glm::distance(getLocation(), m->getLocation());
if ((d > 0) && canSee(*m, m_distViewSeparate)) {
glm::vec3 diff = getLocation() - m->getLocation();
diff = glm::normalize(diff) / d;
sum += diff;
count++;
}
}
if (count > 0) {
sum /= count;
sum = glm::normalize(sum) * m_maxSpeed;
glm::vec3 steer = sum - m_velocity;
return limitVec3(steer, m_maxForce);
}
return glm::vec3(0, 0, 0);
}
glm::vec3 MovableBoid::arrive(glm::vec3 target) {
glm::vec3 desired = target - m_location;
float d = glm::length(desired);
glm::normalize(desired);
if (d < distStartSlowingDown) {
// Set the magnitude according to how close we are.
float m = d*m_maxSpeed/distStartSlowingDown;
desired *= m;
} else {
// Otherwise, proceed at maximum speed.
desired *= m_maxSpeed;
}
// The usual steering = desired - velocity
glm::vec3 steer = desired - m_velocity;
if (glm::length(steer) > m_maxForce) {
steer = glm::normalize(steer)*m_maxForce;
}
return steer;
}
glm::vec3 MovableBoid::align (std::vector<MovableBoidPtr> mvB) {
glm::vec3 sum(0,0,0);
int count = 0;
for (MovableBoidPtr other : mvB) {
float d = glm::distance(getLocation(), other->getLocation());
if ((d > 0) && (d < m_distViewCohesion) && canSee(*other, m_angleView)) {
sum += other->m_velocity;
// For an average, we need to keep track of
// how many boids are within the distance.
count++;
}
}
if (count > 0) {
sum = sum / (float) count;
// sum.normalize();
// sum.mult(maxspeed);
return glm::normalize(limitVec3(sum - m_velocity, m_maxForce));
}
return glm::vec3(0,0,0);
}
glm::vec3 MovableBoid::cohesion (std::vector<MovableBoidPtr> mvB) {
glm::vec3 sum(0,0,0);
int count = 0;
for (MovableBoidPtr other : mvB) {
float d = glm::distance(getLocation(), other->getLocation());
if ((d > 0) && (d < m_distViewCohesion) && canSee(*other, m_angleView)) {
// Adding up all the others’ locations
sum += other->getLocation();
count++;
}
}
if (count > 0) {
sum /= (float) count;
// Here we make use of the seek() function we
// wrote in Example 6.8. The target
// we seek is the average location of
// our neighbors.
return arrive(sum);
}
return glm::vec3(0,0,0);
}
glm::vec3 MovableBoid::getAcceleration() {
return m_acceleration;
}
bool operator==(const MovableBoid& b1, const MovableBoid& b2) {
return b1.getLocation() == b2.getLocation();
}
bool operator!=(const MovableBoid& b1, const MovableBoid& b2){
return !(b1 == b2);
}<commit_msg>Change paramater of initialization of boid<commit_after>#include <iostream>
#include <cmath>
#include "../../include/boids2D/MovableBoid.hpp"
#include "../../include/Utils.hpp"
MovableBoid::MovableBoid(glm::vec3 location, BoidType t)
: MovableBoid(location, glm::vec3(0,0,0), t)
{
}
MovableBoid::MovableBoid(glm::vec3 location, glm::vec3 velocity, BoidType t)
: MovableBoid(location, velocity, 0.05f, t)
{
}
MovableBoid::MovableBoid(glm::vec3 location, glm::vec3 velocity, float mass, BoidType t)
: MovableBoid(location, velocity, mass, 3*M_PI/4, 0.3f, 2.0f, t)
{
}
MovableBoid::MovableBoid(glm::vec3 location, glm::vec3 velocity, float mass,
float angleView, float distViewSeparate, float distViewCohesion, BoidType t)
: MovableBoid(location, velocity, mass, angleView, distViewSeparate, distViewCohesion, 3.5f, 2.0f, t)
{
}
MovableBoid::MovableBoid(glm::vec3 location, glm::vec3 velocity, float mass,
float angleView, float distViewSeparate, float distViewCohesion, float maxSpeed,
float maxForce, BoidType t)
: Boid(location, t), m_velocity(velocity),
m_acceleration(glm::vec3(0,0,0)), m_mass(mass),
m_angleView(angleView), m_distViewSeparate(distViewSeparate),
m_distViewCohesion(distViewCohesion),
m_maxSpeed(maxSpeed), m_maxForce(maxForce)
{
}
bool MovableBoid::canSee(Boid b, float distView) {
return (glm::distance(m_location, b.getLocation()) < distView) && (angleVision(b));
}
bool MovableBoid::angleVision (Boid b) {
glm::vec3 diffPos = b.getLocation() - m_location;
float comparativeValue = acos(glm::dot(glm::normalize(m_velocity), glm::normalize(diffPos)));
if (m_angleView <= M_PI) {
return (0 <= comparativeValue) && (comparativeValue <= m_angleView/2);
} else {
diffPos = - diffPos;
comparativeValue = - comparativeValue;
return !((0 <= comparativeValue) && (comparativeValue <= M_PI - m_angleView/2));
}
}
void MovableBoid::computeNextStep(float dt) {
m_velocity = limitVec3(m_velocity + (dt / m_mass) * limitVec3(m_acceleration, m_maxForce), m_maxSpeed);
setAngle(atan2(m_velocity.y, m_velocity.x));
m_location += dt * m_velocity;
}
glm::vec3 MovableBoid::getVelocity(){
return m_velocity;
}
float MovableBoid::getMass() {
return m_mass;
}
glm::vec3 MovableBoid::computeAcceleration (std::vector<MovableBoidPtr> mvB) {
// Reset acceleration
m_acceleration = glm::vec3(0, 0, 0);
if (getTarget().x == 0) {
glm::vec3 wanderVec = 4.0f * wander();
glm::vec3 separateVec = 16.0f * separate(mvB);
glm::vec3 alignVec = 16.0f * align(mvB);
glm::vec3 cohesionVec = 16.0f * cohesion(mvB);
glm::vec3 stayWithinWallsVec = 48.0f * ruleStayWithinWalls();
m_acceleration = wanderVec + separateVec + alignVec + cohesionVec + stayWithinWallsVec;
} else {
glm::vec3 seek = 1.0f * arrive(glm::vec3(getTarget().x, getTarget().y, 2));
glm::vec3 separateVec = 16.0f * separate(mvB);
m_acceleration = seek + separateVec;
}
}
glm::vec3 MovableBoid::ruleStayWithinWalls() {
glm::vec3 steer(0, 0, 0);
float distToWall = 20.0f;
if (m_location.x < -distToWall) {
glm::vec3 desired(m_maxSpeed, m_velocity.y, 0);
steer = desired - m_velocity;
} else if (m_location.x > distToWall) {
glm::vec3 desired(-m_maxSpeed, m_velocity.y, 0);
steer = desired - m_velocity ;
}
if (m_location.y < -distToWall) {
glm::vec3 desired(m_velocity.x, m_maxSpeed, 0);
steer += desired - m_velocity;
} else if (m_location.y > distToWall) {
glm::vec3 desired(m_velocity.x, -m_maxSpeed, 0);
steer += desired - m_velocity;
}
steer = limitVec3(steer, m_maxForce);
return steer;
}
glm::vec3 MovableBoid::wander() {
float randomVal = random(0.0f, 2*M_PI);
glm::vec3 randomVec3(cos(randomVal), sin(randomVal), 0);
glm::vec3 desiredTarget = m_location + distToCircle*m_velocity + rCircleWander*randomVec3;
return arrive(desiredTarget);
}
glm::vec3 MovableBoid::separate(std::vector<MovableBoidPtr> mvB) {
glm::vec3 sum;
int count = 0;
for(MovableBoidPtr m : mvB) {
float d = glm::distance(getLocation(), m->getLocation());
if ((d > 0) && canSee(*m, m_distViewSeparate)) {
glm::vec3 diff = getLocation() - m->getLocation();
diff = glm::normalize(diff) / d;
sum += diff;
count++;
}
}
if (count > 0) {
sum /= count;
sum = glm::normalize(sum) * m_maxSpeed;
glm::vec3 steer = sum - m_velocity;
return limitVec3(steer, m_maxForce);
}
return glm::vec3(0, 0, 0);
}
glm::vec3 MovableBoid::arrive(glm::vec3 target) {
glm::vec3 desired = target - m_location;
float d = glm::length(desired);
glm::normalize(desired);
if (d < distStartSlowingDown) {
// Set the magnitude according to how close we are.
float m = d*m_maxSpeed/distStartSlowingDown;
desired *= m;
} else {
// Otherwise, proceed at maximum speed.
desired *= m_maxSpeed;
}
// The usual steering = desired - velocity
glm::vec3 steer = desired - m_velocity;
if (glm::length(steer) > m_maxForce) {
steer = glm::normalize(steer)*m_maxForce;
}
return steer;
}
glm::vec3 MovableBoid::align (std::vector<MovableBoidPtr> mvB) {
glm::vec3 sum(0,0,0);
int count = 0;
for (MovableBoidPtr other : mvB) {
float d = glm::distance(getLocation(), other->getLocation());
if ((d > 0) && (d < m_distViewCohesion) && canSee(*other, m_angleView)) {
sum += other->m_velocity;
// For an average, we need to keep track of
// how many boids are within the distance.
count++;
}
}
if (count > 0) {
sum = sum / (float) count;
// sum.normalize();
// sum.mult(maxspeed);
return glm::normalize(limitVec3(sum - m_velocity, m_maxForce));
}
return glm::vec3(0,0,0);
}
glm::vec3 MovableBoid::cohesion (std::vector<MovableBoidPtr> mvB) {
glm::vec3 sum(0,0,0);
int count = 0;
for (MovableBoidPtr other : mvB) {
float d = glm::distance(getLocation(), other->getLocation());
if ((d > 0) && (d < m_distViewCohesion) && canSee(*other, m_angleView)) {
// Adding up all the others’ locations
sum += other->getLocation();
count++;
}
}
if (count > 0) {
sum /= (float) count;
// Here we make use of the seek() function we
// wrote in Example 6.8. The target
// we seek is the average location of
// our neighbors.
return arrive(sum);
}
return glm::vec3(0,0,0);
}
glm::vec3 MovableBoid::getAcceleration() {
return m_acceleration;
}
bool operator==(const MovableBoid& b1, const MovableBoid& b2) {
return b1.getLocation() == b2.getLocation();
}
bool operator!=(const MovableBoid& b1, const MovableBoid& b2){
return !(b1 == b2);
}<|endoftext|>
|
<commit_before><commit_msg>fix -Wunused-variable<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright 2008-2012 NVIDIA 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.
*/
#include <thrust/iterator/iterator_traits.h>
#include <thrust/detail/temporary_array.h>
#include <thrust/merge.h>
#include <thrust/system/detail/sequential/insertion_sort.h>
namespace thrust
{
namespace system
{
namespace detail
{
namespace sequential
{
namespace stable_merge_sort_detail
{
template<typename DerivedPolicy,
typename RandomAccessIterator,
typename StrictWeakOrdering>
__host__ __device__
void inplace_merge(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator first,
RandomAccessIterator middle,
RandomAccessIterator last,
StrictWeakOrdering comp)
{
typedef typename thrust::iterator_value<RandomAccessIterator>::type value_type;
thrust::detail::temporary_array<value_type, DerivedPolicy> a(exec, first, middle);
thrust::detail::temporary_array<value_type, DerivedPolicy> b(exec, middle, last);
thrust::merge(exec, a.begin(), a.end(), b.begin(), b.end(), first, comp);
}
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename StrictWeakOrdering>
__host__ __device__
void inplace_merge_by_key(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 first1,
RandomAccessIterator1 middle1,
RandomAccessIterator1 last1,
RandomAccessIterator2 first2,
StrictWeakOrdering comp)
{
typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type1;
typedef typename thrust::iterator_value<RandomAccessIterator2>::type value_type2;
RandomAccessIterator2 middle2 = first2 + (middle1 - first1);
RandomAccessIterator2 last2 = first2 + (last1 - first1);
thrust::detail::temporary_array<value_type1, DerivedPolicy> lhs1(exec, first1, middle1);
thrust::detail::temporary_array<value_type1, DerivedPolicy> rhs1(exec, middle1, last1);
thrust::detail::temporary_array<value_type2, DerivedPolicy> lhs2(exec, first2, middle2);
thrust::detail::temporary_array<value_type2, DerivedPolicy> rhs2(exec, middle2, last2);
thrust::merge_by_key(exec,
lhs1.begin(), lhs1.end(),
rhs1.begin(), rhs1.end(),
lhs2.begin(), rhs2.begin(),
first1, first2,
comp);
}
template<typename RandomAccessIterator,
typename Size,
typename StrictWeakOrdering>
__host__ __device__
void insertion_sort_each(RandomAccessIterator first,
RandomAccessIterator last,
Size partition_size,
StrictWeakOrdering comp)
{
if(partition_size > 1)
{
for(; first < last; first += partition_size)
{
RandomAccessIterator partition_last = thrust::min(last, first + partition_size);
thrust::system::detail::sequential::insertion_sort(first, partition_last, comp);
} // end for
} // end if
} // end insertion_sort_each()
template<typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename Size,
typename StrictWeakOrdering>
__host__ __device__
void insertion_sort_each_by_key(RandomAccessIterator1 keys_first,
RandomAccessIterator1 keys_last,
RandomAccessIterator2 values_first,
Size partition_size,
StrictWeakOrdering comp)
{
if(partition_size > 1)
{
for(; keys_first < keys_last; keys_first += partition_size, values_first += partition_size)
{
RandomAccessIterator1 keys_partition_last = thrust::min(keys_last, keys_first + partition_size);
thrust::system::detail::sequential::insertion_sort_by_key(keys_first, keys_partition_last, values_first, comp);
} // end for
} // end if
} // end insertion_sort_each()
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename Size,
typename RandomAccessIterator2,
typename StrictWeakOrdering>
__host__ __device__
void merge_adjacent_partitions(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 first,
RandomAccessIterator1 last,
Size partition_size,
RandomAccessIterator2 result,
StrictWeakOrdering comp)
{
for(; first < last; first += 2 * partition_size, result += 2 * partition_size)
{
RandomAccessIterator1 interval_middle = thrust::min(last, first + partition_size);
RandomAccessIterator1 interval_last = thrust::min(last, interval_middle + partition_size);
thrust::merge(exec,
first, interval_middle,
interval_middle, interval_last,
result,
comp);
} // end for
} // end merge_adjacent_partitions()
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename Size,
typename RandomAccessIterator3,
typename RandomAccessIterator4,
typename StrictWeakOrdering>
__host__ __device__
void merge_adjacent_partitions_by_key(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 keys_first,
RandomAccessIterator1 keys_last,
RandomAccessIterator2 values_first,
Size partition_size,
RandomAccessIterator3 keys_result,
RandomAccessIterator4 values_result,
StrictWeakOrdering comp)
{
Size stride = 2 * partition_size;
for(;
keys_first < keys_last;
keys_first += stride, values_first += stride, keys_result += stride, values_result += stride)
{
RandomAccessIterator1 keys_interval_middle = thrust::min(keys_last, keys_first + partition_size);
RandomAccessIterator1 keys_interval_last = thrust::min(keys_last, keys_interval_middle + partition_size);
RandomAccessIterator2 values_first2 = values_first + (keys_interval_middle - keys_first);
thrust::merge_by_key(exec,
keys_first, keys_interval_middle,
keys_interval_middle, keys_interval_last,
values_first,
values_first2,
keys_result,
values_result,
comp);
} // end for
} // end merge_adjacent_partitions()
template<typename DerivedPolicy,
typename RandomAccessIterator,
typename StrictWeakOrdering>
__host__ __device__
void iterative_stable_merge_sort(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator first,
RandomAccessIterator last,
StrictWeakOrdering comp)
{
typedef typename thrust::iterator_value<RandomAccessIterator>::type value_type;
typedef typename thrust::iterator_difference<RandomAccessIterator>::type difference_type;
difference_type n = last - first;
thrust::detail::temporary_array<value_type, DerivedPolicy> temp(exec, n);
// insertion sort each 32 element partition
difference_type partition_size = 32;
insertion_sort_each(first, last, partition_size, comp);
// ping indicates whether or not the latest data is in the source range [first, last)
bool ping = true;
// merge adjacent partitions until the partition size covers the entire range
for(;
partition_size < n;
partition_size *= 2, ping = !ping)
{
if(ping)
{
merge_adjacent_partitions(exec, first, last, partition_size, temp.begin(), comp);
} // end if
else
{
merge_adjacent_partitions(exec, temp.begin(), temp.end(), partition_size, first, comp);
} // end else
} // end for m
if(!ping)
{
thrust::copy(exec, temp.begin(), temp.end(), first);
} // end if
} // end iterative_stable_merge_sort()
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename StrictWeakOrdering>
__host__ __device__
void iterative_stable_merge_sort_by_key(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 keys_first,
RandomAccessIterator1 keys_last,
RandomAccessIterator2 values_first,
StrictWeakOrdering comp)
{
typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type1;
typedef typename thrust::iterator_value<RandomAccessIterator2>::type value_type2;
typedef typename thrust::iterator_difference<RandomAccessIterator1>::type difference_type;
difference_type n = keys_last - keys_first;
thrust::detail::temporary_array<value_type1, DerivedPolicy> keys_temp(exec, n);
thrust::detail::temporary_array<value_type2, DerivedPolicy> values_temp(exec, n);
// insertion sort each 32 element partition
difference_type partition_size = 32;
insertion_sort_each_by_key(keys_first, keys_last, values_first, partition_size, comp);
// ping indicates whether or not the latest data is in the source range [first, last)
bool ping = true;
// merge adjacent partitions until the partition size covers the entire range
for(;
partition_size < n;
partition_size *= 2, ping = !ping)
{
if(ping)
{
merge_adjacent_partitions_by_key(exec, keys_first, keys_last, values_first, partition_size, keys_temp.begin(), values_temp.begin(), comp);
} // end if
else
{
merge_adjacent_partitions_by_key(exec, keys_temp.begin(), keys_temp.end(), values_temp.begin(), partition_size, keys_first, values_first, comp);
} // end else
} // end for m
if(!ping)
{
thrust::copy(exec, keys_temp.begin(), keys_temp.end(), keys_first);
thrust::copy(exec, values_temp.begin(), values_temp.end(), values_first);
} // end if
} // end iterative_stable_merge_sort()
template<typename DerivedPolicy,
typename RandomAccessIterator,
typename StrictWeakOrdering>
__host__ __device__
void recursive_stable_merge_sort(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator first,
RandomAccessIterator last,
StrictWeakOrdering comp)
{
if(last - first <= 32)
{
thrust::system::detail::sequential::insertion_sort(first, last, comp);
} // end if
else
{
RandomAccessIterator middle = first + (last - first) / 2;
stable_merge_sort_detail::recursive_stable_merge_sort(exec, first, middle, comp);
stable_merge_sort_detail::recursive_stable_merge_sort(exec, middle, last, comp);
stable_merge_sort_detail::inplace_merge(exec, first, middle, last, comp);
} // end else
} // end recursive_stable_merge_sort()
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename StrictWeakOrdering>
__host__ __device__
void recursive_stable_merge_sort_by_key(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 first1,
RandomAccessIterator1 last1,
RandomAccessIterator2 first2,
StrictWeakOrdering comp)
{
if(last1 - first1 <= 32)
{
thrust::system::detail::sequential::insertion_sort_by_key(first1, last1, first2, comp);
} // end if
else
{
RandomAccessIterator1 middle1 = first1 + (last1 - first1) / 2;
RandomAccessIterator2 middle2 = first2 + (last1 - first1) / 2;
stable_merge_sort_detail::recursive_stable_merge_sort_by_key(exec, first1, middle1, first2, comp);
stable_merge_sort_detail::recursive_stable_merge_sort_by_key(exec, middle1, last1, middle2, comp);
stable_merge_sort_detail::inplace_merge_by_key(exec, first1, middle1, last1, first2, comp);
} // end else
} // end recursive_stable_merge_sort_by_key()
} // end namespace stable_merge_sort_detail
template<typename DerivedPolicy,
typename RandomAccessIterator,
typename StrictWeakOrdering>
__host__ __device__
void stable_merge_sort(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator first,
RandomAccessIterator last,
StrictWeakOrdering comp)
{
// avoid recursion in CUDA threads
#ifdef __CUDA_ARCH__
stable_merge_sort_detail::iterative_stable_merge_sort(exec, first, last, comp);
#else
stable_merge_sort_detail::recursive_stable_merge_sort(exec, first, last, comp);
#endif
}
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename StrictWeakOrdering>
__host__ __device__
void stable_merge_sort_by_key(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 first1,
RandomAccessIterator1 last1,
RandomAccessIterator2 first2,
StrictWeakOrdering comp)
{
// avoid recursion in CUDA threads
#ifdef __CUDA_ARCH__
stable_merge_sort_detail::iterative_stable_merge_sort_by_key(exec, first1, last1, first2, comp);
#else
stable_merge_sort_detail::recursive_stable_merge_sort_by_key(exec, first1, last1, first2, comp);
#endif
}
} // end namespace sequential
} // end namespace detail
} // end namespace system
} // end namespace thrust
<commit_msg>Add a missing #include <thrust/detail/minmax.h><commit_after>/*
* Copyright 2008-2012 NVIDIA 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.
*/
#include <thrust/iterator/iterator_traits.h>
#include <thrust/detail/temporary_array.h>
#include <thrust/merge.h>
#include <thrust/system/detail/sequential/insertion_sort.h>
#include <thrust/detail/minmax.h>
namespace thrust
{
namespace system
{
namespace detail
{
namespace sequential
{
namespace stable_merge_sort_detail
{
template<typename DerivedPolicy,
typename RandomAccessIterator,
typename StrictWeakOrdering>
__host__ __device__
void inplace_merge(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator first,
RandomAccessIterator middle,
RandomAccessIterator last,
StrictWeakOrdering comp)
{
typedef typename thrust::iterator_value<RandomAccessIterator>::type value_type;
thrust::detail::temporary_array<value_type, DerivedPolicy> a(exec, first, middle);
thrust::detail::temporary_array<value_type, DerivedPolicy> b(exec, middle, last);
thrust::merge(exec, a.begin(), a.end(), b.begin(), b.end(), first, comp);
}
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename StrictWeakOrdering>
__host__ __device__
void inplace_merge_by_key(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 first1,
RandomAccessIterator1 middle1,
RandomAccessIterator1 last1,
RandomAccessIterator2 first2,
StrictWeakOrdering comp)
{
typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type1;
typedef typename thrust::iterator_value<RandomAccessIterator2>::type value_type2;
RandomAccessIterator2 middle2 = first2 + (middle1 - first1);
RandomAccessIterator2 last2 = first2 + (last1 - first1);
thrust::detail::temporary_array<value_type1, DerivedPolicy> lhs1(exec, first1, middle1);
thrust::detail::temporary_array<value_type1, DerivedPolicy> rhs1(exec, middle1, last1);
thrust::detail::temporary_array<value_type2, DerivedPolicy> lhs2(exec, first2, middle2);
thrust::detail::temporary_array<value_type2, DerivedPolicy> rhs2(exec, middle2, last2);
thrust::merge_by_key(exec,
lhs1.begin(), lhs1.end(),
rhs1.begin(), rhs1.end(),
lhs2.begin(), rhs2.begin(),
first1, first2,
comp);
}
template<typename RandomAccessIterator,
typename Size,
typename StrictWeakOrdering>
__host__ __device__
void insertion_sort_each(RandomAccessIterator first,
RandomAccessIterator last,
Size partition_size,
StrictWeakOrdering comp)
{
if(partition_size > 1)
{
for(; first < last; first += partition_size)
{
RandomAccessIterator partition_last = thrust::min(last, first + partition_size);
thrust::system::detail::sequential::insertion_sort(first, partition_last, comp);
} // end for
} // end if
} // end insertion_sort_each()
template<typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename Size,
typename StrictWeakOrdering>
__host__ __device__
void insertion_sort_each_by_key(RandomAccessIterator1 keys_first,
RandomAccessIterator1 keys_last,
RandomAccessIterator2 values_first,
Size partition_size,
StrictWeakOrdering comp)
{
if(partition_size > 1)
{
for(; keys_first < keys_last; keys_first += partition_size, values_first += partition_size)
{
RandomAccessIterator1 keys_partition_last = thrust::min(keys_last, keys_first + partition_size);
thrust::system::detail::sequential::insertion_sort_by_key(keys_first, keys_partition_last, values_first, comp);
} // end for
} // end if
} // end insertion_sort_each()
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename Size,
typename RandomAccessIterator2,
typename StrictWeakOrdering>
__host__ __device__
void merge_adjacent_partitions(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 first,
RandomAccessIterator1 last,
Size partition_size,
RandomAccessIterator2 result,
StrictWeakOrdering comp)
{
for(; first < last; first += 2 * partition_size, result += 2 * partition_size)
{
RandomAccessIterator1 interval_middle = thrust::min(last, first + partition_size);
RandomAccessIterator1 interval_last = thrust::min(last, interval_middle + partition_size);
thrust::merge(exec,
first, interval_middle,
interval_middle, interval_last,
result,
comp);
} // end for
} // end merge_adjacent_partitions()
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename Size,
typename RandomAccessIterator3,
typename RandomAccessIterator4,
typename StrictWeakOrdering>
__host__ __device__
void merge_adjacent_partitions_by_key(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 keys_first,
RandomAccessIterator1 keys_last,
RandomAccessIterator2 values_first,
Size partition_size,
RandomAccessIterator3 keys_result,
RandomAccessIterator4 values_result,
StrictWeakOrdering comp)
{
Size stride = 2 * partition_size;
for(;
keys_first < keys_last;
keys_first += stride, values_first += stride, keys_result += stride, values_result += stride)
{
RandomAccessIterator1 keys_interval_middle = thrust::min(keys_last, keys_first + partition_size);
RandomAccessIterator1 keys_interval_last = thrust::min(keys_last, keys_interval_middle + partition_size);
RandomAccessIterator2 values_first2 = values_first + (keys_interval_middle - keys_first);
thrust::merge_by_key(exec,
keys_first, keys_interval_middle,
keys_interval_middle, keys_interval_last,
values_first,
values_first2,
keys_result,
values_result,
comp);
} // end for
} // end merge_adjacent_partitions()
template<typename DerivedPolicy,
typename RandomAccessIterator,
typename StrictWeakOrdering>
__host__ __device__
void iterative_stable_merge_sort(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator first,
RandomAccessIterator last,
StrictWeakOrdering comp)
{
typedef typename thrust::iterator_value<RandomAccessIterator>::type value_type;
typedef typename thrust::iterator_difference<RandomAccessIterator>::type difference_type;
difference_type n = last - first;
thrust::detail::temporary_array<value_type, DerivedPolicy> temp(exec, n);
// insertion sort each 32 element partition
difference_type partition_size = 32;
insertion_sort_each(first, last, partition_size, comp);
// ping indicates whether or not the latest data is in the source range [first, last)
bool ping = true;
// merge adjacent partitions until the partition size covers the entire range
for(;
partition_size < n;
partition_size *= 2, ping = !ping)
{
if(ping)
{
merge_adjacent_partitions(exec, first, last, partition_size, temp.begin(), comp);
} // end if
else
{
merge_adjacent_partitions(exec, temp.begin(), temp.end(), partition_size, first, comp);
} // end else
} // end for m
if(!ping)
{
thrust::copy(exec, temp.begin(), temp.end(), first);
} // end if
} // end iterative_stable_merge_sort()
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename StrictWeakOrdering>
__host__ __device__
void iterative_stable_merge_sort_by_key(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 keys_first,
RandomAccessIterator1 keys_last,
RandomAccessIterator2 values_first,
StrictWeakOrdering comp)
{
typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type1;
typedef typename thrust::iterator_value<RandomAccessIterator2>::type value_type2;
typedef typename thrust::iterator_difference<RandomAccessIterator1>::type difference_type;
difference_type n = keys_last - keys_first;
thrust::detail::temporary_array<value_type1, DerivedPolicy> keys_temp(exec, n);
thrust::detail::temporary_array<value_type2, DerivedPolicy> values_temp(exec, n);
// insertion sort each 32 element partition
difference_type partition_size = 32;
insertion_sort_each_by_key(keys_first, keys_last, values_first, partition_size, comp);
// ping indicates whether or not the latest data is in the source range [first, last)
bool ping = true;
// merge adjacent partitions until the partition size covers the entire range
for(;
partition_size < n;
partition_size *= 2, ping = !ping)
{
if(ping)
{
merge_adjacent_partitions_by_key(exec, keys_first, keys_last, values_first, partition_size, keys_temp.begin(), values_temp.begin(), comp);
} // end if
else
{
merge_adjacent_partitions_by_key(exec, keys_temp.begin(), keys_temp.end(), values_temp.begin(), partition_size, keys_first, values_first, comp);
} // end else
} // end for m
if(!ping)
{
thrust::copy(exec, keys_temp.begin(), keys_temp.end(), keys_first);
thrust::copy(exec, values_temp.begin(), values_temp.end(), values_first);
} // end if
} // end iterative_stable_merge_sort()
template<typename DerivedPolicy,
typename RandomAccessIterator,
typename StrictWeakOrdering>
__host__ __device__
void recursive_stable_merge_sort(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator first,
RandomAccessIterator last,
StrictWeakOrdering comp)
{
if(last - first <= 32)
{
thrust::system::detail::sequential::insertion_sort(first, last, comp);
} // end if
else
{
RandomAccessIterator middle = first + (last - first) / 2;
stable_merge_sort_detail::recursive_stable_merge_sort(exec, first, middle, comp);
stable_merge_sort_detail::recursive_stable_merge_sort(exec, middle, last, comp);
stable_merge_sort_detail::inplace_merge(exec, first, middle, last, comp);
} // end else
} // end recursive_stable_merge_sort()
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename StrictWeakOrdering>
__host__ __device__
void recursive_stable_merge_sort_by_key(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 first1,
RandomAccessIterator1 last1,
RandomAccessIterator2 first2,
StrictWeakOrdering comp)
{
if(last1 - first1 <= 32)
{
thrust::system::detail::sequential::insertion_sort_by_key(first1, last1, first2, comp);
} // end if
else
{
RandomAccessIterator1 middle1 = first1 + (last1 - first1) / 2;
RandomAccessIterator2 middle2 = first2 + (last1 - first1) / 2;
stable_merge_sort_detail::recursive_stable_merge_sort_by_key(exec, first1, middle1, first2, comp);
stable_merge_sort_detail::recursive_stable_merge_sort_by_key(exec, middle1, last1, middle2, comp);
stable_merge_sort_detail::inplace_merge_by_key(exec, first1, middle1, last1, first2, comp);
} // end else
} // end recursive_stable_merge_sort_by_key()
} // end namespace stable_merge_sort_detail
template<typename DerivedPolicy,
typename RandomAccessIterator,
typename StrictWeakOrdering>
__host__ __device__
void stable_merge_sort(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator first,
RandomAccessIterator last,
StrictWeakOrdering comp)
{
// avoid recursion in CUDA threads
#ifdef __CUDA_ARCH__
stable_merge_sort_detail::iterative_stable_merge_sort(exec, first, last, comp);
#else
stable_merge_sort_detail::recursive_stable_merge_sort(exec, first, last, comp);
#endif
}
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename StrictWeakOrdering>
__host__ __device__
void stable_merge_sort_by_key(sequential::execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 first1,
RandomAccessIterator1 last1,
RandomAccessIterator2 first2,
StrictWeakOrdering comp)
{
// avoid recursion in CUDA threads
#ifdef __CUDA_ARCH__
stable_merge_sort_detail::iterative_stable_merge_sort_by_key(exec, first1, last1, first2, comp);
#else
stable_merge_sort_detail::recursive_stable_merge_sort_by_key(exec, first1, last1, first2, comp);
#endif
}
} // end namespace sequential
} // end namespace detail
} // end namespace system
} // end namespace thrust
<|endoftext|>
|
<commit_before>/*
*
* Copyright (C) 2004 Mekensleep
*
* Mekensleep
* 24 rue vieille du temple
* 75004 Paris
* licensing@mekensleep.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 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
*
* Author:
* Igor Kravtchenko <igor@obraz.net>
*
*/
#include "hdrloader.h"
#include <math.h>
#include <memory.h>
#include <stdio.h>
#include <osgDB/FileUtils>
typedef unsigned char RGBE[4];
#define R 0
#define G 1
#define B 2
#define E 3
#define MINELEN 8 // minimum scanline length for encoding
#define MAXELEN 0x7fff // maximum scanline length for encoding
static void rawRGBEData(RGBE *scan, int len, float *cols);
static void workOnRGBE(RGBE *scan, int len, float *cols);
static bool decrunch(RGBE *scanline, int len, FILE *file);
static bool oldDecrunch(RGBE *scanline, int len, FILE *file);
bool HDRLoader::isHDRFile(const char *_fileName)
{
FILE *file;
file = osgDB::fopen(_fileName, "rb");
if (!file)
return false;
char str[10];
fread(str, 10, 1, file);
fclose(file);
if (memcmp(str, "#?RADIANCE", 10) && memcmp(str, "#?RGBE", 6))
return false;
return true;
}
bool HDRLoader::load(const char *_fileName, const bool _rawRGBE, HDRLoaderResult &_res)
{
int i;
char str[200];
FILE *file;
file = osgDB::fopen(_fileName, "rb");
if (!file)
return false;
fread(str, 10, 1, file);
if (memcmp(str, "#?RADIANCE", 10)) {
fseek(file, 0, SEEK_SET);
fread(str, 6, 1, file);
if (memcmp(str, "#?RGBE", 6)) {
fclose(file);
return false;
}
}
fseek(file, 1, SEEK_CUR);
char cmd[2000];
i = 0;
char c = 0, oldc;
while(true) {
oldc = c;
c = fgetc(file);
if (c == 0xa && oldc == 0xa)
break;
cmd[i++] = c;
}
char reso[2000];
i = 0;
while(true) {
c = fgetc(file);
reso[i++] = c;
if (c == 0xa)
break;
}
int w, h;
if (!sscanf(reso, "-Y %d +X %d", &h, &w)) {
fclose(file);
return false;
}
_res.width = w;
_res.height = h;
int components = _rawRGBE ? 4 : 3;
float *cols = new float[w * h * components];
_res.cols = cols;
RGBE *scanline = new RGBE[w];
if (!scanline) {
fclose(file);
return false;
}
// convert image
cols += (h-1) * w * components;
for (int y = h - 1; y >= 0; y--) {
if (decrunch(scanline, w, file) == false)
break;
if (_rawRGBE)
rawRGBEData(scanline, w, cols);
else
workOnRGBE(scanline, w, cols);
cols -= w * components;
}
delete [] scanline;
fclose(file);
return true;
}
void rawRGBEData(RGBE *_scan, int _len, float *_cols)
{
int ii = 0;
while (_len-- > 0) {
_cols[0] = _scan[0][R] / 255.0f;
_cols[1] = _scan[0][G] / 255.0f;
_cols[2] = _scan[0][B] / 255.0f;
_cols[3] = _scan[0][E] / 255.0f;
_cols += 4;
_scan++;
ii++;
}
}
inline float convertComponent(int _expo, int _val)
{
return static_cast<float>(ldexp( static_cast<float>(_val), _expo-8));
}
void workOnRGBE(RGBE *_scan, int _len, float *_cols)
{
int ii = 0;
while (_len-- > 0) {
int expo = _scan[0][E] - 128;
_cols[0] = convertComponent(expo, _scan[0][R]);
_cols[1] = convertComponent(expo, _scan[0][G]);
_cols[2] = convertComponent(expo, _scan[0][B]);
_cols += 3;
_scan++;
ii++;
}
}
bool decrunch(RGBE *_scanline, int _len, FILE *_file)
{
int i, j;
if (_len < MINELEN || _len > MAXELEN)
return oldDecrunch(_scanline, _len, _file);
i = fgetc(_file);
if (i != 2) {
fseek(_file, -1, SEEK_CUR);
return oldDecrunch(_scanline, _len, _file);
}
_scanline[0][G] = fgetc(_file);
_scanline[0][B] = fgetc(_file);
i = fgetc(_file);
if (_scanline[0][G] != 2 || _scanline[0][B] & 128) {
_scanline[0][R] = 2;
_scanline[0][E] = i;
return oldDecrunch(_scanline + 1, _len - 1, _file);
}
// read each component
for (i = 0; i < 4; i++) {
for (j = 0; j < _len; ) {
unsigned char code = fgetc(_file);
if (code > 128) { // run
code &= 127;
unsigned char val = fgetc(_file);
while (code--)
_scanline[j++][i] = val;
}
else { // non-run
while(code--)
_scanline[j++][i] = fgetc(_file);
}
}
}
return feof(_file) ? false : true;
}
bool oldDecrunch(RGBE *_scanline, int _len, FILE *_file)
{
int i;
int rshift = 0;
while (_len > 0) {
_scanline[0][R] = fgetc(_file);
_scanline[0][G] = fgetc(_file);
_scanline[0][B] = fgetc(_file);
_scanline[0][E] = fgetc(_file);
if (feof(_file))
return false;
if (_scanline[0][R] == 1 &&
_scanline[0][G] == 1 &&
_scanline[0][B] == 1) {
for (i = _scanline[0][E] << rshift; i > 0; i--) {
memcpy(&_scanline[0][0], &_scanline[-1][0], 4);
_scanline++;
_len--;
}
rshift += 8;
}
else {
_scanline++;
_len--;
rshift = 0;
}
}
return true;
}
<commit_msg>Fixed warnings<commit_after>/*
*
* Copyright (C) 2004 Mekensleep
*
* Mekensleep
* 24 rue vieille du temple
* 75004 Paris
* licensing@mekensleep.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 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
*
* Author:
* Igor Kravtchenko <igor@obraz.net>
*
*/
#include "hdrloader.h"
#include <math.h>
#include <memory.h>
#include <stdio.h>
#include <osgDB/FileUtils>
typedef unsigned char RGBE[4];
#define R 0
#define G 1
#define B 2
#define E 3
#define MINELEN 8 // minimum scanline length for encoding
#define MAXELEN 0x7fff // maximum scanline length for encoding
static void rawRGBEData(RGBE *scan, int len, float *cols);
static void workOnRGBE(RGBE *scan, int len, float *cols);
static bool decrunch(RGBE *scanline, int len, FILE *file);
static bool oldDecrunch(RGBE *scanline, int len, FILE *file);
bool HDRLoader::isHDRFile(const char *_fileName)
{
FILE *file;
file = osgDB::fopen(_fileName, "rb");
if (!file)
return false;
char str[10];
size_t numRead = fread(str, 10, 1, file);
fclose(file);
if (numRead<10) return false;
if (memcmp(str, "#?RADIANCE", 10) && memcmp(str, "#?RGBE", 6))
return false;
return true;
}
bool HDRLoader::load(const char *_fileName, const bool _rawRGBE, HDRLoaderResult &_res)
{
int i;
char str[200];
FILE *file;
file = osgDB::fopen(_fileName, "rb");
if (!file)
return false;
size_t numRead = fread(str, 10, 1, file);
if (numRead<10)
{
fclose(file);
return false;
}
if (memcmp(str, "#?RADIANCE", 10))
{
fseek(file, 0, SEEK_SET);
numRead = fread(str, 6, 1, file);
if (numRead<6 || memcmp(str, "#?RGBE", 6))
{
fclose(file);
return false;
}
}
fseek(file, 1, SEEK_CUR);
char cmd[2000];
i = 0;
char c = 0, oldc;
while(true) {
oldc = c;
c = fgetc(file);
if (c == 0xa && oldc == 0xa)
break;
cmd[i++] = c;
}
char reso[2000];
i = 0;
while(true) {
c = fgetc(file);
reso[i++] = c;
if (c == 0xa)
break;
}
int w, h;
if (!sscanf(reso, "-Y %d +X %d", &h, &w)) {
fclose(file);
return false;
}
_res.width = w;
_res.height = h;
int components = _rawRGBE ? 4 : 3;
float *cols = new float[w * h * components];
_res.cols = cols;
RGBE *scanline = new RGBE[w];
if (!scanline) {
fclose(file);
return false;
}
// convert image
cols += (h-1) * w * components;
for (int y = h - 1; y >= 0; y--) {
if (decrunch(scanline, w, file) == false)
break;
if (_rawRGBE)
rawRGBEData(scanline, w, cols);
else
workOnRGBE(scanline, w, cols);
cols -= w * components;
}
delete [] scanline;
fclose(file);
return true;
}
void rawRGBEData(RGBE *_scan, int _len, float *_cols)
{
int ii = 0;
while (_len-- > 0) {
_cols[0] = _scan[0][R] / 255.0f;
_cols[1] = _scan[0][G] / 255.0f;
_cols[2] = _scan[0][B] / 255.0f;
_cols[3] = _scan[0][E] / 255.0f;
_cols += 4;
_scan++;
ii++;
}
}
inline float convertComponent(int _expo, int _val)
{
return static_cast<float>(ldexp( static_cast<float>(_val), _expo-8));
}
void workOnRGBE(RGBE *_scan, int _len, float *_cols)
{
int ii = 0;
while (_len-- > 0) {
int expo = _scan[0][E] - 128;
_cols[0] = convertComponent(expo, _scan[0][R]);
_cols[1] = convertComponent(expo, _scan[0][G]);
_cols[2] = convertComponent(expo, _scan[0][B]);
_cols += 3;
_scan++;
ii++;
}
}
bool decrunch(RGBE *_scanline, int _len, FILE *_file)
{
int i, j;
if (_len < MINELEN || _len > MAXELEN)
return oldDecrunch(_scanline, _len, _file);
i = fgetc(_file);
if (i != 2) {
fseek(_file, -1, SEEK_CUR);
return oldDecrunch(_scanline, _len, _file);
}
_scanline[0][G] = fgetc(_file);
_scanline[0][B] = fgetc(_file);
i = fgetc(_file);
if (_scanline[0][G] != 2 || _scanline[0][B] & 128) {
_scanline[0][R] = 2;
_scanline[0][E] = i;
return oldDecrunch(_scanline + 1, _len - 1, _file);
}
// read each component
for (i = 0; i < 4; i++) {
for (j = 0; j < _len; ) {
unsigned char code = fgetc(_file);
if (code > 128) { // run
code &= 127;
unsigned char val = fgetc(_file);
while (code--)
_scanline[j++][i] = val;
}
else { // non-run
while(code--)
_scanline[j++][i] = fgetc(_file);
}
}
}
return feof(_file) ? false : true;
}
bool oldDecrunch(RGBE *_scanline, int _len, FILE *_file)
{
int i;
int rshift = 0;
while (_len > 0) {
_scanline[0][R] = fgetc(_file);
_scanline[0][G] = fgetc(_file);
_scanline[0][B] = fgetc(_file);
_scanline[0][E] = fgetc(_file);
if (feof(_file))
return false;
if (_scanline[0][R] == 1 &&
_scanline[0][G] == 1 &&
_scanline[0][B] == 1) {
for (i = _scanline[0][E] << rshift; i > 0; i--) {
memcpy(&_scanline[0][0], &_scanline[-1][0], 4);
_scanline++;
_len--;
}
rshift += 8;
}
else {
_scanline++;
_len--;
rshift = 0;
}
}
return true;
}
<|endoftext|>
|
<commit_before>#include "qt/editor_dialog.hpp"
#include "search/result.hpp"
#include "indexer/classificator.hpp"
#include "indexer/feature.hpp"
#include "indexer/osm_editor.hpp"
#include "base/collection_cast.hpp"
#include "std/set.hpp"
#include "std/vector.hpp"
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QVBoxLayout>
#include <QtCore/QSignalMapper>
using feature::Metadata;
EditorDialog::EditorDialog(QWidget * parent, FeatureType const & feature) : QDialog(parent)
{
QVBoxLayout * vLayout = new QVBoxLayout();
// First uneditable row: feature types.
string strTypes;
feature.ForEachType([&strTypes](uint32_t type)
{
strTypes += classif().GetReadableObjectName(type) + " ";
});
QHBoxLayout * typesRow = new QHBoxLayout();
typesRow->addWidget(new QLabel("Types:"));
typesRow->addWidget(new QLabel(QString::fromStdString(strTypes)));
vLayout->addLayout(typesRow);
if (osm::Editor::Instance().IsNameEditable(feature))
{
// Rows block: Name(s) label(s) and text input.
char const * defaultLangStr = StringUtf8Multilang::GetLangByCode(StringUtf8Multilang::DEFAULT_CODE);
// Default name editor is always displayed, even if feature name is empty.
QHBoxLayout * defaultNameRow = new QHBoxLayout();
defaultNameRow->addWidget(new QLabel(QString("Name:")));
QLineEdit * defaultNamelineEdit = new QLineEdit();
defaultNamelineEdit->setObjectName(defaultLangStr);
defaultNameRow->addWidget(defaultNamelineEdit);
vLayout->addLayout(defaultNameRow);
feature.ForEachNameRef([&vLayout, &defaultNamelineEdit](int8_t langCode, string const & name) -> bool
{
if (langCode == StringUtf8Multilang::DEFAULT_CODE)
defaultNamelineEdit->setText(QString::fromStdString(name));
else
{
QHBoxLayout * nameRow = new QHBoxLayout();
char const * langStr = StringUtf8Multilang::GetLangByCode(langCode);
nameRow->addWidget(new QLabel(QString("Name:") + langStr));
QLineEdit * lineEditName = new QLineEdit(QString::fromStdString(name));
lineEditName->setObjectName(langStr);
nameRow->addWidget(lineEditName);
vLayout->addLayout(nameRow);
}
return true; // true is needed to enumerate all languages.
});
}
// All metadata rows.
QVBoxLayout * metaRows = new QVBoxLayout();
// Features can have several types, so we merge all editable fields here.
set<Metadata::EType> const editableMetadataFields =
// TODO(mgsergio, Alex): Maybe just return set in EditableMetadataForType?
my::collection_cast<set>(osm::Editor::Instance().EditableMetadataForType(feature));
for (Metadata::EType const field : editableMetadataFields)
{
QString const fieldName = QString::fromStdString(DebugPrint(field));
QHBoxLayout * fieldRow = new QHBoxLayout();
fieldRow->addWidget(new QLabel(fieldName + ":"));
QLineEdit * lineEdit = new QLineEdit(QString::fromStdString(feature.GetMetadata().Get(field)));
// Mark line editor to query it's text value when editing is finished.
lineEdit->setObjectName(fieldName);
fieldRow->addWidget(lineEdit);
metaRows->addLayout(fieldRow);
}
vLayout->addLayout(metaRows);
// Dialog buttons.
QDialogButtonBox * buttonBox = new QDialogButtonBox(
QDialogButtonBox::Cancel | QDialogButtonBox::Save);
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
// Delete button should send custom int return value from dialog.
QPushButton * deletePOIButton = new QPushButton("Delete POI");
QSignalMapper * signalMapper = new QSignalMapper();
connect(deletePOIButton, SIGNAL(clicked()), signalMapper, SLOT(map()));
signalMapper->setMapping(deletePOIButton, QDialogButtonBox::DestructiveRole);
connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(done(int)));
buttonBox->addButton(deletePOIButton, QDialogButtonBox::DestructiveRole);
QHBoxLayout * buttonsRowLayout = new QHBoxLayout();
buttonsRowLayout->addWidget(buttonBox);
vLayout->addLayout(buttonsRowLayout);
setLayout(vLayout);
setWindowTitle("POI Editor");
}
StringUtf8Multilang EditorDialog::GetEditedNames() const
{
StringUtf8Multilang names;
for (int8_t langCode = StringUtf8Multilang::DEFAULT_CODE; langCode < StringUtf8Multilang::MAX_SUPPORTED_LANGUAGES; ++langCode)
{
QLineEdit * le = findChild<QLineEdit *>(StringUtf8Multilang::GetLangByCode(langCode));
if (!le)
continue;
string const name = le->text().toStdString();
if (!name.empty())
names.AddString(langCode, name);
}
return names;
}
Metadata EditorDialog::GetEditedMetadata() const
{
Metadata metadata;
for (int type = Metadata::FMD_CUISINE; type < Metadata::FMD_COUNT; ++type)
{
QLineEdit * editor = findChild<QLineEdit *>(QString::fromStdString(DebugPrint(static_cast<Metadata::EType>(type))));
if (editor)
metadata.Set(static_cast<Metadata::EType>(type), editor->text().toStdString());
}
return metadata;
}
<commit_msg>[editor] Avoid unnecessary container cast.<commit_after>#include "qt/editor_dialog.hpp"
#include "search/result.hpp"
#include "indexer/classificator.hpp"
#include "indexer/feature.hpp"
#include "indexer/osm_editor.hpp"
#include "base/collection_cast.hpp"
#include "std/set.hpp"
#include "std/vector.hpp"
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QVBoxLayout>
#include <QtCore/QSignalMapper>
using feature::Metadata;
EditorDialog::EditorDialog(QWidget * parent, FeatureType const & feature) : QDialog(parent)
{
QVBoxLayout * vLayout = new QVBoxLayout();
// First uneditable row: feature types.
string strTypes;
feature.ForEachType([&strTypes](uint32_t type)
{
strTypes += classif().GetReadableObjectName(type) + " ";
});
QHBoxLayout * typesRow = new QHBoxLayout();
typesRow->addWidget(new QLabel("Types:"));
typesRow->addWidget(new QLabel(QString::fromStdString(strTypes)));
vLayout->addLayout(typesRow);
if (osm::Editor::Instance().IsNameEditable(feature))
{
// Rows block: Name(s) label(s) and text input.
char const * defaultLangStr = StringUtf8Multilang::GetLangByCode(StringUtf8Multilang::DEFAULT_CODE);
// Default name editor is always displayed, even if feature name is empty.
QHBoxLayout * defaultNameRow = new QHBoxLayout();
defaultNameRow->addWidget(new QLabel(QString("Name:")));
QLineEdit * defaultNamelineEdit = new QLineEdit();
defaultNamelineEdit->setObjectName(defaultLangStr);
defaultNameRow->addWidget(defaultNamelineEdit);
vLayout->addLayout(defaultNameRow);
feature.ForEachNameRef([&vLayout, &defaultNamelineEdit](int8_t langCode, string const & name) -> bool
{
if (langCode == StringUtf8Multilang::DEFAULT_CODE)
defaultNamelineEdit->setText(QString::fromStdString(name));
else
{
QHBoxLayout * nameRow = new QHBoxLayout();
char const * langStr = StringUtf8Multilang::GetLangByCode(langCode);
nameRow->addWidget(new QLabel(QString("Name:") + langStr));
QLineEdit * lineEditName = new QLineEdit(QString::fromStdString(name));
lineEditName->setObjectName(langStr);
nameRow->addWidget(lineEditName);
vLayout->addLayout(nameRow);
}
return true; // true is needed to enumerate all languages.
});
}
// All metadata rows.
QVBoxLayout * metaRows = new QVBoxLayout();
vector<Metadata::EType> const editableMetadataFields = editor.EditableMetadataForType(feature);
for (Metadata::EType const field : editableMetadataFields)
{
QString const fieldName = QString::fromStdString(DebugPrint(field));
QHBoxLayout * fieldRow = new QHBoxLayout();
fieldRow->addWidget(new QLabel(fieldName + ":"));
QLineEdit * lineEdit = new QLineEdit(QString::fromStdString(feature.GetMetadata().Get(field)));
// Mark line editor to query it's text value when editing is finished.
lineEdit->setObjectName(fieldName);
fieldRow->addWidget(lineEdit);
metaRows->addLayout(fieldRow);
}
vLayout->addLayout(metaRows);
// Dialog buttons.
QDialogButtonBox * buttonBox = new QDialogButtonBox(
QDialogButtonBox::Cancel | QDialogButtonBox::Save);
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
// Delete button should send custom int return value from dialog.
QPushButton * deletePOIButton = new QPushButton("Delete POI");
QSignalMapper * signalMapper = new QSignalMapper();
connect(deletePOIButton, SIGNAL(clicked()), signalMapper, SLOT(map()));
signalMapper->setMapping(deletePOIButton, QDialogButtonBox::DestructiveRole);
connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(done(int)));
buttonBox->addButton(deletePOIButton, QDialogButtonBox::DestructiveRole);
QHBoxLayout * buttonsRowLayout = new QHBoxLayout();
buttonsRowLayout->addWidget(buttonBox);
vLayout->addLayout(buttonsRowLayout);
setLayout(vLayout);
setWindowTitle("POI Editor");
}
StringUtf8Multilang EditorDialog::GetEditedNames() const
{
StringUtf8Multilang names;
for (int8_t langCode = StringUtf8Multilang::DEFAULT_CODE; langCode < StringUtf8Multilang::MAX_SUPPORTED_LANGUAGES; ++langCode)
{
QLineEdit * le = findChild<QLineEdit *>(StringUtf8Multilang::GetLangByCode(langCode));
if (!le)
continue;
string const name = le->text().toStdString();
if (!name.empty())
names.AddString(langCode, name);
}
return names;
}
Metadata EditorDialog::GetEditedMetadata() const
{
Metadata metadata;
for (int type = Metadata::FMD_CUISINE; type < Metadata::FMD_COUNT; ++type)
{
QLineEdit * editor = findChild<QLineEdit *>(QString::fromStdString(DebugPrint(static_cast<Metadata::EType>(type))));
if (editor)
metadata.Set(static_cast<Metadata::EType>(type), editor->text().toStdString());
}
return metadata;
}
<|endoftext|>
|
<commit_before>#ifndef STAN_MATH_PRIM_ARR_FUN_APPEND_ARRAY_HPP
#define STAN_MATH_PRIM_ARR_FUN_APPEND_ARRAY_HPP
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/scal/meta/is_vector_like.hpp>
#include <stan/math/prim/scal/meta/return_type.hpp>
#include <boost/math/tools/promotion.hpp>
#include <boost/utility/enable_if.hpp>
#include <vector>
namespace stan {
namespace math {
/**
* Return the concatenation of two specified integer vectors in the
* order of the arguments.
*
* @param x First vector
* @param y Second vector
* @return A vector of x and y concatenated together (in that order)
*/
inline std::vector<int>
append_array(const std::vector<int>& x, const std::vector<int>& y) {
std::vector<int> z;
z.reserve(x.size() + y.size());
z.insert(z.end(), x.begin(), x.end());
z.insert(z.end(), y.begin(), y.end());
return z;
}
/**
* Return the concatenation of two vectors containing Matrices
* of the same type in the order of the arguments.
*
* @tparam T1 Type of element in Matrices in first vector
* @tparam T2 Type of element in Matrices in second vector
* @tparam R Row specification of matrices
* @tparam C Column specification of matrices
* @param x First vector
* @param y Second vector
* @return A vector of x and y concatenated together (in that order)
*/
template <typename T1, typename T2, int R, int C>
inline std::vector<Eigen::Matrix<typename return_type<T1, T2>::type, R, C> >
append_array(const std::vector<Eigen::Matrix<T1, R, C> >& x,
const std::vector<Eigen::Matrix<T2, R, C> >& y) {
if (!x.empty() && !y.empty()) {
check_matching_dims("append_array",
"x[1]",
x.front(),
"y[1]",
y.front());
}
std::vector<Eigen::Matrix<typename return_type<T1, T2>::type, R, C> > z;
z.reserve(x.size() + y.size());
for (size_t i = 0; i < x.size(); i++)
z.push_back(x[i].template cast<typename return_type<T1, T2>::type>());
for (size_t i = 0; i < y.size(); i++)
z.push_back(y[i].template cast<typename return_type<T1, T2>::type>());
return z;
}
/**
* Return the concatenation of two specified vectors in the order of
* the arguments. The types in each vector must not be vector-like
* themselves.
*
* @tparam T1 Scalar type of first vector
* @tparam T2 Scalar Type of second vector
* @param x First vector
* @param y Second vector
* @return A vector of x and y concatenated together (in that order)
*/
template <typename T1, typename T2>
inline typename
boost::disable_if_c<is_vector_like<T1>::value || is_vector_like<T2>::value,
std::vector<typename return_type<T1, T2>::type> >::type
append_array(const std::vector<T1>& x, const std::vector<T2>& y) {
std::vector<typename boost::math::tools::promote_args<T1, T2>::type> z;
z.reserve(x.size() + y.size());
z.insert(z.end(), x.begin(), x.end());
z.insert(z.end(), y.begin(), y.end());
return z;
}
}
}
#endif
<commit_msg>Removed code that make append_array only work for scalar types (Issue 481)<commit_after>#ifndef STAN_MATH_PRIM_ARR_FUN_APPEND_ARRAY_HPP
#define STAN_MATH_PRIM_ARR_FUN_APPEND_ARRAY_HPP
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/scal/meta/return_type.hpp>
#include <vector>
namespace stan {
namespace math {
/**
* Return the concatenation of two specified integer vectors in the
* order of the arguments.
*
* @param x First vector
* @param y Second vector
* @return A vector of x and y concatenated together (in that order)
*/
inline std::vector<int>
append_array(const std::vector<int>& x, const std::vector<int>& y) {
std::vector<int> z;
z.reserve(x.size() + y.size());
z.insert(z.end(), x.begin(), x.end());
z.insert(z.end(), y.begin(), y.end());
return z;
}
/**
* Return the concatenation of two vectors containing Matrices
* of the same type in the order of the arguments.
*
* @tparam T1 Type of element in Matrices in first vector
* @tparam T2 Type of element in Matrices in second vector
* @tparam R Row specification of matrices
* @tparam C Column specification of matrices
* @param x First vector
* @param y Second vector
* @return A vector of x and y concatenated together (in that order)
*/
template <typename T1, typename T2, int R, int C>
inline std::vector<Eigen::Matrix<typename return_type<T1, T2>::type, R, C> >
append_array(const std::vector<Eigen::Matrix<T1, R, C> >& x,
const std::vector<Eigen::Matrix<T2, R, C> >& y) {
if (!x.empty() && !y.empty()) {
check_matching_dims("append_array",
"x[1]",
x.front(),
"y[1]",
y.front());
}
std::vector<Eigen::Matrix<typename return_type<T1, T2>::type, R, C> > z;
z.reserve(x.size() + y.size());
for (size_t i = 0; i < x.size(); i++)
z.push_back(x[i].template cast<typename return_type<T1, T2>::type>());
for (size_t i = 0; i < y.size(); i++)
z.push_back(y[i].template cast<typename return_type<T1, T2>::type>());
return z;
}
/**
* Return the concatenation of two specified vectors in the order of
* the arguments.
*
* @tparam T1 Scalar type of first vector
* @tparam T2 Scalar type of second vector
* @param x First vector
* @param y Second vector
* @return A vector of x and y concatenated together (in that order)
*/
template <typename T1, typename T2>
inline typename std::vector<typename return_type<T1, T2>::type>
append_array(const std::vector<T1>& x, const std::vector<T2>& y) {
std::vector<typename return_type<T1, T2>::type> z;
z.reserve(x.size() + y.size());
z.insert(z.end(), x.begin(), x.end());
z.insert(z.end(), y.begin(), y.end());
return z;
}
}
}
#endif
<|endoftext|>
|
<commit_before>#include "SparseSideInfo.h"
#include "linop.h"
#include <SmurffCpp/Utils/MatrixUtils.h>
#include <vector>
namespace smurff {
SparseSideInfo::SparseSideInfo(const DataConfig &mc) {
F = mc.getSparseMatrixData();
Ft = F.transpose();
}
SparseSideInfo::~SparseSideInfo() {}
int SparseSideInfo::cols() const
{
return F.cols();
}
int SparseSideInfo::rows() const
{
return F.rows();
}
std::ostream& SparseSideInfo::print(std::ostream &os) const
{
double percent = 100.8 * (double)F.nonZeros() / (double)F.rows() / (double) F.cols();
os << "SparseDouble " << F.nonZeros() << " [" << F.rows() << ", " << F.cols() << "] ("
<< percent << "%)" << std::endl;
return os;
}
bool SparseSideInfo::is_dense() const
{
return false;
}
void SparseSideInfo::compute_uhat(Matrix& uhat, Matrix& beta)
{
COUNTER("compute_uhat");
uhat = F * beta;
}
void SparseSideInfo::At_mul_A(Matrix& out)
{
COUNTER("At_mul_A");
out = Ft * F;
}
Matrix SparseSideInfo::A_mul_B(Matrix& A)
{
COUNTER("A_mul_B");
return F.transpose() * A;
}
int SparseSideInfo::solve_blockcg(Matrix& X, double reg, Matrix& B, double tol, const int blocksize, const int excess, bool throw_on_cholesky_error)
{
COUNTER("solve_blockcg");
return linop::solve_blockcg(X, *this, reg, B, tol, blocksize, excess, throw_on_cholesky_error);
#if 0
int iter1, iter2;
Matrix X1 = X;
{
COUNTER("eigen_cg");
linop::AtA A(F, reg);
Eigen::ConjugateGradient<linop::AtA, Eigen::Lower | Eigen::Upper> cg;
cg.setTolerance(tol);
cg.compute(A);
X1 = cg.solve(B.transpose()).transpose();
iter1 = cg.iterations();
SHOW(iter1);
SHOW((X1 - B).norm());
}
Matrix X2 = X;
{
COUNTER("smurff_cg");
iter2 = linop::solve_blockcg(X2, *this, reg, B, tol, blocksize, excess, throw_on_cholesky_error);
SHOW(iter2);
SHOW((X2 - B).norm());
}
SHOW((X2 - X1).norm());
return iter1;
#endif
}
Vector SparseSideInfo::col_square_sum()
{
COUNTER("col_square_sum");
// component-wise square
auto E = F.unaryExpr([](const float_type &d) { return d * d; });
// col-wise sum
return E.transpose() * Vector::Ones(E.rows()).transpose();
}
// Y = X[:,row]' * B'
void SparseSideInfo::At_mul_Bt(Vector& Y, const int row, Matrix& B)
{
COUNTER("At_mul_Bt");
Y = Ft.block(row, 0, row + 1, Ft.cols()) * B;
}
// computes Z += A[:,row] * b', where a and b are vectors
void SparseSideInfo::add_Acol_mul_bt(Matrix& Z, const int col, Vector& b)
{
COUNTER("add_Acol_mul_bt");
Z += F.col(col) * b;
}
} // end namespace smurff
<commit_msg>ENH: use row() instead of block()<commit_after>#include "SparseSideInfo.h"
#include "linop.h"
#include <SmurffCpp/Utils/MatrixUtils.h>
#include <vector>
namespace smurff {
SparseSideInfo::SparseSideInfo(const DataConfig &mc) {
F = mc.getSparseMatrixData();
Ft = F.transpose();
}
SparseSideInfo::~SparseSideInfo() {}
int SparseSideInfo::cols() const
{
return F.cols();
}
int SparseSideInfo::rows() const
{
return F.rows();
}
std::ostream& SparseSideInfo::print(std::ostream &os) const
{
double percent = 100.8 * (double)F.nonZeros() / (double)F.rows() / (double) F.cols();
os << "SparseDouble " << F.nonZeros() << " [" << F.rows() << ", " << F.cols() << "] ("
<< percent << "%)" << std::endl;
return os;
}
bool SparseSideInfo::is_dense() const
{
return false;
}
void SparseSideInfo::compute_uhat(Matrix& uhat, Matrix& beta)
{
COUNTER("compute_uhat");
uhat = F * beta;
}
void SparseSideInfo::At_mul_A(Matrix& out)
{
COUNTER("At_mul_A");
out = Ft * F;
}
Matrix SparseSideInfo::A_mul_B(Matrix& A)
{
COUNTER("A_mul_B");
return F.transpose() * A;
}
int SparseSideInfo::solve_blockcg(Matrix& X, double reg, Matrix& B, double tol, const int blocksize, const int excess, bool throw_on_cholesky_error)
{
COUNTER("solve_blockcg");
return linop::solve_blockcg(X, *this, reg, B, tol, blocksize, excess, throw_on_cholesky_error);
#if 0
int iter1, iter2;
Matrix X1 = X;
{
COUNTER("eigen_cg");
linop::AtA A(F, reg);
Eigen::ConjugateGradient<linop::AtA, Eigen::Lower | Eigen::Upper> cg;
cg.setTolerance(tol);
cg.compute(A);
X1 = cg.solve(B.transpose()).transpose();
iter1 = cg.iterations();
SHOW(iter1);
SHOW((X1 - B).norm());
}
Matrix X2 = X;
{
COUNTER("smurff_cg");
iter2 = linop::solve_blockcg(X2, *this, reg, B, tol, blocksize, excess, throw_on_cholesky_error);
SHOW(iter2);
SHOW((X2 - B).norm());
}
SHOW((X2 - X1).norm());
return iter1;
#endif
}
Vector SparseSideInfo::col_square_sum()
{
COUNTER("col_square_sum");
// component-wise square
auto E = F.unaryExpr([](const float_type &d) { return d * d; });
// col-wise sum
return E.transpose() * Vector::Ones(E.rows()).transpose();
}
// Y = X[:,row]' * B'
void SparseSideInfo::At_mul_Bt(Vector& Y, const int row, Matrix& B)
{
COUNTER("At_mul_Bt");
Y = Ft.row(row) * B;
}
// computes Z += A[:,row] * b', where a and b are vectors
void SparseSideInfo::add_Acol_mul_bt(Matrix& Z, const int col, Vector& b)
{
COUNTER("add_Acol_mul_bt");
Z += F.col(col) * b;
}
} // end namespace smurff
<|endoftext|>
|
<commit_before>/*
*
* Copyright (C) 2004 Mekensleep
*
* Mekensleep
* 24 rue vieille du temple
* 75004 Paris
* licensing@mekensleep.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 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
*
* Author:
* Igor Kravtchenko <igor@obraz.net>
*
*/
#include "hdrloader.h"
#include <math.h>
#include <memory.h>
#include <stdio.h>
typedef unsigned char RGBE[4];
#define R 0
#define G 1
#define B 2
#define E 3
#define MINELEN 8 // minimum scanline length for encoding
#define MAXELEN 0x7fff // maximum scanline length for encoding
static void workOnRGBE(RGBE *scan, int len, float *cols);
static bool decrunch(RGBE *scanline, int len, FILE *file);
static bool oldDecrunch(RGBE *scanline, int len, FILE *file);
bool HDRLoader::isHDRFile(const char *_fileName)
{
FILE *file;
file = fopen(_fileName, "rb");
if (!file)
return false;
char str[10];
fread(str, 10, 1, file);
fclose(file);
if (memcmp(str, "#?RADIANCE", 10) && memcmp(str, "#?RGBE", 6))
return false;
return true;
}
bool HDRLoader::load(const char *_fileName, HDRLoaderResult &_res)
{
int i;
char str[200];
FILE *file;
file = fopen(_fileName, "rb");
if (!file)
return false;
fread(str, 10, 1, file);
if (memcmp(str, "#?RADIANCE", 10)) {
fseek(file, 0, SEEK_SET);
fread(str, 6, 1, file);
if (memcmp(str, "#?RGBE", 6)) {
fclose(file);
return false;
}
}
fseek(file, 1, SEEK_CUR);
char cmd[2000];
i = 0;
char c = 0, oldc;
while(true) {
oldc = c;
c = fgetc(file);
if (c == 0xa && oldc == 0xa)
break;
cmd[i++] = c;
}
char reso[2000];
i = 0;
while(true) {
c = fgetc(file);
reso[i++] = c;
if (c == 0xa)
break;
}
int w, h;
if (!sscanf(reso, "-Y %d +X %d", &h, &w)) {
fclose(file);
return false;
}
_res.width = w;
_res.height = h;
float *cols = new float[w * h * 3];
_res.cols = cols;
RGBE *scanline = new RGBE[w];
if (!scanline) {
fclose(file);
return false;
}
// convert image
cols += (h-1) * w * 3;
for (int y = h - 1; y >= 0; y--) {
if (decrunch(scanline, w, file) == false)
break;
workOnRGBE(scanline, w, cols);
cols -= w * 3;
}
delete [] scanline;
fclose(file);
return true;
}
inline float convertComponent(int _expo, int _val)
{
return ldexp( _val, _expo-8);
}
void workOnRGBE(RGBE *_scan, int _len, float *_cols)
{
int ii = 0;
while (_len-- > 0) {
int expo = _scan[0][E] - 128;
_cols[0] = convertComponent(expo, _scan[0][R]);
_cols[1] = convertComponent(expo, _scan[0][G]);
_cols[2] = convertComponent(expo, _scan[0][B]);
_cols += 3;
_scan++;
ii++;
}
}
bool decrunch(RGBE *_scanline, int _len, FILE *_file)
{
int i, j;
if (_len < MINELEN || _len > MAXELEN)
return oldDecrunch(_scanline, _len, _file);
i = fgetc(_file);
if (i != 2) {
fseek(_file, -1, SEEK_CUR);
return oldDecrunch(_scanline, _len, _file);
}
_scanline[0][G] = fgetc(_file);
_scanline[0][B] = fgetc(_file);
i = fgetc(_file);
if (_scanline[0][G] != 2 || _scanline[0][B] & 128) {
_scanline[0][R] = 2;
_scanline[0][E] = i;
return oldDecrunch(_scanline + 1, _len - 1, _file);
}
// read each component
for (i = 0; i < 4; i++) {
for (j = 0; j < _len; ) {
unsigned char code = fgetc(_file);
if (code > 128) { // run
code &= 127;
unsigned char val = fgetc(_file);
while (code--)
_scanline[j++][i] = val;
}
else { // non-run
while(code--)
_scanline[j++][i] = fgetc(_file);
}
}
}
return feof(_file) ? false : true;
}
bool oldDecrunch(RGBE *_scanline, int _len, FILE *_file)
{
int i;
int rshift = 0;
while (_len > 0) {
_scanline[0][R] = fgetc(_file);
_scanline[0][G] = fgetc(_file);
_scanline[0][B] = fgetc(_file);
_scanline[0][E] = fgetc(_file);
if (feof(_file))
return false;
if (_scanline[0][R] == 1 &&
_scanline[0][G] == 1 &&
_scanline[0][B] == 1) {
for (i = _scanline[0][E] << rshift; i > 0; i--) {
memcpy(&_scanline[0][0], &_scanline[-1][0], 4);
_scanline++;
_len--;
}
rshift += 8;
}
else {
_scanline++;
_len--;
rshift = 0;
}
}
return true;
}
<commit_msg>From Mike Weiblen, fix for Win32 build<commit_after>/*
*
* Copyright (C) 2004 Mekensleep
*
* Mekensleep
* 24 rue vieille du temple
* 75004 Paris
* licensing@mekensleep.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 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
*
* Author:
* Igor Kravtchenko <igor@obraz.net>
*
*/
#include "hdrloader.h"
#include <math.h>
#include <memory.h>
#include <stdio.h>
typedef unsigned char RGBE[4];
#define R 0
#define G 1
#define B 2
#define E 3
#define MINELEN 8 // minimum scanline length for encoding
#define MAXELEN 0x7fff // maximum scanline length for encoding
static void workOnRGBE(RGBE *scan, int len, float *cols);
static bool decrunch(RGBE *scanline, int len, FILE *file);
static bool oldDecrunch(RGBE *scanline, int len, FILE *file);
bool HDRLoader::isHDRFile(const char *_fileName)
{
FILE *file;
file = fopen(_fileName, "rb");
if (!file)
return false;
char str[10];
fread(str, 10, 1, file);
fclose(file);
if (memcmp(str, "#?RADIANCE", 10) && memcmp(str, "#?RGBE", 6))
return false;
return true;
}
bool HDRLoader::load(const char *_fileName, HDRLoaderResult &_res)
{
int i;
char str[200];
FILE *file;
file = fopen(_fileName, "rb");
if (!file)
return false;
fread(str, 10, 1, file);
if (memcmp(str, "#?RADIANCE", 10)) {
fseek(file, 0, SEEK_SET);
fread(str, 6, 1, file);
if (memcmp(str, "#?RGBE", 6)) {
fclose(file);
return false;
}
}
fseek(file, 1, SEEK_CUR);
char cmd[2000];
i = 0;
char c = 0, oldc;
while(true) {
oldc = c;
c = fgetc(file);
if (c == 0xa && oldc == 0xa)
break;
cmd[i++] = c;
}
char reso[2000];
i = 0;
while(true) {
c = fgetc(file);
reso[i++] = c;
if (c == 0xa)
break;
}
int w, h;
if (!sscanf(reso, "-Y %d +X %d", &h, &w)) {
fclose(file);
return false;
}
_res.width = w;
_res.height = h;
float *cols = new float[w * h * 3];
_res.cols = cols;
RGBE *scanline = new RGBE[w];
if (!scanline) {
fclose(file);
return false;
}
// convert image
cols += (h-1) * w * 3;
for (int y = h - 1; y >= 0; y--) {
if (decrunch(scanline, w, file) == false)
break;
workOnRGBE(scanline, w, cols);
cols -= w * 3;
}
delete [] scanline;
fclose(file);
return true;
}
inline float convertComponent(int _expo, int _val)
{
return ldexp( static_cast<float>(_val), _expo-8);
}
void workOnRGBE(RGBE *_scan, int _len, float *_cols)
{
int ii = 0;
while (_len-- > 0) {
int expo = _scan[0][E] - 128;
_cols[0] = convertComponent(expo, _scan[0][R]);
_cols[1] = convertComponent(expo, _scan[0][G]);
_cols[2] = convertComponent(expo, _scan[0][B]);
_cols += 3;
_scan++;
ii++;
}
}
bool decrunch(RGBE *_scanline, int _len, FILE *_file)
{
int i, j;
if (_len < MINELEN || _len > MAXELEN)
return oldDecrunch(_scanline, _len, _file);
i = fgetc(_file);
if (i != 2) {
fseek(_file, -1, SEEK_CUR);
return oldDecrunch(_scanline, _len, _file);
}
_scanline[0][G] = fgetc(_file);
_scanline[0][B] = fgetc(_file);
i = fgetc(_file);
if (_scanline[0][G] != 2 || _scanline[0][B] & 128) {
_scanline[0][R] = 2;
_scanline[0][E] = i;
return oldDecrunch(_scanline + 1, _len - 1, _file);
}
// read each component
for (i = 0; i < 4; i++) {
for (j = 0; j < _len; ) {
unsigned char code = fgetc(_file);
if (code > 128) { // run
code &= 127;
unsigned char val = fgetc(_file);
while (code--)
_scanline[j++][i] = val;
}
else { // non-run
while(code--)
_scanline[j++][i] = fgetc(_file);
}
}
}
return feof(_file) ? false : true;
}
bool oldDecrunch(RGBE *_scanline, int _len, FILE *_file)
{
int i;
int rshift = 0;
while (_len > 0) {
_scanline[0][R] = fgetc(_file);
_scanline[0][G] = fgetc(_file);
_scanline[0][B] = fgetc(_file);
_scanline[0][E] = fgetc(_file);
if (feof(_file))
return false;
if (_scanline[0][R] == 1 &&
_scanline[0][G] == 1 &&
_scanline[0][B] == 1) {
for (i = _scanline[0][E] << rshift; i > 0; i--) {
memcpy(&_scanline[0][0], &_scanline[-1][0], 4);
_scanline++;
_len--;
}
rshift += 8;
}
else {
_scanline++;
_len--;
rshift = 0;
}
}
return true;
}
<|endoftext|>
|
<commit_before>#include "ug_sampling_bias.h"
#include <iostream>
#include <boost/foreach.hpp>
#include "moses/Util.h"
#ifndef NO_MOSES
#include "moses/Timer.h"
#endif
// #ifdef HAVE_CURLPP
// #include <curlpp/Options.hpp>
// #include <curlpp/cURLpp.hpp>
// #include <curlpp/Easy.hpp>
// #endif
// #ifdef WITH_MMT_BIAS_CLIENT
#include "ug_http_client.h"
// #endif
namespace Moses
{
namespace bitext
{
using ugdiss::id_type;
std::string
query_bias_server(std::string const& server, std::string const& context)
{
std::string query = server+uri_encode(context);
boost::asio::io_service io_service;
Moses::http_client c(io_service, query);
io_service.run();
// std::string response = c.content();
// std::cerr << "SERVER RESPONSE: " << response << std::endl;
return c.content();
}
// #endif
SamplingBias::
SamplingBias(std::vector<id_type> const* sid2doc)
: m_sid2docid(sid2doc)
{ }
int
SamplingBias::
GetClass(id_type const idx) const
{
return m_sid2docid ? m_sid2docid->at(idx) : -1;
}
DocumentBias::
DocumentBias(std::vector<id_type> const& sid2doc,
std::map<std::string,id_type> const& docname2docid,
std::string const& server_url, std::string const& text,
std::ostream* log)
: SamplingBias(&sid2doc)
, m_bias(docname2docid.size(), 0)
{
// #ifdef HAVE_CURLPP
// #ifndef NO_MOSES
Timer timer;
if (log) timer.start(NULL);
std::string json = query_bias_server(server_url, text);
// std::cerr << "SERVER RESPONSE " << json << std::endl;
init_from_json(json, docname2docid, log);
if (log) *log << "Bias query took " << timer << " seconds." << std::endl;
}
DocumentBias::
DocumentBias(std::vector<id_type> const& sid2doc,
std::map<std::string,id_type> const& docname2docid,
std::map<std::string, float> const& context_weights,
std::ostream* log)
: SamplingBias(&sid2doc)
, m_bias(docname2docid.size(), 0)
{
init(context_weights, docname2docid);
}
std::map<std::string, float>& SamplingBias::getBiasMap() {
return m_bias_map;
}
void
DocumentBias::
init_from_json
( std::string const& json, std::map<std::string,id_type> const& docname2docid,
std::ostream* log)
{ // poor man's special purpose json parser for responses from the
// MMT bias server
std::string d; float total = 0; std::map<std::string,float> bias;
size_t i = 0; while (i < json.size() && json[i] != '"') ++i;
while (++i < json.size())
{
size_t k = i; while (i < json.size() && json[i] != '"') ++i;
if (i >= json.size()) break;
float& f = bias[json.substr(k,i-k)];
while (++i < json.size() && json[i] != ':');
k = ++i;
while (++i < json.size() && json[i] != ',' && json[i] != '}');
total += (f = atof(json.substr(k, i-k).c_str()));
k = ++i; while (i < json.size() && json[i] != '"') ++i;
}
typedef std::pair<std::string const,float> item;
if (total) { BOOST_FOREACH(item& x, bias) { x.second /= total; } }
if (log)
{
BOOST_FOREACH(item& x, bias)
{
std::map<std::string,id_type>::const_iterator m;
m = docname2docid.find(x.first);
int docid = m != docname2docid.end() ? m->second : -1;
*log << "CONTEXT SERVER RESPONSE "
<< "[" << docid << "] "
<< x.first << " " << x.second << std::endl;
}
}
init(bias, docname2docid);
// using xmlrpc_parse_json didn't always work (parser errors)
// xmlrpc_value* b = xmlrpc_parse_json(env ,buf.str().c_str());
// std::cerr << "|" << buf.str() << "|" << std::endl;
// // if (b == NULL) std::cerr << "OOpS" << std::endl;
// xmlrpc_c::value_struct v(b); // = *b;
// std::map<std::string, xmlrpc_c::value> const
// bmap = static_cast<map<std::string, xmlrpc_c::value> >(v);
// std::map<std::string, float> bias;
// typedef std::map<std::string, xmlrpc_c::value>::value_type item;
// float total = 0;
// BOOST_FOREACH(item const& x, bmap)
// {
// total += bias[x.first] = xmlrpc_c::value_double(x.second);
// }
// typedef std::map<std::string, float>::value_type fitem;
// BOOST_FOREACH(fitem const& x, bias)
// std::cerr << x.first << " " << x.second/total << std::endl;
// // delete b;
}
void
DocumentBias::
init(std::map<std::string,float> const& biasmap,
std::map<std::string,id_type> const& docname2docid)
{
typedef std::map<std::string, id_type>::value_type doc_record;
float total = 0;
BOOST_FOREACH(doc_record const& d, docname2docid)
{
std::map<std::string, float>::const_iterator m = biasmap.find(d.first);
if (m != biasmap.end()) total += (m_bias[d.second] = m->second);
}
if (total) { BOOST_FOREACH(float& f, m_bias) f /= total; }
BOOST_FOREACH(doc_record const& d, docname2docid)
std::cerr << "BIAS " << d.first << " " << m_bias[d.second] << std::endl;
}
float
DocumentBias::
operator[](id_type const idx) const
{
UTIL_THROW_IF2(idx >= m_sid2docid->size(), "Out of bounds: "
<< idx << "/" << m_sid2docid->size());
return m_bias[(*m_sid2docid)[idx]];
}
size_t
DocumentBias::
size() const
{ return m_sid2docid->size(); }
SentenceBias::
SentenceBias(std::vector<float> const& bias,
std::vector<id_type> const* sid2doc)
: SamplingBias(sid2doc)
, m_bias(bias)
{ }
SentenceBias::
SentenceBias(size_t const s, float const f,
std::vector<id_type> const* sid2doc)
: SamplingBias(sid2doc)
, m_bias(s,f)
{ }
float&
SentenceBias::
operator[](id_type const idx)
{
UTIL_THROW_IF2(idx >= m_bias.size(), "Out of bounds");
return m_bias[idx];
}
float
SentenceBias::
operator[](id_type const idx) const
{
UTIL_THROW_IF2(idx >= m_bias.size(), "Out of bounds");
return m_bias[idx];
}
size_t
SentenceBias::
size() const { return m_bias.size(); }
}
}
<commit_msg>Trying to make sampling more efficient for large document collections underlying the sampling phrase table.<commit_after>#include "ug_sampling_bias.h"
#include <iostream>
#include <boost/foreach.hpp>
#include "moses/Util.h"
#ifndef NO_MOSES
#include "moses/Timer.h"
#endif
// #ifdef HAVE_CURLPP
// #include <curlpp/Options.hpp>
// #include <curlpp/cURLpp.hpp>
// #include <curlpp/Easy.hpp>
// #endif
// #ifdef WITH_MMT_BIAS_CLIENT
#include "ug_http_client.h"
// #endif
namespace Moses
{
namespace bitext
{
using ugdiss::id_type;
std::string
query_bias_server(std::string const& server, std::string const& context)
{
std::string query = server+uri_encode(context);
boost::asio::io_service io_service;
Moses::http_client c(io_service, query);
io_service.run();
// std::string response = c.content();
// std::cerr << "SERVER RESPONSE: " << response << std::endl;
UTIL_THROW_IF2(c.content().size() == 0, "No response from bias server!");
return c.content();
}
// #endif
SamplingBias::
SamplingBias(std::vector<id_type> const* sid2doc)
: m_sid2docid(sid2doc)
{ }
int
SamplingBias::
GetClass(id_type const idx) const
{
return m_sid2docid ? m_sid2docid->at(idx) : -1;
}
DocumentBias::
DocumentBias(std::vector<id_type> const& sid2doc,
std::map<std::string,id_type> const& docname2docid,
std::string const& server_url, std::string const& text,
std::ostream* _log)
: SamplingBias(&sid2doc)
// , m_bias(docname2docid.size(), 0)
{
this->log = _log;
#ifndef NO_MOSES
Timer timer;
if (_log) timer.start(NULL);
#endif
std::string json = query_bias_server(server_url, text);
// std::cerr << "SERVER RESPONSE " << json << std::endl;
init_from_json(json, docname2docid, log);
#ifndef NO_MOSES
if (_log) *_log << "Bias query took " << timer << " seconds." << std::endl;
#endif
}
DocumentBias::
DocumentBias(std::vector<id_type> const& sid2doc,
std::map<std::string,id_type> const& docname2docid,
std::map<std::string, float> const& context_weights,
std::ostream* _log)
: SamplingBias(&sid2doc)
// , m_bias(docname2docid.size(), 0)
{
this->log = _log;
init(context_weights, docname2docid);
}
std::map<std::string, float>& SamplingBias::getBiasMap() {
return m_bias_map;
}
void
DocumentBias::
init_from_json
( std::string const& json, std::map<std::string,id_type> const& docname2docid,
std::ostream* log)
{ // poor man's special purpose json parser for responses from the
// MMT bias server
std::string d; float total = 0; std::map<std::string,float> bias;
size_t i = 0; while (i < json.size() && json[i] != '"') ++i;
while (++i < json.size())
{
size_t k = i; while (i < json.size() && json[i] != '"') ++i;
if (i >= json.size()) break;
float& f = bias[json.substr(k,i-k)];
while (++i < json.size() && json[i] != ':');
k = ++i;
while (++i < json.size() && json[i] != ',' && json[i] != '}');
total += (f = atof(json.substr(k, i-k).c_str()));
k = ++i; while (i < json.size() && json[i] != '"') ++i;
}
typedef std::pair<std::string const,float> item;
if (total) { BOOST_FOREACH(item& x, bias) { x.second /= total; } }
if (log)
{
BOOST_FOREACH(item& x, bias)
{
std::map<std::string,id_type>::const_iterator m;
m = docname2docid.find(x.first);
int docid = m != docname2docid.end() ? m->second : -1;
*log << "CONTEXT SERVER RESPONSE "
<< "[" << docid << "] "
<< x.first << " " << x.second << std::endl;
}
}
init(bias, docname2docid);
// using xmlrpc_parse_json didn't always work (parser errors)
// xmlrpc_value* b = xmlrpc_parse_json(env ,buf.str().c_str());
// std::cerr << "|" << buf.str() << "|" << std::endl;
// // if (b == NULL) std::cerr << "OOpS" << std::endl;
// xmlrpc_c::value_struct v(b); // = *b;
// std::map<std::string, xmlrpc_c::value> const
// bmap = static_cast<map<std::string, xmlrpc_c::value> >(v);
// std::map<std::string, float> bias;
// typedef std::map<std::string, xmlrpc_c::value>::value_type item;
// float total = 0;
// BOOST_FOREACH(item const& x, bmap)
// {
// total += bias[x.first] = xmlrpc_c::value_double(x.second);
// }
// typedef std::map<std::string, float>::value_type fitem;
// BOOST_FOREACH(fitem const& x, bias)
// std::cerr << x.first << " " << x.second/total << std::endl;
// // delete b;
}
void
DocumentBias::
init(std::map<std::string,float> const& biasmap,
std::map<std::string,id_type> const& docname2docid)
{
typedef std::map<std::string, float>::value_type bias_record;
float total = 0;
BOOST_FOREACH(bias_record const& b, biasmap)
{
std::map<std::string, id_type>::const_iterator m = docname2docid.find(b.first);
if (m != docname2docid.end())
total += (m_bias[m->second] = b.second);
}
if (total)
{
typedef std::map<id_type, float>::value_type item;
BOOST_FOREACH(item& i, m_bias) i.second /= total;
}
if (log)
{
BOOST_FOREACH(bias_record const& b, biasmap)
{
std::map<std::string, id_type>::const_iterator m = docname2docid.find(b.first);
if (m != docname2docid.end())
*log << "BIAS " << b.first << " " << m_bias[m->second] << std::endl;
else
*log << "WARNING: bias reported for unknown document " << b.first << std::endl;
}
}
}
float
DocumentBias::
operator[](id_type const idx) const
{
// UTIL_THROW_IF2(idx >= m_sid2docid->size(), "Out of bounds: "
// << idx << "/" << m_sid2docid->size());
std::map<id_type, float>::const_iterator m = m_bias.find((*m_sid2docid)[idx]);
return m != m_bias.end() ? m->second : 0;
}
size_t
DocumentBias::
size() const
{ return m_sid2docid->size(); }
SentenceBias::
SentenceBias(std::vector<float> const& bias,
std::vector<id_type> const* sid2doc)
: SamplingBias(sid2doc)
, m_bias(bias)
{ }
SentenceBias::
SentenceBias(size_t const s, float const f,
std::vector<id_type> const* sid2doc)
: SamplingBias(sid2doc)
, m_bias(s,f)
{ }
float&
SentenceBias::
operator[](id_type const idx)
{
UTIL_THROW_IF2(idx >= m_bias.size(), "Out of bounds");
return m_bias[idx];
}
float
SentenceBias::
operator[](id_type const idx) const
{
UTIL_THROW_IF2(idx >= m_bias.size(), "Out of bounds");
return m_bias[idx];
}
size_t
SentenceBias::
size() const { return m_bias.size(); }
}
}
<|endoftext|>
|
<commit_before>#include <build-bot/bot.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <chrono>
#include <thread>
#include <boost/asio.hpp>
#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
namespace fs = boost::filesystem;
using namespace dsn::build_bot;
namespace dsn {
namespace build_bot {
namespace priv {
class Bot : public dsn::log::Base<Bot> {
protected:
boost::property_tree::ptree m_settings;
bool loadConfig(const std::string& config_file)
{
BOOST_LOG_SEV(log, severity::info) << "Loading configuration from " << config_file;
fs::path path(config_file);
if (!fs::exists(path)) {
BOOST_LOG_SEV(log, severity::error) << "Config file " << config_file << " doesn't exist!";
return false;
}
if (!fs::is_regular_file(path)) {
BOOST_LOG_SEV(log, severity::error) << "Config file " << config_file << " isn't a regular file!";
return false;
}
try {
boost::property_tree::read_ini(config_file, m_settings);
}
catch (boost::property_tree::ini_parser_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to parse config file " << config_file << ": " << ex.what();
return false;
}
m_configFile = config_file;
return true;
}
bool initFifo()
{
std::string fifoName;
try {
fifoName = m_settings.get<std::string>("fifo.name");
}
catch (boost::property_tree::ptree_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to get FIFO settings from configuration: " << ex.what();
return false;
}
fs::path path(fifoName);
if (!fs::exists(path)) {
BOOST_LOG_SEV(log, severity::warning) << "FIFO " << fifoName << " doesn't exist; trying to create it!";
if (mkfifo(fifoName.c_str(), 0666) == -1) {
BOOST_LOG_SEV(log, severity::error) << "Failed to create FIFO " << fifoName << ": " << strerror(errno);
return false;
}
}
BOOST_LOG_SEV(log, severity::debug) << "Opening FIFO " << fifoName << " for reading.";
int fd{ -1 };
if ((fd = open(fifoName.c_str(), O_RDWR)) == -1) {
BOOST_LOG_SEV(log, severity::error) << "Failed to open FIFO " << fifoName << " for reading: " << strerror(errno);
return false;
}
boost::system::error_code error = m_fifo.assign(fd, error);
if (error) {
BOOST_LOG_SEV(log, severity::error) << "Failed to assign FIFO fd to stream_descriptor: " << boost::system::system_error(error).what();
close(fd);
return false;
}
return true;
}
boost::asio::io_service m_io;
boost::asio::strand m_strand;
std::atomic<bool> m_stopRequested;
std::atomic<bool> m_restartAfterStop;
std::string m_configFile;
boost::asio::posix::stream_descriptor m_fifo;
boost::asio::streambuf m_buffer;
void read(const boost::system::error_code& error)
{
if (error) {
BOOST_LOG_SEV(log, severity::error) << "Failed to read from FIFO: " << boost::system::system_error(error).what();
return;
}
std::string message;
{
std::istream stream(&m_buffer);
std::getline(stream, message);
}
BOOST_LOG_SEV(log, severity::trace) << "Read line from FIFO: " << message;
}
public:
Bot()
: m_io()
, m_strand(m_io)
, m_stopRequested(false)
, m_restartAfterStop(false)
, m_configFile("")
, m_fifo(m_io)
{
}
~Bot()
{
if (m_fifo.is_open())
m_fifo.close();
}
bool init(const std::string& config_file)
{
if (!loadConfig(config_file))
return false;
if (!initFifo())
return false;
return true;
}
void stop(bool restart = false)
{
if (restart)
m_restartAfterStop = true;
m_stopRequested = true;
}
dsn::build_bot::Bot::ExitCode run()
{
BOOST_LOG_SEV(log, severity::trace) << "Starting io_service";
std::thread ioServiceThread([&]() {
m_io.run();
});
while (!m_stopRequested.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
BOOST_LOG_SEV(log, severity::trace) << "Stopping io_service";
m_io.stop();
ioServiceThread.join();
if (m_restartAfterStop.load())
return dsn::build_bot::Bot::ExitCode::Restart;
return dsn::build_bot::Bot::ExitCode::Success;
}
};
}
}
}
const std::string dsn::build_bot::Bot::DEFAULT_CONFIG_FILE{ "etc/build-bot/bot.conf" };
Bot::Bot()
: m_impl(new priv::Bot())
{
}
Bot::~Bot()
{
}
bool Bot::init(const std::string& config_file)
{
return m_impl->init(config_file);
}
void Bot::stop()
{
return m_impl->stop();
}
void Bot::restart()
{
return m_impl->stop(true);
}
Bot::ExitCode Bot::run()
{
return m_impl->run();
}
<commit_msg>Install async read handlers for FIFO<commit_after>#include <build-bot/bot.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <chrono>
#include <thread>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
namespace fs = boost::filesystem;
using namespace dsn::build_bot;
namespace dsn {
namespace build_bot {
namespace priv {
class Bot : public dsn::log::Base<Bot> {
protected:
boost::property_tree::ptree m_settings;
bool loadConfig(const std::string& config_file)
{
BOOST_LOG_SEV(log, severity::info) << "Loading configuration from " << config_file;
fs::path path(config_file);
if (!fs::exists(path)) {
BOOST_LOG_SEV(log, severity::error) << "Config file " << config_file << " doesn't exist!";
return false;
}
if (!fs::is_regular_file(path)) {
BOOST_LOG_SEV(log, severity::error) << "Config file " << config_file << " isn't a regular file!";
return false;
}
try {
boost::property_tree::read_ini(config_file, m_settings);
}
catch (boost::property_tree::ini_parser_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to parse config file " << config_file << ": " << ex.what();
return false;
}
m_configFile = config_file;
return true;
}
bool initFifo()
{
std::string fifoName;
try {
fifoName = m_settings.get<std::string>("fifo.name");
}
catch (boost::property_tree::ptree_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to get FIFO settings from configuration: " << ex.what();
return false;
}
fs::path path(fifoName);
if (!fs::exists(path)) {
BOOST_LOG_SEV(log, severity::warning) << "FIFO " << fifoName << " doesn't exist; trying to create it!";
if (mkfifo(fifoName.c_str(), 0666) == -1) {
BOOST_LOG_SEV(log, severity::error) << "Failed to create FIFO " << fifoName << ": " << strerror(errno);
return false;
}
}
BOOST_LOG_SEV(log, severity::debug) << "Opening FIFO " << fifoName << " for reading.";
int fd{ -1 };
if ((fd = open(fifoName.c_str(), O_RDWR)) == -1) {
BOOST_LOG_SEV(log, severity::error) << "Failed to open FIFO " << fifoName << " for reading: " << strerror(errno);
return false;
}
boost::system::error_code error = m_fifo.assign(fd, error);
if (error) {
BOOST_LOG_SEV(log, severity::error) << "Failed to assign FIFO fd to stream_descriptor: " << boost::system::system_error(error).what();
close(fd);
return false;
}
return true;
}
boost::asio::io_service m_io;
boost::asio::strand m_strand;
std::atomic<bool> m_stopRequested;
std::atomic<bool> m_restartAfterStop;
std::string m_configFile;
boost::asio::posix::stream_descriptor m_fifo;
boost::asio::streambuf m_buffer;
void read(const boost::system::error_code& error)
{
if (error) {
BOOST_LOG_SEV(log, severity::error) << "Failed to read from FIFO: " << boost::system::system_error(error).what();
return;
}
std::string message;
{
std::istream stream(&m_buffer);
std::getline(stream, message);
}
BOOST_LOG_SEV(log, severity::trace) << "Read line from FIFO: " << message;
boost::asio::async_read_until(m_fifo, m_buffer, "\n", boost::bind(&Bot::read, this, boost::asio::placeholders::error));
}
public:
Bot()
: m_io()
, m_strand(m_io)
, m_stopRequested(false)
, m_restartAfterStop(false)
, m_configFile("")
, m_fifo(m_io)
{
}
~Bot()
{
if (m_fifo.is_open())
m_fifo.close();
}
bool init(const std::string& config_file)
{
if (!loadConfig(config_file))
return false;
if (!initFifo())
return false;
return true;
}
void stop(bool restart = false)
{
if (restart)
m_restartAfterStop = true;
m_stopRequested = true;
}
dsn::build_bot::Bot::ExitCode run()
{
BOOST_LOG_SEV(log, severity::trace) << "Installing async read handler for FIFO";
boost::asio::async_read_until(m_fifo, m_buffer, "\n", boost::bind(&Bot::read, this, boost::asio::placeholders::error));
BOOST_LOG_SEV(log, severity::trace) << "Starting io_service";
std::thread ioServiceThread([&]() {
m_io.run();
});
while (!m_stopRequested.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
BOOST_LOG_SEV(log, severity::trace) << "Stopping io_service";
m_io.stop();
ioServiceThread.join();
if (m_restartAfterStop.load())
return dsn::build_bot::Bot::ExitCode::Restart;
return dsn::build_bot::Bot::ExitCode::Success;
}
};
}
}
}
const std::string dsn::build_bot::Bot::DEFAULT_CONFIG_FILE{ "etc/build-bot/bot.conf" };
Bot::Bot()
: m_impl(new priv::Bot())
{
}
Bot::~Bot()
{
}
bool Bot::init(const std::string& config_file)
{
return m_impl->init(config_file);
}
void Bot::stop()
{
return m_impl->stop();
}
void Bot::restart()
{
return m_impl->stop(true);
}
Bot::ExitCode Bot::run()
{
return m_impl->run();
}
<|endoftext|>
|
<commit_before>/*
* #%L
* %%
* Copyright (C) 2011 - 2014 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "joynr/PrivateCopyAssign.h"
#include "joynr/MessageQueue.h"
#include "joynr/Timer.h"
#include <chrono>
#include <cstdint>
using namespace joynr;
class MessageQueueTest : public ::testing::Test {
public:
MessageQueueTest()
: messageQueue(),
cleanerTimer(),
expiryDate(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()) + std::chrono::milliseconds(100))
{
}
~MessageQueueTest() = default;
void SetUp()
{
cleanerTimer.addTimer(
[this](joynr::Timer::TimerId) {
this->messageQueue.removeOutdatedMessages();
},
[](Timer::TimerId) { },
50,
true
);
}
void TearDown()
{
cleanerTimer.shutdown();
}
protected:
MessageQueue messageQueue;
Timer cleanerTimer;
JoynrTimePoint expiryDate;
private:
DISALLOW_COPY_AND_ASSIGN(MessageQueueTest);
};
TEST_F(MessageQueueTest, initialQueueIsEmpty) {
EXPECT_EQ(messageQueue.getQueueLength(), 0);
}
TEST_F(MessageQueueTest, addMultipleMessages) {
JoynrMessage msg1;
msg1.setHeaderExpiryDate(expiryDate);
EXPECT_EQ(messageQueue.queueMessage(msg1), 1);
JoynrMessage msg2;
msg2.setHeaderExpiryDate(expiryDate);
EXPECT_EQ(messageQueue.queueMessage(msg2), 2);
JoynrMessage msg3;
msg3.setHeaderExpiryDate(expiryDate);
EXPECT_EQ(messageQueue.queueMessage(msg3), 3);
JoynrMessage msg4;
msg4.setHeaderExpiryDate(expiryDate);
EXPECT_EQ(messageQueue.queueMessage(msg4), 4);
}
TEST_F(MessageQueueTest, queueDequeueMessages) {
// add messages to the queue
JoynrMessage msg1;
msg1.setHeaderTo("TEST1");
msg1.setHeaderExpiryDate(expiryDate);
messageQueue.queueMessage(msg1);
JoynrMessage msg2;
msg2.setHeaderTo("TEST2");
msg2.setHeaderExpiryDate(expiryDate);
messageQueue.queueMessage(msg2);
EXPECT_EQ(messageQueue.getQueueLength(), 2);
// get messages from queue
MessageQueueItem* item = messageQueue.getNextMessageForParticipant("TEST1");
EXPECT_EQ(item->getContent(), msg1);
EXPECT_EQ(messageQueue.getQueueLength(), 1);
item = messageQueue.getNextMessageForParticipant("TEST2");
EXPECT_EQ(item->getContent(), msg2);
EXPECT_EQ(messageQueue.getQueueLength(), 0);
}
TEST_F(MessageQueueTest, queueDequeueMultipleMessagesForOneParticipant) {
// add messages to the queue
JoynrMessage msg;
msg.setHeaderTo("TEST");
msg.setHeaderExpiryDate(expiryDate);
messageQueue.queueMessage(msg);
messageQueue.queueMessage(msg);
EXPECT_EQ(messageQueue.getQueueLength(), 2);
// get messages from queue
MessageQueueItem* item = messageQueue.getNextMessageForParticipant("TEST");
EXPECT_EQ(item->getContent(), msg);
EXPECT_EQ(messageQueue.getQueueLength(), 1);
item = messageQueue.getNextMessageForParticipant("TEST");
EXPECT_EQ(item->getContent(), msg);
EXPECT_EQ(messageQueue.getQueueLength(), 0);
}
TEST_F(MessageQueueTest, dequeueInvalidParticipantId) {
EXPECT_FALSE(messageQueue.getNextMessageForParticipant("TEST"));
}
TEST_F(MessageQueueTest, removeOutdatedMessage) {
JoynrMessage msg10;
JoynrTimePoint now = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
msg10.setHeaderExpiryDate(now + std::chrono::milliseconds(10));
EXPECT_EQ(messageQueue.queueMessage(msg10), 1);
std::this_thread::sleep_for(std::chrono::milliseconds(5));
EXPECT_EQ(messageQueue.removeOutdatedMessages(), 0);
std::this_thread::sleep_for(std::chrono::milliseconds(6));
EXPECT_EQ(messageQueue.removeOutdatedMessages(), 1);
}
TEST_F(MessageQueueTest, removeOutdatedMessagesWithRunnable) {
JoynrMessage msg25;
JoynrTimePoint now = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
msg25.setHeaderExpiryDate(now + std::chrono::milliseconds(25));
JoynrMessage msg250;
msg250.setHeaderExpiryDate(now + std::chrono::milliseconds(250));
JoynrMessage msg300;
msg300.setHeaderExpiryDate(now + std::chrono::milliseconds(250));
EXPECT_EQ(messageQueue.queueMessage(msg25), 1);
EXPECT_EQ(messageQueue.queueMessage(msg250), 2);
EXPECT_EQ(messageQueue.queueMessage(msg300), 3);
// wait to remove the first message
std::this_thread::sleep_for(std::chrono::milliseconds(100));
EXPECT_EQ(messageQueue.getQueueLength(), 2);
// wait to remove all messages
std::this_thread::sleep_for(std::chrono::milliseconds(500));
EXPECT_EQ(messageQueue.getQueueLength(), 0);
}
<commit_msg>[C++] Remove 'message outdated' tests from MessageQueueTest<commit_after>/*
* #%L
* %%
* Copyright (C) 2011 - 2014 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "joynr/PrivateCopyAssign.h"
#include "joynr/MessageQueue.h"
#include "joynr/Timer.h"
#include <chrono>
#include <cstdint>
using namespace joynr;
class MessageQueueTest : public ::testing::Test {
public:
MessageQueueTest()
: messageQueue(),
cleanerTimer(),
expiryDate(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()) + std::chrono::milliseconds(100))
{
}
~MessageQueueTest() = default;
void SetUp()
{
cleanerTimer.addTimer(
[this](joynr::Timer::TimerId) {
this->messageQueue.removeOutdatedMessages();
},
[](Timer::TimerId) { },
50,
true
);
}
void TearDown()
{
cleanerTimer.shutdown();
}
protected:
MessageQueue messageQueue;
Timer cleanerTimer;
JoynrTimePoint expiryDate;
private:
DISALLOW_COPY_AND_ASSIGN(MessageQueueTest);
};
TEST_F(MessageQueueTest, initialQueueIsEmpty) {
EXPECT_EQ(messageQueue.getQueueLength(), 0);
}
TEST_F(MessageQueueTest, addMultipleMessages) {
JoynrMessage msg1;
msg1.setHeaderExpiryDate(expiryDate);
EXPECT_EQ(messageQueue.queueMessage(msg1), 1);
JoynrMessage msg2;
msg2.setHeaderExpiryDate(expiryDate);
EXPECT_EQ(messageQueue.queueMessage(msg2), 2);
JoynrMessage msg3;
msg3.setHeaderExpiryDate(expiryDate);
EXPECT_EQ(messageQueue.queueMessage(msg3), 3);
JoynrMessage msg4;
msg4.setHeaderExpiryDate(expiryDate);
EXPECT_EQ(messageQueue.queueMessage(msg4), 4);
}
TEST_F(MessageQueueTest, queueDequeueMessages) {
// add messages to the queue
JoynrMessage msg1;
msg1.setHeaderTo("TEST1");
msg1.setHeaderExpiryDate(expiryDate);
messageQueue.queueMessage(msg1);
JoynrMessage msg2;
msg2.setHeaderTo("TEST2");
msg2.setHeaderExpiryDate(expiryDate);
messageQueue.queueMessage(msg2);
EXPECT_EQ(messageQueue.getQueueLength(), 2);
// get messages from queue
MessageQueueItem* item = messageQueue.getNextMessageForParticipant("TEST1");
EXPECT_EQ(item->getContent(), msg1);
EXPECT_EQ(messageQueue.getQueueLength(), 1);
item = messageQueue.getNextMessageForParticipant("TEST2");
EXPECT_EQ(item->getContent(), msg2);
EXPECT_EQ(messageQueue.getQueueLength(), 0);
}
TEST_F(MessageQueueTest, queueDequeueMultipleMessagesForOneParticipant) {
// add messages to the queue
JoynrMessage msg;
msg.setHeaderTo("TEST");
msg.setHeaderExpiryDate(expiryDate);
messageQueue.queueMessage(msg);
messageQueue.queueMessage(msg);
EXPECT_EQ(messageQueue.getQueueLength(), 2);
// get messages from queue
MessageQueueItem* item = messageQueue.getNextMessageForParticipant("TEST");
EXPECT_EQ(item->getContent(), msg);
EXPECT_EQ(messageQueue.getQueueLength(), 1);
item = messageQueue.getNextMessageForParticipant("TEST");
EXPECT_EQ(item->getContent(), msg);
EXPECT_EQ(messageQueue.getQueueLength(), 0);
}
TEST_F(MessageQueueTest, dequeueInvalidParticipantId) {
EXPECT_FALSE(messageQueue.getNextMessageForParticipant("TEST"));
}
<|endoftext|>
|
<commit_before>//===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the X86 specific subclass of TargetMachine.
//
//===----------------------------------------------------------------------===//
#include "X86TargetAsmInfo.h"
#include "X86TargetMachine.h"
#include "X86.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetMachineRegistry.h"
#include "llvm/Transforms/Scalar.h"
using namespace llvm;
/// X86TargetMachineModule - Note that this is used on hosts that cannot link
/// in a library unless there are references into the library. In particular,
/// it seems that it is not possible to get things to work on Win32 without
/// this. Though it is unused, do not remove it.
extern "C" int X86TargetMachineModule;
int X86TargetMachineModule = 0;
// Register the target.
static RegisterTarget<X86_32TargetMachine>
X("x86", " 32-bit X86: Pentium-Pro and above");
static RegisterTarget<X86_64TargetMachine>
Y("x86-64", " 64-bit X86: EM64T and AMD64");
const TargetAsmInfo *X86TargetMachine::createTargetAsmInfo() const {
return new X86TargetAsmInfo(*this);
}
unsigned X86_32TargetMachine::getJITMatchQuality() {
#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)
return 10;
#endif
return 0;
}
unsigned X86_64TargetMachine::getJITMatchQuality() {
#if defined(__x86_64__) || defined(_M_AMD64)
return 10;
#endif
return 0;
}
unsigned X86_32TargetMachine::getModuleMatchQuality(const Module &M) {
// We strongly match "i[3-9]86-*".
std::string TT = M.getTargetTriple();
if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
TT[4] == '-' && TT[1] - '3' < 6)
return 20;
// If the target triple is something non-X86, we don't match.
if (!TT.empty()) return 0;
if (M.getEndianness() == Module::LittleEndian &&
M.getPointerSize() == Module::Pointer32)
return 10; // Weak match
else if (M.getEndianness() != Module::AnyEndianness ||
M.getPointerSize() != Module::AnyPointerSize)
return 0; // Match for some other target
return getJITMatchQuality()/2;
}
unsigned X86_64TargetMachine::getModuleMatchQuality(const Module &M) {
// We strongly match "x86_64-*".
std::string TT = M.getTargetTriple();
if (TT.size() >= 7 && TT[0] == 'x' && TT[1] == '8' && TT[2] == '6' &&
TT[3] == '_' && TT[4] == '6' && TT[5] == '4' && TT[6] == '-')
return 20;
// We strongly match "amd64-*".
if (TT.size() >= 6 && TT[0] == 'a' && TT[1] == 'm' && TT[2] == 'd' &&
TT[3] == '6' && TT[4] == '4' && TT[5] == '-')
return 20;
// If the target triple is something non-X86-64, we don't match.
if (!TT.empty()) return 0;
if (M.getEndianness() == Module::LittleEndian &&
M.getPointerSize() == Module::Pointer64)
return 10; // Weak match
else if (M.getEndianness() != Module::AnyEndianness ||
M.getPointerSize() != Module::AnyPointerSize)
return 0; // Match for some other target
return getJITMatchQuality()/2;
}
X86_32TargetMachine::X86_32TargetMachine(const Module &M, const std::string &FS)
: X86TargetMachine(M, FS, false) {
}
X86_64TargetMachine::X86_64TargetMachine(const Module &M, const std::string &FS)
: X86TargetMachine(M, FS, true) {
}
/// X86TargetMachine ctor - Create an ILP32 architecture model
///
X86TargetMachine::X86TargetMachine(const Module &M, const std::string &FS,
bool is64Bit)
: Subtarget(M, FS, is64Bit),
DataLayout(Subtarget.getDataLayout()),
FrameInfo(TargetFrameInfo::StackGrowsDown,
Subtarget.getStackAlignment(), Subtarget.is64Bit() ? -8 : -4),
InstrInfo(*this), JITInfo(*this), TLInfo(*this) {
DefRelocModel = getRelocationModel();
// FIXME: Correctly select PIC model for Win64 stuff
if (getRelocationModel() == Reloc::Default) {
if (Subtarget.isTargetDarwin() ||
(Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64()))
setRelocationModel(Reloc::DynamicNoPIC);
else
setRelocationModel(Reloc::Static);
}
if (Subtarget.is64Bit()) {
// No DynamicNoPIC support under X86-64.
if (getRelocationModel() == Reloc::DynamicNoPIC)
setRelocationModel(Reloc::PIC_);
// Default X86-64 code model is small.
if (getCodeModel() == CodeModel::Default)
setCodeModel(CodeModel::Small);
}
if (Subtarget.isTargetCygMing())
Subtarget.setPICStyle(PICStyle::WinPIC);
else if (Subtarget.isTargetDarwin()) {
if (Subtarget.is64Bit())
Subtarget.setPICStyle(PICStyle::RIPRel);
else
Subtarget.setPICStyle(PICStyle::Stub);
} else if (Subtarget.isTargetELF()) {
if (Subtarget.is64Bit())
Subtarget.setPICStyle(PICStyle::RIPRel);
else
Subtarget.setPICStyle(PICStyle::GOT);
}
}
//===----------------------------------------------------------------------===//
// Pass Pipeline Configuration
//===----------------------------------------------------------------------===//
bool X86TargetMachine::addInstSelector(PassManagerBase &PM, bool Fast) {
// Install an instruction selector.
PM.add(createX86ISelDag(*this, Fast));
return false;
}
bool X86TargetMachine::addPreRegAlloc(PassManagerBase &PM, bool Fast) {
// Calculate and set max stack object alignment early, so we can decide
// whether we will need stack realignment (and thus FP).
PM.add(createX86MaxStackAlignmentCalculatorPass());
return false; // -print-machineinstr shouldn't print after this.
}
bool X86TargetMachine::addPostRegAlloc(PassManagerBase &PM, bool Fast) {
PM.add(createX86FloatingPointStackifierPass());
return true; // -print-machineinstr should print after this.
}
bool X86TargetMachine::addAssemblyEmitter(PassManagerBase &PM, bool Fast,
std::ostream &Out) {
PM.add(createX86CodePrinterPass(Out, *this));
return false;
}
bool X86TargetMachine::addCodeEmitter(PassManagerBase &PM, bool Fast,
bool DumpAsm, MachineCodeEmitter &MCE) {
// FIXME: Move this to TargetJITInfo!
if (DefRelocModel == Reloc::Default) {
setRelocationModel(Reloc::Static);
Subtarget.setPICStyle(PICStyle::None);
}
// JIT cannot ensure globals are placed in the lower 4G of address.
if (Subtarget.is64Bit())
setCodeModel(CodeModel::Large);
PM.add(createX86CodeEmitterPass(*this, MCE));
if (DumpAsm)
PM.add(createX86CodePrinterPass(*cerr.stream(), *this));
return false;
}
bool X86TargetMachine::addSimpleCodeEmitter(PassManagerBase &PM, bool Fast,
bool DumpAsm, MachineCodeEmitter &MCE) {
PM.add(createX86CodeEmitterPass(*this, MCE));
if (DumpAsm)
PM.add(createX86CodePrinterPass(*cerr.stream(), *this));
return false;
}
<commit_msg>X86CodeEmitter should not set PIC style to None at initialization time. This will break codegen if relocation model is changed to PIC_ later.<commit_after>//===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the X86 specific subclass of TargetMachine.
//
//===----------------------------------------------------------------------===//
#include "X86TargetAsmInfo.h"
#include "X86TargetMachine.h"
#include "X86.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetMachineRegistry.h"
#include "llvm/Transforms/Scalar.h"
using namespace llvm;
/// X86TargetMachineModule - Note that this is used on hosts that cannot link
/// in a library unless there are references into the library. In particular,
/// it seems that it is not possible to get things to work on Win32 without
/// this. Though it is unused, do not remove it.
extern "C" int X86TargetMachineModule;
int X86TargetMachineModule = 0;
// Register the target.
static RegisterTarget<X86_32TargetMachine>
X("x86", " 32-bit X86: Pentium-Pro and above");
static RegisterTarget<X86_64TargetMachine>
Y("x86-64", " 64-bit X86: EM64T and AMD64");
const TargetAsmInfo *X86TargetMachine::createTargetAsmInfo() const {
return new X86TargetAsmInfo(*this);
}
unsigned X86_32TargetMachine::getJITMatchQuality() {
#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)
return 10;
#endif
return 0;
}
unsigned X86_64TargetMachine::getJITMatchQuality() {
#if defined(__x86_64__) || defined(_M_AMD64)
return 10;
#endif
return 0;
}
unsigned X86_32TargetMachine::getModuleMatchQuality(const Module &M) {
// We strongly match "i[3-9]86-*".
std::string TT = M.getTargetTriple();
if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
TT[4] == '-' && TT[1] - '3' < 6)
return 20;
// If the target triple is something non-X86, we don't match.
if (!TT.empty()) return 0;
if (M.getEndianness() == Module::LittleEndian &&
M.getPointerSize() == Module::Pointer32)
return 10; // Weak match
else if (M.getEndianness() != Module::AnyEndianness ||
M.getPointerSize() != Module::AnyPointerSize)
return 0; // Match for some other target
return getJITMatchQuality()/2;
}
unsigned X86_64TargetMachine::getModuleMatchQuality(const Module &M) {
// We strongly match "x86_64-*".
std::string TT = M.getTargetTriple();
if (TT.size() >= 7 && TT[0] == 'x' && TT[1] == '8' && TT[2] == '6' &&
TT[3] == '_' && TT[4] == '6' && TT[5] == '4' && TT[6] == '-')
return 20;
// We strongly match "amd64-*".
if (TT.size() >= 6 && TT[0] == 'a' && TT[1] == 'm' && TT[2] == 'd' &&
TT[3] == '6' && TT[4] == '4' && TT[5] == '-')
return 20;
// If the target triple is something non-X86-64, we don't match.
if (!TT.empty()) return 0;
if (M.getEndianness() == Module::LittleEndian &&
M.getPointerSize() == Module::Pointer64)
return 10; // Weak match
else if (M.getEndianness() != Module::AnyEndianness ||
M.getPointerSize() != Module::AnyPointerSize)
return 0; // Match for some other target
return getJITMatchQuality()/2;
}
X86_32TargetMachine::X86_32TargetMachine(const Module &M, const std::string &FS)
: X86TargetMachine(M, FS, false) {
}
X86_64TargetMachine::X86_64TargetMachine(const Module &M, const std::string &FS)
: X86TargetMachine(M, FS, true) {
}
/// X86TargetMachine ctor - Create an ILP32 architecture model
///
X86TargetMachine::X86TargetMachine(const Module &M, const std::string &FS,
bool is64Bit)
: Subtarget(M, FS, is64Bit),
DataLayout(Subtarget.getDataLayout()),
FrameInfo(TargetFrameInfo::StackGrowsDown,
Subtarget.getStackAlignment(), Subtarget.is64Bit() ? -8 : -4),
InstrInfo(*this), JITInfo(*this), TLInfo(*this) {
DefRelocModel = getRelocationModel();
// FIXME: Correctly select PIC model for Win64 stuff
if (getRelocationModel() == Reloc::Default) {
if (Subtarget.isTargetDarwin() ||
(Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64()))
setRelocationModel(Reloc::DynamicNoPIC);
else
setRelocationModel(Reloc::Static);
}
if (Subtarget.is64Bit()) {
// No DynamicNoPIC support under X86-64.
if (getRelocationModel() == Reloc::DynamicNoPIC)
setRelocationModel(Reloc::PIC_);
// Default X86-64 code model is small.
if (getCodeModel() == CodeModel::Default)
setCodeModel(CodeModel::Small);
}
if (Subtarget.isTargetCygMing())
Subtarget.setPICStyle(PICStyle::WinPIC);
else if (Subtarget.isTargetDarwin()) {
if (Subtarget.is64Bit())
Subtarget.setPICStyle(PICStyle::RIPRel);
else
Subtarget.setPICStyle(PICStyle::Stub);
} else if (Subtarget.isTargetELF()) {
if (Subtarget.is64Bit())
Subtarget.setPICStyle(PICStyle::RIPRel);
else
Subtarget.setPICStyle(PICStyle::GOT);
}
}
//===----------------------------------------------------------------------===//
// Pass Pipeline Configuration
//===----------------------------------------------------------------------===//
bool X86TargetMachine::addInstSelector(PassManagerBase &PM, bool Fast) {
// Install an instruction selector.
PM.add(createX86ISelDag(*this, Fast));
return false;
}
bool X86TargetMachine::addPreRegAlloc(PassManagerBase &PM, bool Fast) {
// Calculate and set max stack object alignment early, so we can decide
// whether we will need stack realignment (and thus FP).
PM.add(createX86MaxStackAlignmentCalculatorPass());
return false; // -print-machineinstr shouldn't print after this.
}
bool X86TargetMachine::addPostRegAlloc(PassManagerBase &PM, bool Fast) {
PM.add(createX86FloatingPointStackifierPass());
return true; // -print-machineinstr should print after this.
}
bool X86TargetMachine::addAssemblyEmitter(PassManagerBase &PM, bool Fast,
std::ostream &Out) {
PM.add(createX86CodePrinterPass(Out, *this));
return false;
}
bool X86TargetMachine::addCodeEmitter(PassManagerBase &PM, bool Fast,
bool DumpAsm, MachineCodeEmitter &MCE) {
// FIXME: Move this to TargetJITInfo!
if (DefRelocModel == Reloc::Default)
setRelocationModel(Reloc::Static);
// JIT cannot ensure globals are placed in the lower 4G of address.
if (Subtarget.is64Bit())
setCodeModel(CodeModel::Large);
PM.add(createX86CodeEmitterPass(*this, MCE));
if (DumpAsm)
PM.add(createX86CodePrinterPass(*cerr.stream(), *this));
return false;
}
bool X86TargetMachine::addSimpleCodeEmitter(PassManagerBase &PM, bool Fast,
bool DumpAsm, MachineCodeEmitter &MCE) {
PM.add(createX86CodeEmitterPass(*this, MCE));
if (DumpAsm)
PM.add(createX86CodePrinterPass(*cerr.stream(), *this));
return false;
}
<|endoftext|>
|
<commit_before><commit_msg>Don't add the sender's address to the list of recipients even if it's listed in the Mail-Followup-To header.<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: geometrycontrolmodel.hxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: hr $ $Date: 2006-06-19 22:56:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _TOOLKIT_HELPERS_GEOMETRYCONTROLMODEL_HXX_
#define _TOOLKIT_HELPERS_GEOMETRYCONTROLMODEL_HXX_
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_AGGREGATION_HXX_
#include <comphelper/propagg.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _COMPHELPER_PROPERTYCONTAINER_HXX_
#include <comphelper/propertycontainer.hxx>
#endif
#ifndef _CPPUHELPER_WEAKAGG_HXX_
#include <cppuhelper/weakagg.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCLONEABLE_HPP_
#include <com/sun/star/util/XCloneable.hpp>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_XSCRIPTEVENTSSUPPLIER_HPP_
#include <com/sun/star/script/XScriptEventsSupplier.hpp>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef COMPHELPER_IDPROPERTYARRAYUSAGEHELPER_HXX
#include <comphelper/IdPropArrayHelper.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
FORWARD_DECLARE_INTERFACE( lang, XMultiServiceFactory )
FORWARD_DECLARE_INTERFACE( script, XNameContainer )
//........................................................................
// namespace toolkit
// {
//........................................................................
//====================================================================
//= OGeometryControlModel_Base
//====================================================================
typedef ::cppu::WeakAggComponentImplHelper2 < ::com::sun::star::util::XCloneable
, ::com::sun::star::script::XScriptEventsSupplier
> OGCM_Base;
class OGeometryControlModel_Base
:public ::comphelper::OMutexAndBroadcastHelper
,public ::comphelper::OPropertySetAggregationHelper
,public ::comphelper::OPropertyContainer
,public OGCM_Base
{
protected:
::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation >
m_xAggregate;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >
mxEventContainer;
// <properties>
sal_Int32 m_nPosX;
sal_Int32 m_nPosY;
sal_Int32 m_nWidth;
sal_Int32 m_nHeight;
::rtl::OUString m_aName;
sal_Int16 m_nTabIndex;
sal_Int32 m_nStep;
::rtl::OUString m_aTag;
// </properties>
sal_Bool m_bCloneable;
protected:
virtual ::com::sun::star::uno::Any ImplGetDefaultValueByHandle(sal_Int32 nHandle) const;
virtual ::com::sun::star::uno::Any ImplGetPropertyValueByHandle(sal_Int32 nHandle) const;
virtual void ImplSetPropertyValueByHandle(sal_Int32 nHandle, const :: com::sun::star::uno::Any& aValue);
protected:
/**
@param _pAggregateInstance
the object to be aggregated. The refcount of the instance given MUST be 0!
*/
OGeometryControlModel_Base(::com::sun::star::uno::XAggregation* _pAggregateInstance);
/**
@param _rxAggregateInstance
is the object to be aggregated. Must be aquired excatly once (by the reference object given).<br/>
Will be reset to NULL upon leaving
*/
OGeometryControlModel_Base(::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance);
/** releases the aggregation
<p>Can be used if in a derived class, an exception has to be thrown after this base class here already
did the aggregation</p>
*/
void releaseAggregation();
protected:
~OGeometryControlModel_Base();
// XAggregation
::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _aType ) throw(::com::sun::star::uno::RuntimeException);
// XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire( ) throw();
virtual void SAL_CALL release( ) throw();
// XTypeProvider
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw (::com::sun::star::uno::RuntimeException);
// OPropertySetHelper overridables
virtual sal_Bool SAL_CALL convertFastPropertyValue(
::com::sun::star::uno::Any& _rConvertedValue, ::com::sun::star::uno::Any& _rOldValue,
sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue )
throw (::com::sun::star::lang::IllegalArgumentException);
virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue)
throw (::com::sun::star::uno::Exception);
using comphelper::OPropertySetAggregationHelper::getFastPropertyValue;
virtual void SAL_CALL getFastPropertyValue(
::com::sun::star::uno::Any& _rValue, sal_Int32 _nHandle) const;
// OPropertyStateHelper overridables
virtual ::com::sun::star::beans::PropertyState getPropertyStateByHandle(sal_Int32 nHandle);
virtual void setPropertyToDefaultByHandle(sal_Int32 nHandle);
virtual ::com::sun::star::uno::Any getPropertyDefaultByHandle(sal_Int32 nHandle) const;
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
// OPropertySetAggregationHelper overridables
virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper() = 0;
// XCloneable
virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable > SAL_CALL createClone( ) throw(::com::sun::star::uno::RuntimeException);
//XScriptEventsSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >
SAL_CALL getEvents( ) throw(::com::sun::star::uno::RuntimeException);
// XCloneable implementation - to be overwritten
virtual OGeometryControlModel_Base* createClone_Impl(
::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance) = 0;
// XComponent
using comphelper::OPropertySetAggregationHelper::disposing;
virtual void SAL_CALL disposing();
private:
void registerProperties();
};
//====================================================================
//= OTemplateInstanceDisambiguation
//====================================================================
template <class CONTROLMODEL>
class OTemplateInstanceDisambiguation
{
};
//====================================================================
//= OGeometryControlModel
//====================================================================
/* example for usage:
Reference< XAggregation > xIFace = new ::toolkit::OGeometryControlModel< UnoControlButtonModel > ();
*/
template <class CONTROLMODEL>
class OGeometryControlModel
:public OGeometryControlModel_Base
,public ::comphelper::OAggregationArrayUsageHelper< OTemplateInstanceDisambiguation< CONTROLMODEL > >
{
public:
OGeometryControlModel();
private:
OGeometryControlModel(::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance);
protected:
// OAggregationArrayUsageHelper overridables
virtual void fillProperties(
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& _rProps,
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& _rAggregateProps
) const;
// OPropertySetAggregationHelper overridables
virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
// OGeometryControlModel_Base
virtual OGeometryControlModel_Base* createClone_Impl(
::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance);
// XTypeProvider
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw (::com::sun::star::uno::RuntimeException);
};
//====================================================================
//= OCommonGeometryControlModel
//====================================================================
/** allows to extend an arbitrary <type scope="com.sun.star.awt">UnoControlModel</type> with geometry
information.
*/
class OCommonGeometryControlModel
:public OGeometryControlModel_Base
,public ::comphelper::OIdPropertyArrayUsageHelper< OCommonGeometryControlModel >
{
private:
::rtl::OUString m_sServiceSpecifier; // the service specifier of our aggregate
sal_Int32 m_nPropertyMapId; // our unique property info id, used to look up in s_aAggregateProperties
public:
/** instantiate the model
@param _rxAgg
the instance to aggregate. Must support the <type scope="com.sun.star.awt">UnoControlModel</type>
(this is not checked here)
*/
OCommonGeometryControlModel(
::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAgg,
const ::rtl::OUString& _rxServiceSpecifier
);
// OIdPropertyArrayUsageHelper overridables
virtual ::cppu::IPropertyArrayHelper* createArrayHelper(sal_Int32 nId) const;
// OPropertySetAggregationHelper overridables
virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
// OGeometryControlModel_Base
virtual OGeometryControlModel_Base* createClone_Impl(
::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance);
// XTypeProvider
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw (::com::sun::star::uno::RuntimeException);
private:
virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue)
throw (::com::sun::star::uno::Exception);
};
#include "toolkit/controls/geometrycontrolmodel_impl.hxx"
//........................................................................
// } // namespace toolkit
//........................................................................
#endif // _TOOLKIT_HELPERS_GEOMETRYCONTROLMODEL_HXX_
<commit_msg>INTEGRATION: CWS sb59 (1.17.16); FILE MERGED 2006/07/21 07:59:24 sb 1.17.16.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: geometrycontrolmodel.hxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: obo $ $Date: 2006-10-12 10:30:06 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _TOOLKIT_HELPERS_GEOMETRYCONTROLMODEL_HXX_
#define _TOOLKIT_HELPERS_GEOMETRYCONTROLMODEL_HXX_
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_AGGREGATION_HXX_
#include <comphelper/propagg.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _COMPHELPER_PROPERTYCONTAINER_HXX_
#include <comphelper/propertycontainer.hxx>
#endif
#ifndef _CPPUHELPER_WEAKAGG_HXX_
#include <cppuhelper/weakagg.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCLONEABLE_HPP_
#include <com/sun/star/util/XCloneable.hpp>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_XSCRIPTEVENTSSUPPLIER_HPP_
#include <com/sun/star/script/XScriptEventsSupplier.hpp>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef COMPHELPER_IDPROPERTYARRAYUSAGEHELPER_HXX
#include <comphelper/IdPropArrayHelper.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
FORWARD_DECLARE_INTERFACE( lang, XMultiServiceFactory )
FORWARD_DECLARE_INTERFACE( script, XNameContainer )
//........................................................................
// namespace toolkit
// {
//........................................................................
//====================================================================
//= OGeometryControlModel_Base
//====================================================================
typedef ::cppu::WeakAggComponentImplHelper2 < ::com::sun::star::util::XCloneable
, ::com::sun::star::script::XScriptEventsSupplier
> OGCM_Base;
class OGeometryControlModel_Base
:public ::comphelper::OMutexAndBroadcastHelper
,public ::comphelper::OPropertySetAggregationHelper
,public ::comphelper::OPropertyContainer
,public OGCM_Base
{
protected:
::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation >
m_xAggregate;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >
mxEventContainer;
// <properties>
sal_Int32 m_nPosX;
sal_Int32 m_nPosY;
sal_Int32 m_nWidth;
sal_Int32 m_nHeight;
::rtl::OUString m_aName;
sal_Int16 m_nTabIndex;
sal_Int32 m_nStep;
::rtl::OUString m_aTag;
// </properties>
sal_Bool m_bCloneable;
protected:
virtual ::com::sun::star::uno::Any ImplGetDefaultValueByHandle(sal_Int32 nHandle) const;
virtual ::com::sun::star::uno::Any ImplGetPropertyValueByHandle(sal_Int32 nHandle) const;
virtual void ImplSetPropertyValueByHandle(sal_Int32 nHandle, const :: com::sun::star::uno::Any& aValue);
protected:
/**
@param _pAggregateInstance
the object to be aggregated. The refcount of the instance given MUST be 0!
*/
OGeometryControlModel_Base(::com::sun::star::uno::XAggregation* _pAggregateInstance);
/**
@param _rxAggregateInstance
is the object to be aggregated. Must be aquired excatly once (by the reference object given).<br/>
Will be reset to NULL upon leaving
*/
OGeometryControlModel_Base(::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance);
/** releases the aggregation
<p>Can be used if in a derived class, an exception has to be thrown after this base class here already
did the aggregation</p>
*/
void releaseAggregation();
protected:
~OGeometryControlModel_Base();
// XAggregation
::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _aType ) throw(::com::sun::star::uno::RuntimeException);
// XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire( ) throw();
virtual void SAL_CALL release( ) throw();
// XTypeProvider
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw (::com::sun::star::uno::RuntimeException);
// OPropertySetHelper overridables
virtual sal_Bool SAL_CALL convertFastPropertyValue(
::com::sun::star::uno::Any& _rConvertedValue, ::com::sun::star::uno::Any& _rOldValue,
sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue )
throw (::com::sun::star::lang::IllegalArgumentException);
virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue)
throw (::com::sun::star::uno::Exception);
using comphelper::OPropertySetAggregationHelper::getFastPropertyValue;
virtual void SAL_CALL getFastPropertyValue(
::com::sun::star::uno::Any& _rValue, sal_Int32 _nHandle) const;
// OPropertyStateHelper overridables
virtual ::com::sun::star::beans::PropertyState getPropertyStateByHandle(sal_Int32 nHandle);
virtual void setPropertyToDefaultByHandle(sal_Int32 nHandle);
virtual ::com::sun::star::uno::Any getPropertyDefaultByHandle(sal_Int32 nHandle) const;
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
// OPropertySetAggregationHelper overridables
using OPropertySetAggregationHelper::getInfoHelper;
// XCloneable
virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable > SAL_CALL createClone( ) throw(::com::sun::star::uno::RuntimeException);
//XScriptEventsSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >
SAL_CALL getEvents( ) throw(::com::sun::star::uno::RuntimeException);
// XCloneable implementation - to be overwritten
virtual OGeometryControlModel_Base* createClone_Impl(
::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance) = 0;
// XComponent
using comphelper::OPropertySetAggregationHelper::disposing;
virtual void SAL_CALL disposing();
private:
void registerProperties();
};
//====================================================================
//= OTemplateInstanceDisambiguation
//====================================================================
template <class CONTROLMODEL>
class OTemplateInstanceDisambiguation
{
};
//====================================================================
//= OGeometryControlModel
//====================================================================
/* example for usage:
Reference< XAggregation > xIFace = new ::toolkit::OGeometryControlModel< UnoControlButtonModel > ();
*/
template <class CONTROLMODEL>
class OGeometryControlModel
:public OGeometryControlModel_Base
,public ::comphelper::OAggregationArrayUsageHelper< OTemplateInstanceDisambiguation< CONTROLMODEL > >
{
public:
OGeometryControlModel();
private:
OGeometryControlModel(::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance);
protected:
// OAggregationArrayUsageHelper overridables
virtual void fillProperties(
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& _rProps,
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& _rAggregateProps
) const;
// OPropertySetAggregationHelper overridables
virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
// OGeometryControlModel_Base
virtual OGeometryControlModel_Base* createClone_Impl(
::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance);
// XTypeProvider
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw (::com::sun::star::uno::RuntimeException);
};
//====================================================================
//= OCommonGeometryControlModel
//====================================================================
/** allows to extend an arbitrary <type scope="com.sun.star.awt">UnoControlModel</type> with geometry
information.
*/
class OCommonGeometryControlModel
:public OGeometryControlModel_Base
,public ::comphelper::OIdPropertyArrayUsageHelper< OCommonGeometryControlModel >
{
private:
::rtl::OUString m_sServiceSpecifier; // the service specifier of our aggregate
sal_Int32 m_nPropertyMapId; // our unique property info id, used to look up in s_aAggregateProperties
public:
/** instantiate the model
@param _rxAgg
the instance to aggregate. Must support the <type scope="com.sun.star.awt">UnoControlModel</type>
(this is not checked here)
*/
OCommonGeometryControlModel(
::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAgg,
const ::rtl::OUString& _rxServiceSpecifier
);
// OIdPropertyArrayUsageHelper overridables
virtual ::cppu::IPropertyArrayHelper* createArrayHelper(sal_Int32 nId) const;
// OPropertySetAggregationHelper overridables
virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
// OGeometryControlModel_Base
virtual OGeometryControlModel_Base* createClone_Impl(
::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance);
// XTypeProvider
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw (::com::sun::star::uno::RuntimeException);
private:
virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue)
throw (::com::sun::star::uno::Exception);
};
#include "toolkit/controls/geometrycontrolmodel_impl.hxx"
//........................................................................
// } // namespace toolkit
//........................................................................
#endif // _TOOLKIT_HELPERS_GEOMETRYCONTROLMODEL_HXX_
<|endoftext|>
|
<commit_before>#include "Rendering/CascadedShadowMap.hpp"
#include <cmath>
#include <algorithm>
#include "Math/Vec2.hpp"
#include "Math/Math.hpp"
#include "Math/Frustum.hpp"
#include "Math/BoundingBox.hpp"
namespace CascadedShadowMap
{
int GetShadowCascadeResolution()
{
return 1024;
}
unsigned int GetCascadeCount()
{
return 4;
}
void CalculateCascadeFrusta(
const Vec3f& lightDirection,
const Mat4x4f& cameraTransform,
const ProjectionParameters& projection,
Mat4x4f* transformsOut,
ProjectionParameters* projectionsOut)
{
float splits[MaxCascadeCount];
CalculateSplitDepths(projection, splits);
Vec3f up(0.0f, 1.0f, 0.0f);
if (std::abs(Vec3f::Dot(lightDirection, up)) > 0.99f)
up = Vec3f(0.0f, 0.0f, -1.0f);
Mat4x4f placeholderLightTransform = Mat4x4f::LookAt(Vec3f(0.0f, 0.0f, 0.0f), lightDirection, up);
Vec3f lightDirX = (placeholderLightTransform * Vec4f(1.0f, 0.0f, 0.0f, 0.0f)).xyz();
Vec3f lightDirY = (placeholderLightTransform * Vec4f(0.0f, 1.0f, 0.0f, 0.0f)).xyz();
Vec2f halfFovTan;
halfFovTan.y = std::tan(projection.height * 0.5f);
halfFovTan.x = halfFovTan.y * projection.aspect;
float crossHalfFovTan = halfFovTan.Magnitude();
for (unsigned int cascIdx = 0, count = GetCascadeCount(); cascIdx < count; ++cascIdx)
{
// Calculate frusta for camera perspective
ProjectionParameters cascadeCameraFrustum;
cascadeCameraFrustum.projection = projection.projection;
cascadeCameraFrustum.aspect = projection.aspect;
cascadeCameraFrustum.height = projection.height;
cascadeCameraFrustum.near = cascIdx > 0 ? splits[cascIdx - 1] : projection.near;
cascadeCameraFrustum.far = splits[cascIdx];
FrustumPoints fp;
fp.Update(cascadeCameraFrustum, cameraTransform);
// Calculate frusta for light perspective
// Calculate enclosing sphere
Vec3f farPlaneCenter = (cameraTransform * Vec4f(0.0f, 0.0f, -splits[cascIdx], 1.0f)).xyz();
float resolution = static_cast<float>(GetShadowCascadeResolution());
float roundingMarginFactor = resolution / (resolution - 1.0f);
Vec3f sphereCenter;
float radius;
// Near plane points are closer than far plane points
if ((fp.points[0] - farPlaneCenter).SqrMagnitude() < (fp.points[4] - farPlaneCenter).SqrMagnitude())
{
// Optimal sphere center is at far plane center
sphereCenter = farPlaneCenter;
radius = (fp.points[4] - farPlaneCenter).Magnitude() * roundingMarginFactor;
}
else // Near plane points are farther than far plane points
{
// Need to calculate optimal position for sphere center
// Consider as a 2D corner to corner cross-section of frustum
// Average of near and far depths
float cascadeHalfDepth = (cascadeCameraFrustum.far + cascadeCameraFrustum.near) * 0.5f;
// Distance from center axis to frustum corner line at halfway depth
float midHalfWidth = cascadeHalfDepth * crossHalfFovTan;
// Sphere center offset from frustum center line halfway point
float offsetFromFrustumCenter = midHalfWidth * crossHalfFovTan;
// Sphere center depth from camera
float sphereDepth = cascadeHalfDepth + offsetFromFrustumCenter;
sphereCenter = (cameraTransform * Vec4f(0.0f, 0.0f, -sphereDepth, 1.0f)).xyz();
radius = (sphereCenter - fp.points[0]).Magnitude() * roundingMarginFactor;
}
Vec3f from = sphereCenter - lightDirection * radius;
Mat4x4f lightModelTransform = Mat4x4f::LookAt(from, sphereCenter, up);
Mat4x4f lightViewTransform = lightModelTransform.GetInverse();
float diameter = radius * 2.0f;
ProjectionParameters cascProj;
cascProj.projection = ProjectionType::Orthographic;
cascProj.aspect = 1.0f;
cascProj.height = diameter;
cascProj.near = 0.0f;
cascProj.far = diameter;
// Calculate rounding in shadow map space to remove edge shimmer
Mat4x4f shadowMatrix = cascProj.GetProjectionMatrix() * lightViewTransform;
Vec4f originShadowSpace = shadowMatrix * Vec4f(0.0f, 0.0f, 0.0f, 1.0f) * resolution * 0.5f;
Vec4f roundedOrigin(std::round(originShadowSpace.x), std::round(originShadowSpace.y), 0.0f, 0.0f);
Vec4f offsetShadowSpace = (roundedOrigin - originShadowSpace) * (2.0f / resolution);
Vec3f offsetWs = (lightDirX * offsetShadowSpace.x + lightDirY * offsetShadowSpace.y) * radius;
// Because we don't return projection as a matrix, we have to add the offset to the view transform
transformsOut[cascIdx] = Mat4x4f::LookAt(from - offsetWs, sphereCenter - offsetWs, up);
projectionsOut[cascIdx] = cascProj;
}
}
void CalculateSplitDepths(const ProjectionParameters& projection, float* depthsOut)
{
CalculateSplitDepths(projection.near, projection.far, depthsOut);
}
void CalculateSplitDepths(float near, float far, float* depthsOut)
{
const float maxShadowDistance = 100.0f;
const float shadowSplitLogFactor = 0.8f;
far = std::min(maxShadowDistance, far);
float i_f = 1.0f;
unsigned int cascadeCountInt = GetCascadeCount();
float cascadeCountFloat = static_cast<float>(cascadeCountInt);
for (unsigned int i = 0; i < cascadeCountInt - 1; i++, i_f += 1.0f)
{
depthsOut[i] = Math::Lerp(
near + (i_f / cascadeCountFloat) * (far - near),
near * std::powf(far / near, i_f / cascadeCountFloat),
shadowSplitLogFactor);
}
depthsOut[cascadeCountInt - 1] = far;
}
} // namespace CascadedShadowMap
<commit_msg>Fix a shadow rendering issue<commit_after>#include "Rendering/CascadedShadowMap.hpp"
#include <cmath>
#include <algorithm>
#include "Math/Vec2.hpp"
#include "Math/Math.hpp"
#include "Math/Frustum.hpp"
#include "Math/BoundingBox.hpp"
namespace CascadedShadowMap
{
int GetShadowCascadeResolution()
{
return 1024;
}
unsigned int GetCascadeCount()
{
return 4;
}
void CalculateCascadeFrusta(
const Vec3f& lightDirection,
const Mat4x4f& cameraTransform,
const ProjectionParameters& projection,
Mat4x4f* transformsOut,
ProjectionParameters* projectionsOut)
{
float splits[MaxCascadeCount];
CalculateSplitDepths(projection, splits);
Vec3f up(0.0f, 1.0f, 0.0f);
if (std::abs(Vec3f::Dot(lightDirection, up)) > 0.99f)
up = Vec3f(0.0f, 0.0f, -1.0f);
Mat4x4f placeholderLightTransform = Mat4x4f::LookAt(Vec3f(0.0f, 0.0f, 0.0f), lightDirection, up);
Vec3f lightDirX = (placeholderLightTransform * Vec4f(1.0f, 0.0f, 0.0f, 0.0f)).xyz();
Vec3f lightDirY = (placeholderLightTransform * Vec4f(0.0f, 1.0f, 0.0f, 0.0f)).xyz();
Vec2f halfFovTan;
halfFovTan.y = std::tan(projection.height * 0.5f);
halfFovTan.x = halfFovTan.y * projection.aspect;
float crossHalfFovTan = halfFovTan.Magnitude();
for (unsigned int cascIdx = 0, count = GetCascadeCount(); cascIdx < count; ++cascIdx)
{
// Calculate frusta for camera perspective
ProjectionParameters cascadeCameraFrustum;
cascadeCameraFrustum.projection = projection.projection;
cascadeCameraFrustum.aspect = projection.aspect;
cascadeCameraFrustum.height = projection.height;
cascadeCameraFrustum.near = cascIdx > 0 ? splits[cascIdx - 1] : projection.near;
cascadeCameraFrustum.far = splits[cascIdx];
FrustumPoints fp;
fp.Update(cascadeCameraFrustum, cameraTransform);
// Calculate frusta for light perspective
// Calculate enclosing sphere
Vec3f farPlaneCenter = (cameraTransform * Vec4f(0.0f, 0.0f, -splits[cascIdx], 1.0f)).xyz();
float resolution = static_cast<float>(GetShadowCascadeResolution());
float roundingMarginFactor = resolution / (resolution - 1.0f);
Vec3f sphereCenter;
float radius;
// Near plane points are closer than far plane points
if ((fp.points[0] - farPlaneCenter).SqrMagnitude() < (fp.points[4] - farPlaneCenter).SqrMagnitude())
{
// Optimal sphere center is at far plane center
sphereCenter = farPlaneCenter;
radius = (fp.points[4] - farPlaneCenter).Magnitude() * roundingMarginFactor;
}
else // Near plane points are farther than far plane points
{
// Need to calculate optimal position for sphere center
// Consider as a 2D corner to corner cross-section of frustum
// Average of near and far depths
float cascadeHalfDepth = (cascadeCameraFrustum.far + cascadeCameraFrustum.near) * 0.5f;
// Distance from center axis to frustum corner line at halfway depth
float midHalfWidth = cascadeHalfDepth * crossHalfFovTan;
// Sphere center offset from frustum center line halfway point
float offsetFromFrustumCenter = midHalfWidth * crossHalfFovTan;
// Sphere center depth from camera
float sphereDepth = cascadeHalfDepth + offsetFromFrustumCenter;
sphereCenter = (cameraTransform * Vec4f(0.0f, 0.0f, -sphereDepth, 1.0f)).xyz();
radius = (sphereCenter - fp.points[0]).Magnitude() * roundingMarginFactor;
}
Vec3f from = sphereCenter - lightDirection * radius;
Mat4x4f lightModelTransform = Mat4x4f::LookAt(from, sphereCenter, up);
Mat4x4f lightViewTransform = lightModelTransform.GetInverse();
float diameter = radius * 2.0f;
const float frontShadowRenderingDistance = 500.0f;
ProjectionParameters cascProj;
cascProj.projection = ProjectionType::Orthographic;
cascProj.aspect = 1.0f;
cascProj.height = diameter;
cascProj.near = -frontShadowRenderingDistance;
cascProj.far = diameter;
// Calculate rounding in shadow map space to remove edge shimmer
Mat4x4f shadowMatrix = cascProj.GetProjectionMatrix() * lightViewTransform;
Vec4f originShadowSpace = shadowMatrix * Vec4f(0.0f, 0.0f, 0.0f, 1.0f) * resolution * 0.5f;
Vec4f roundedOrigin(std::round(originShadowSpace.x), std::round(originShadowSpace.y), 0.0f, 0.0f);
Vec4f offsetShadowSpace = (roundedOrigin - originShadowSpace) * (2.0f / resolution);
Vec3f offsetWs = (lightDirX * offsetShadowSpace.x + lightDirY * offsetShadowSpace.y) * radius;
// Because we don't return projection as a matrix, we have to add the offset to the view transform
transformsOut[cascIdx] = Mat4x4f::LookAt(from - offsetWs, sphereCenter - offsetWs, up);
projectionsOut[cascIdx] = cascProj;
}
}
void CalculateSplitDepths(const ProjectionParameters& projection, float* depthsOut)
{
CalculateSplitDepths(projection.near, projection.far, depthsOut);
}
void CalculateSplitDepths(float near, float far, float* depthsOut)
{
const float maxShadowDistance = 100.0f;
const float shadowSplitLogFactor = 0.8f;
far = std::min(maxShadowDistance, far);
float i_f = 1.0f;
unsigned int cascadeCountInt = GetCascadeCount();
float cascadeCountFloat = static_cast<float>(cascadeCountInt);
for (unsigned int i = 0; i < cascadeCountInt - 1; i++, i_f += 1.0f)
{
depthsOut[i] = Math::Lerp(
near + (i_f / cascadeCountFloat) * (far - near),
near * std::powf(far / near, i_f / cascadeCountFloat),
shadowSplitLogFactor);
}
depthsOut[cascadeCountInt - 1] = far;
}
} // namespace CascadedShadowMap
<|endoftext|>
|
<commit_before>// Copyright 2018 Google LLC
//
// 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 "bigtable/client/instance_admin.h"
#include "bigtable/client/internal/make_unique.h"
#include <gmock/gmock.h>
namespace {
class InstanceTestEnvironment : public ::testing::Environment {
public:
explicit InstanceTestEnvironment(std::string project) {
project_id_ = std::move(project);
}
static std::string const& project_id() { return project_id_; }
private:
static std::string project_id_;
};
std::string InstanceTestEnvironment::project_id_;
class InstanceAdminIntegrationTest : public ::testing::Test {
protected:
void SetUp() override {
auto instance_admin_client = bigtable::CreateDefaultInstanceAdminClient(
InstanceTestEnvironment::project_id(), bigtable::ClientOptions());
instance_admin_ = bigtable::internal::make_unique<bigtable::InstanceAdmin>(
instance_admin_client);
}
protected:
std::unique_ptr<bigtable::InstanceAdmin> instance_admin_;
};
bool UsingCloudBigtableEmulator() {
return std::getenv("BIGTABLE_EMULATOR_HOST") != nullptr;
}
bool IsInstancePresent(
std::vector<::google::bigtable::admin::v2::Instance> instances,
std::string const& instance_name) {
bool instance_present = false;
for (auto const& i : instances) {
if (instance_name == i.name()) {
instance_present = true;
std::cout << "Instance Name " << i.name();
break;
}
}
return instance_present;
}
} // namespace
/// @test Verify that InstanceAdmin::ListInstances works as expected.
TEST_F(InstanceAdminIntegrationTest, ListInstancesTest) {
// The emulator does not support instance operations.
if (UsingCloudBigtableEmulator()) {
return;
}
auto instances = instance_admin_->ListInstances();
for (auto const& i : instances) {
auto const npos = std::string::npos;
EXPECT_NE(npos, i.name().find(instance_admin_->project_name()));
}
}
/// @test Verify that InstanceAdmin::DeleteInstances works as expected.
TEST_F(InstanceAdminIntegrationTest, DeleteInstancesTest) {
// The emulator does not support instance operations.
if (UsingCloudBigtableEmulator()) {
return;
}
std::string instance_id = "DeleteInstancesTest_instance";
bigtable::InstanceId instance(instance_id);
bigtable::DisplayName diplay_name(instance_id);
EXPECT_FALSE(
IsInstancePresent(instance_admin_->ListInstances(), instance_id));
std::vector<std::pair<std::string, bigtable::ClusterConfig>> clusters;
clusters.push_back(std::make_pair(
"sample-cluster",
bigtable::ClusterConfig("sample-cluster", 1,
google::bigtable::admin::v2::StorageType::HDD)));
auto instance_config =
bigtable::InstanceConfig(instance, diplay_name, clusters);
instance_admin_->CreateInstance(instance_config);
EXPECT_TRUE(IsInstancePresent(instance_admin_->ListInstances(), instance_id));
instance_admin_->DeleteInstance(instance_id);
EXPECT_FALSE(
IsInstancePresent(instance_admin_->ListInstances(), instance_id));
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
if (argc != 2) {
std::string const cmd = argv[0];
auto last_slash = std::string(cmd).find_last_of('/');
// Show usage if number of arguments is invalid.
std::cerr << "Usage: " << cmd.substr(last_slash + 1) << " <project_id>"
<< std::endl;
return 1;
}
std::string const project_id = argv[1];
(void)::testing::AddGlobalTestEnvironment(
new InstanceTestEnvironment(project_id));
return RUN_ALL_TESTS();
}
<commit_msg>Fix the DeleteInstance integration test. (#476)<commit_after>// Copyright 2018 Google LLC
//
// 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 "bigtable/client/instance_admin.h"
#include "bigtable/client/internal/make_unique.h"
#include <gmock/gmock.h>
namespace {
class InstanceTestEnvironment : public ::testing::Environment {
public:
explicit InstanceTestEnvironment(std::string project) {
project_id_ = std::move(project);
}
static std::string const& project_id() { return project_id_; }
private:
static std::string project_id_;
};
std::string InstanceTestEnvironment::project_id_;
class InstanceAdminIntegrationTest : public ::testing::Test {
protected:
void SetUp() override {
auto instance_admin_client = bigtable::CreateDefaultInstanceAdminClient(
InstanceTestEnvironment::project_id(), bigtable::ClientOptions());
instance_admin_ = bigtable::internal::make_unique<bigtable::InstanceAdmin>(
instance_admin_client);
}
protected:
std::unique_ptr<bigtable::InstanceAdmin> instance_admin_;
};
bool UsingCloudBigtableEmulator() {
return std::getenv("BIGTABLE_EMULATOR_HOST") != nullptr;
}
bool IsInstancePresent(
std::vector<::google::bigtable::admin::v2::Instance> instances,
std::string const& instance_name) {
for (auto const& i : instances) {
if (instance_name == i.name()) {
return true;
}
}
return false;
}
} // namespace
/// @test Verify that InstanceAdmin::ListInstances works as expected.
TEST_F(InstanceAdminIntegrationTest, ListInstancesTest) {
// The emulator does not support instance operations.
if (UsingCloudBigtableEmulator()) {
return;
}
auto instances = instance_admin_->ListInstances();
for (auto const& i : instances) {
auto const npos = std::string::npos;
EXPECT_NE(npos, i.name().find(instance_admin_->project_name()));
}
}
/// @test Verify that InstanceAdmin::DeleteInstances works as expected.
TEST_F(InstanceAdminIntegrationTest, DeleteInstancesTest) {
// The emulator does not support instance operations.
if (UsingCloudBigtableEmulator()) {
return;
}
std::string id = "delete-instance-test";
bigtable::InstanceId instance_id(id);
bigtable::DisplayName display_name(id);
EXPECT_FALSE(
IsInstancePresent(instance_admin_->ListInstances(),
instance_admin_->project_name() + "/instances/" + id));
std::vector<std::pair<std::string, bigtable::ClusterConfig>> clusters;
clusters.push_back(std::make_pair(
id + "-c1", bigtable::ClusterConfig("us-central1-f", 0,
bigtable::ClusterConfig::HDD)));
auto instance_config =
bigtable::InstanceConfig(instance_id, display_name, clusters)
.set_type(bigtable::InstanceConfig::DEVELOPMENT);
auto instance_details =
instance_admin_->CreateInstance(instance_config).get();
EXPECT_NE(std::string::npos, instance_details.name().find(id));
EXPECT_TRUE(IsInstancePresent(instance_admin_->ListInstances(),
instance_details.name()));
instance_admin_->DeleteInstance(id);
EXPECT_FALSE(IsInstancePresent(instance_admin_->ListInstances(),
instance_details.name()));
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
if (argc != 2) {
std::string const cmd = argv[0];
auto last_slash = std::string(cmd).find_last_of('/');
// Show usage if number of arguments is invalid.
std::cerr << "Usage: " << cmd.substr(last_slash + 1) << " <project_id>"
<< std::endl;
return 1;
}
std::string const project_id = argv[1];
(void)::testing::AddGlobalTestEnvironment(
new InstanceTestEnvironment(project_id));
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>// -*- c-basic-offset: 8; indent-tabs: nil -*-
//
// See LICENSE for details.
//
#include <smoke.h>
#include <smoke/qtcore_smoke.h>
#include <Qt/qstring.h>
#include <Qt/qstringlist.h>
#include <Qt/qpointer.h>
#include <Qt/qmetaobject.h>
#include <QtCore/qobject.h>
#include <QtGui/qapplication.h>
#include "commonqt.h"
// #define DEBUG 1
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
typedef void (*t_deletion_callback)(void*, void*);
typedef bool (*t_callmethod_callback)(void*, short, void*, void*, bool);
typedef void (*t_child_callback)(void*, bool, void*);
class Binding : public SmokeBinding
{
public:
Binding(Smoke* s) : SmokeBinding(s) {}
t_deletion_callback deletion_callback;
t_callmethod_callback callmethod_callback;
t_child_callback child_callback;
void deleted(Smoke::Index, void* obj) {
deletion_callback(smoke, obj);
}
bool callMethod(Smoke::Index method, void* obj,
Smoke::Stack args, bool isAbstract)
{
Smoke::Method* m = &smoke->methods[method];
const char* name = smoke->methodNames[m->name];
Smoke::Class* c = &smoke->classes[m->classId];
if (*name == '~')
callmethod_callback(smoke, method, obj, args, isAbstract);
else if (!strcmp(name, "notify")
&& (!strcmp(c->className, "QApplication")
|| !strcmp(c->className, "QCoreApplication")))
{
QEvent* e = (QEvent*) args[2].s_voidp;
if (e->type() == QEvent::ChildAdded
|| e->type() == QEvent::ChildRemoved)
{
QChildEvent* f = (QChildEvent*) e;
child_callback(smoke, f->added(), f->child());
}
}
return false;
}
char* className(Smoke::Index classId) {
return (char*) smoke->classes[classId].className;
}
};
class DynamicBinding : public Binding
{
public:
DynamicBinding(Smoke* s) : Binding(s) {}
bool callMethod(Smoke::Index method, void* obj,
Smoke::Stack args, bool isAbstract)
{
return callmethod_callback(smoke, method, obj, args, isAbstract);
}
};
void
sw_smoke(Smoke* smoke,
SmokeData* data,
void* deletion_callback,
void* method_callback,
void* child_callback)
{
Binding* binding = new Binding(smoke);
DynamicBinding* dynamicBinding = new DynamicBinding(smoke);
data->name = smoke->moduleName();
data->classes = smoke->classes;
data->numClasses = smoke->numClasses;
data->methods = smoke->methods;
data->numMethods = smoke->numMethods;
data->methodMaps = smoke->methodMaps;
data->numMethodMaps = smoke->numMethodMaps;
data->methodNames = smoke->methodNames;
data->numMethodNames = smoke->numMethodNames;
data->types = smoke->types;
data->numTypes = smoke->numTypes;
data->inheritanceList = smoke->inheritanceList;
data->argumentList = smoke->argumentList;
data->ambiguousMethodList = smoke->ambiguousMethodList;
data->castFn = (void *) smoke->castFn;
dynamicBinding->deletion_callback
= (t_deletion_callback) deletion_callback;
dynamicBinding->callmethod_callback
= (t_callmethod_callback) method_callback;
dynamicBinding->child_callback
= (t_child_callback) child_callback;
binding->deletion_callback = dynamicBinding->deletion_callback;
binding->callmethod_callback = dynamicBinding->callmethod_callback;
binding->child_callback = dynamicBinding->child_callback;
data->thin = binding;
data->fat = dynamicBinding;
}
int
sw_windows_version()
{
#ifdef WINDOWS
return QSysInfo::windowsVersion();
#else
return -1;
#endif
}
// void*
// sw_make_qstring(char *str)
// {
// QString* qstr = new QString();
// *qstr = QString::fromUtf8(str);
// return qstr;
// }
void*
sw_make_qstring(char *str)
{
return new QString(QString::fromUtf8(str));
}
void*
sw_qstring_to_utf8(void* s)
{
QString* str = (QString*) s;
return new QByteArray(str->toUtf8());
}
const void*
sw_qstring_to_utf16(void* s)
{
QString* str = static_cast<QString*>(s);
return str->utf16();
}
void
sw_delete_qstring(void *q)
{
delete (QString*) q;
}
void*
sw_make_qstringlist()
{
return new QStringList();
}
void
sw_delete_qstringlist(void *q)
{
delete static_cast<QStringList*>(q);
}
void
sw_qstringlist_append(void *q, char *x)
{
static_cast<QStringList*>(q)->append(QString(x));
}
void*
sw_make_metaobject(void *p, char *strings, int *d)
{
QMetaObject* parent = (QMetaObject*) p;
const uint* data = (const uint*) d;
QMetaObject tmp = { { parent, strings, data, 0 } };
QMetaObject* ptr = new QMetaObject;
*ptr = tmp;
return ptr;
}
void
sw_delete(void *p)
{
QObject* q = (QObject*) p;
delete q;
}
typedef void (*t_ptr_callback)(void *);
void
sw_find_class(char *name, Smoke **smoke, short *index)
{
Smoke::ModuleIndex mi = qtcore_Smoke->findClass(name);
*smoke = mi.smoke;
*index = mi.index;
}
short
sw_id_instance_class(void *ptr, Smoke **smoke, short *index)
{
Smoke::ModuleIndex mi = qtcore_Smoke->findClass(((QObject*)ptr)->metaObject()->className());
*smoke = mi.smoke;
*index = mi.index;
}
short
sw_find_name(Smoke *smoke, char *name)
{
Smoke::ModuleIndex mi = smoke->idMethodName(name);
return mi.index;
}
short
sw_id_method(Smoke *smoke, short classIndex, short name)
{
Smoke::ModuleIndex mi = smoke->idMethod(classIndex, name);
return mi.index;
}
short
sw_id_type(Smoke *smoke, char *name)
{
return smoke->idType(name);
}
short
sw_id_class(Smoke *smoke, char *name, bool external)
{
return smoke->idClass(name, external).index;
}
// QList marshalling
void*
sw_qlist_void_new()
{
return new QList<void*>;
}
int
sw_qlist_void_size(void *ptr)
{
QList<void*>* qlist = static_cast<QList<void*>*>(ptr);
return qlist->size();
}
void
sw_qlist_void_delete(void *ptr)
{
QList<void*>* qlist = static_cast<QList<void*>*>(ptr);
delete qlist;
}
const void*
sw_qlist_void_at(void *ptr, int index)
{
QList<void*>* qlist = static_cast<QList<void*>*>(ptr);
return qlist->at(index);
}
void
sw_qlist_void_append(void *ptr, void *whatptr)
{
QList<void*>* qlist = static_cast<QList<void*>*>(ptr);
qlist->append(whatptr);
}
const void* sw_qlist_scalar_at(void *ptr, int index)
{
QList<int>* qlist = static_cast<QList<int>*>(ptr);
return &qlist->at(index);
}
<commit_msg>"Inclusion of header files from include/Qt is deprecated."<commit_after>// -*- c-basic-offset: 8; indent-tabs: nil -*-
//
// See LICENSE for details.
//
#include <smoke.h>
#include <smoke/qtcore_smoke.h>
#include <QStringList>
#include <QPointer>
#include <QMetaObject>
#include <QObject>
#include <QApplication>
#include "commonqt.h"
// #define DEBUG 1
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
typedef void (*t_deletion_callback)(void*, void*);
typedef bool (*t_callmethod_callback)(void*, short, void*, void*, bool);
typedef void (*t_child_callback)(void*, bool, void*);
class Binding : public SmokeBinding
{
public:
Binding(Smoke* s) : SmokeBinding(s) {}
t_deletion_callback deletion_callback;
t_callmethod_callback callmethod_callback;
t_child_callback child_callback;
void deleted(Smoke::Index, void* obj) {
deletion_callback(smoke, obj);
}
bool callMethod(Smoke::Index method, void* obj,
Smoke::Stack args, bool isAbstract)
{
Smoke::Method* m = &smoke->methods[method];
const char* name = smoke->methodNames[m->name];
Smoke::Class* c = &smoke->classes[m->classId];
if (*name == '~')
callmethod_callback(smoke, method, obj, args, isAbstract);
else if (!strcmp(name, "notify")
&& (!strcmp(c->className, "QApplication")
|| !strcmp(c->className, "QCoreApplication")))
{
QEvent* e = (QEvent*) args[2].s_voidp;
if (e->type() == QEvent::ChildAdded
|| e->type() == QEvent::ChildRemoved)
{
QChildEvent* f = (QChildEvent*) e;
child_callback(smoke, f->added(), f->child());
}
}
return false;
}
char* className(Smoke::Index classId) {
return (char*) smoke->classes[classId].className;
}
};
class DynamicBinding : public Binding
{
public:
DynamicBinding(Smoke* s) : Binding(s) {}
bool callMethod(Smoke::Index method, void* obj,
Smoke::Stack args, bool isAbstract)
{
return callmethod_callback(smoke, method, obj, args, isAbstract);
}
};
void
sw_smoke(Smoke* smoke,
SmokeData* data,
void* deletion_callback,
void* method_callback,
void* child_callback)
{
Binding* binding = new Binding(smoke);
DynamicBinding* dynamicBinding = new DynamicBinding(smoke);
data->name = smoke->moduleName();
data->classes = smoke->classes;
data->numClasses = smoke->numClasses;
data->methods = smoke->methods;
data->numMethods = smoke->numMethods;
data->methodMaps = smoke->methodMaps;
data->numMethodMaps = smoke->numMethodMaps;
data->methodNames = smoke->methodNames;
data->numMethodNames = smoke->numMethodNames;
data->types = smoke->types;
data->numTypes = smoke->numTypes;
data->inheritanceList = smoke->inheritanceList;
data->argumentList = smoke->argumentList;
data->ambiguousMethodList = smoke->ambiguousMethodList;
data->castFn = (void *) smoke->castFn;
dynamicBinding->deletion_callback
= (t_deletion_callback) deletion_callback;
dynamicBinding->callmethod_callback
= (t_callmethod_callback) method_callback;
dynamicBinding->child_callback
= (t_child_callback) child_callback;
binding->deletion_callback = dynamicBinding->deletion_callback;
binding->callmethod_callback = dynamicBinding->callmethod_callback;
binding->child_callback = dynamicBinding->child_callback;
data->thin = binding;
data->fat = dynamicBinding;
}
int
sw_windows_version()
{
#ifdef WINDOWS
return QSysInfo::windowsVersion();
#else
return -1;
#endif
}
// void*
// sw_make_qstring(char *str)
// {
// QString* qstr = new QString();
// *qstr = QString::fromUtf8(str);
// return qstr;
// }
void*
sw_make_qstring(char *str)
{
return new QString(QString::fromUtf8(str));
}
void*
sw_qstring_to_utf8(void* s)
{
QString* str = (QString*) s;
return new QByteArray(str->toUtf8());
}
const void*
sw_qstring_to_utf16(void* s)
{
QString* str = static_cast<QString*>(s);
return str->utf16();
}
void
sw_delete_qstring(void *q)
{
delete (QString*) q;
}
void*
sw_make_qstringlist()
{
return new QStringList();
}
void
sw_delete_qstringlist(void *q)
{
delete static_cast<QStringList*>(q);
}
void
sw_qstringlist_append(void *q, char *x)
{
static_cast<QStringList*>(q)->append(QString(x));
}
void*
sw_make_metaobject(void *p, char *strings, int *d)
{
QMetaObject* parent = (QMetaObject*) p;
const uint* data = (const uint*) d;
QMetaObject tmp = { { parent, strings, data, 0 } };
QMetaObject* ptr = new QMetaObject;
*ptr = tmp;
return ptr;
}
void
sw_delete(void *p)
{
QObject* q = (QObject*) p;
delete q;
}
typedef void (*t_ptr_callback)(void *);
void
sw_find_class(char *name, Smoke **smoke, short *index)
{
Smoke::ModuleIndex mi = qtcore_Smoke->findClass(name);
*smoke = mi.smoke;
*index = mi.index;
}
short
sw_id_instance_class(void *ptr, Smoke **smoke, short *index)
{
Smoke::ModuleIndex mi = qtcore_Smoke->findClass(((QObject*)ptr)->metaObject()->className());
*smoke = mi.smoke;
*index = mi.index;
}
short
sw_find_name(Smoke *smoke, char *name)
{
Smoke::ModuleIndex mi = smoke->idMethodName(name);
return mi.index;
}
short
sw_id_method(Smoke *smoke, short classIndex, short name)
{
Smoke::ModuleIndex mi = smoke->idMethod(classIndex, name);
return mi.index;
}
short
sw_id_type(Smoke *smoke, char *name)
{
return smoke->idType(name);
}
short
sw_id_class(Smoke *smoke, char *name, bool external)
{
return smoke->idClass(name, external).index;
}
// QList marshalling
void*
sw_qlist_void_new()
{
return new QList<void*>;
}
int
sw_qlist_void_size(void *ptr)
{
QList<void*>* qlist = static_cast<QList<void*>*>(ptr);
return qlist->size();
}
void
sw_qlist_void_delete(void *ptr)
{
QList<void*>* qlist = static_cast<QList<void*>*>(ptr);
delete qlist;
}
const void*
sw_qlist_void_at(void *ptr, int index)
{
QList<void*>* qlist = static_cast<QList<void*>*>(ptr);
return qlist->at(index);
}
void
sw_qlist_void_append(void *ptr, void *whatptr)
{
QList<void*>* qlist = static_cast<QList<void*>*>(ptr);
qlist->append(whatptr);
}
const void* sw_qlist_scalar_at(void *ptr, int index)
{
QList<int>* qlist = static_cast<QList<int>*>(ptr);
return &qlist->at(index);
}
<|endoftext|>
|
<commit_before>#include "FCStdAfx.h"
#include "HAL.h"
#include "RC_Comms.h"
#include "GS_Comms.h"
#include "utils/Clock.h"
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <sys/time.h>
#include <sys/resource.h>
//#include <boost/program_options.hpp>
#include <thread>
#include <iostream>
#include <malloc.h>
size_t s_test = 0;
bool s_exit = false;
boost::asio::io_service s_async_io_service;
struct Memory
{
size_t allocation_count = 0;
size_t free_count = 0;
} s_memory;
namespace boost
{
void throw_exception(std::exception const & e)
{
QLOGE("boost::exception {}", e.what());
throw e;
}
}
namespace silk
{
void execute_async_call(std::function<void()> f)
{
s_async_io_service.post(f);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/* This prints an "Assertion failed" message and aborts. */
void __assert_fail(const char *__assertion, const char *__file, unsigned int __line, const char *__function)
{
QASSERT_MSG(false, "assert: {}:{}: {}: {}", __file, __line, __function, __assertion);
}
//static void* malloc_hook(size_t size, const void* caller)
//{
// s_memory.allocation_count++;
// __malloc_hook = nullptr;
// printf("\n%d, %d", int(s_memory.allocation_count), int(s_memory.free_count));
// fflush(stdout);
// void* ptr = malloc(size);
// __malloc_hook = &malloc_hook;
// return ptr;
//}
//void free_hook(void* ptr, const void* caller)
//{
// s_memory.free_count++;
// __free_hook = nullptr;
// printf("\n%d, %d", int(s_memory.allocation_count), int(s_memory.free_count));
// fflush(stdout);
// free(ptr);
// __free_hook = &free_hook;
//}
// Define the function to be called when ctrl-c (SIGINT) signal is sent to process
void signal_handler(int signum)
{
if (s_exit)
{
QLOGI("Forcing an exit due to signal {}", signum);
abort();
}
s_exit = true;
QLOGI("Exitting due to signal {}", signum);
}
void out_of_memory_handler()
{
QLOGE("Out of memory");
std::abort();
}
int main(int argc, char const* argv[])
{
signal(SIGINT, signal_handler); // Trap basic signals (exit cleanly)
signal(SIGKILL, signal_handler);
signal(SIGUSR1, signal_handler);
signal(SIGQUIT, signal_handler);
// signal(SIGABRT, signal_handler);
signal(SIGTERM, signal_handler);
//__malloc_hook = &malloc_hook;
//__free_hook = &free_hook;
//set the new_handler
std::set_new_handler(out_of_memory_handler);
std::srand(std::time(0));
q::logging::add_logger(q::logging::Logger_uptr(new q::logging::Console_Logger()));
q::logging::set_decorations(q::logging::Decorations(q::logging::Decoration::TIMESTAMP, q::logging::Decoration::LEVEL, q::logging::Decoration::TOPIC));
QLOG_TOPIC("silk");
// namespace po = boost::program_options;
// po::options_description desc("Options");
// desc.add_options()
// ("help", "produce help message")
// ("blind", "no camera")
// ("test", po::value<size_t>(), "test");
// po::variables_map vm;
// po::store(po::parse_command_line(argc, argv, desc), vm);
// po::notify(vm);
// if (vm.count("help"))
// {
// std::cout << desc << "\n";
// return 1;
// }
// s_test = vm.count("test") ? vm["test"].as<size_t>() : size_t(0);
// //bool blind = vm.count("blind") != 0;
QLOGI("Creating io_service thread");
boost::shared_ptr<boost::asio::io_service::work> async_work(new boost::asio::io_service::work(s_async_io_service));
auto async_thread = boost::thread([]() { s_async_io_service.run(); });
#if defined RASPBERRY_PI
{
int policy = SCHED_FIFO;
struct sched_param param;
param.sched_priority = sched_get_priority_max(policy);
if (pthread_setschedparam(pthread_self(), policy, ¶m) != 0)
{
perror("Failed to set priority for main thread");
//exit(EXIT_FAILURE);
}
policy = SCHED_IDLE;
param.sched_priority = sched_get_priority_min(policy);
if (pthread_setschedparam(async_thread.native_handle(), policy, ¶m) != 0)
{
perror("Failed to set priority for async thread");
//exit(EXIT_FAILURE);
}
}
#endif
try
{
silk::HAL hal;
silk::RC_Comms rc_comms(hal);
silk::GS_Comms gs_comms(hal, rc_comms);
if (!hal.init(rc_comms, gs_comms))
{
QLOGE("Hardware failure! Aborting");
goto exit;
}
if (!rc_comms.start("wlan1", 3))
{
QLOGW("Cannot start rc communication channel!");
// goto exit;
}
if (!gs_comms.start_udp(8005, 8006))
{
QLOGE("Cannot start gs communication channel! Aborting");
goto exit;
}
// while (!s_exit)
// {
// std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// QLOGI("Waiting for comms to connect...");
// if (comms.is_connected())
// {
// break;
// }
// }
QLOGI("All systems up. Ready to fly...");
{
constexpr std::chrono::microseconds PERIOD(5000);
auto last = Clock::now();
while (!s_exit)
{
auto start = Clock::now();
auto dt = start - last;
last = start;
#ifdef NDEBUG
if (dt > std::chrono::milliseconds(5))
#else
if (dt > std::chrono::milliseconds(50))
#endif
{
QLOGW("Process Latency of {}!!!!!", dt);
}
gs_comms.process();
rc_comms.process();
hal.process();
//No sleeping here!!! process as fast as possible as the nodes are not always in the ideal order
// and out of order nodes will be processes next 'frame'. So the quicker the frames, the smaller the lag between nodes
#ifndef RASPBERRY_PI
std::this_thread::sleep_for(std::chrono::milliseconds(1));
#endif
// {
// static Clock::time_point last_timestamp = Clock::now();
// auto now = Clock::now();
// auto dt = now - last_timestamp;
// last_timestamp = now;
// static Clock::duration min_dt, max_dt, avg_dt;
// static int xxx = 0;
// min_dt = std::min(min_dt, dt);
// max_dt = std::max(max_dt, dt);
// avg_dt += dt;
// xxx++;
// static Clock::time_point xxx_timestamp = Clock::now();
// if (now - xxx_timestamp >= std::chrono::milliseconds(1000))
// {
// xxx_timestamp = now;
// QLOGI("min {}, max {}, avg {}", min_dt, max_dt, avg_dt/ xxx);
// min_dt = dt;
// max_dt = dt;
// avg_dt = std::chrono::milliseconds(0);
// xxx = 0;
// }
// }
}
}
exit:
QLOGI("Stopping everything");
//stop threads
async_work.reset();
s_async_io_service.stop();
if (async_thread.joinable())
{
std::this_thread::yield();
async_thread.join();
}
hal.shutdown();
}
catch (std::exception const& e)
{
QLOGE("exception: {}", e.what());
abort();
}
QLOGI("Closing");
}
<commit_msg>API fix<commit_after>#include "FCStdAfx.h"
#include "HAL.h"
#include "RC_Comms.h"
#include "GS_Comms.h"
#include "utils/Clock.h"
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <sys/time.h>
#include <sys/resource.h>
//#include <boost/program_options.hpp>
#include <thread>
#include <iostream>
#include <malloc.h>
size_t s_test = 0;
bool s_exit = false;
boost::asio::io_service s_async_io_service;
struct Memory
{
size_t allocation_count = 0;
size_t free_count = 0;
} s_memory;
namespace boost
{
void throw_exception(std::exception const & e)
{
QLOGE("boost::exception {}", e.what());
throw e;
}
}
namespace silk
{
void execute_async_call(std::function<void()> f)
{
s_async_io_service.post(f);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/* This prints an "Assertion failed" message and aborts. */
void __assert_fail(const char *__assertion, const char *__file, unsigned int __line, const char *__function)
{
QASSERT_MSG(false, "assert: {}:{}: {}: {}", __file, __line, __function, __assertion);
}
//static void* malloc_hook(size_t size, const void* caller)
//{
// s_memory.allocation_count++;
// __malloc_hook = nullptr;
// printf("\n%d, %d", int(s_memory.allocation_count), int(s_memory.free_count));
// fflush(stdout);
// void* ptr = malloc(size);
// __malloc_hook = &malloc_hook;
// return ptr;
//}
//void free_hook(void* ptr, const void* caller)
//{
// s_memory.free_count++;
// __free_hook = nullptr;
// printf("\n%d, %d", int(s_memory.allocation_count), int(s_memory.free_count));
// fflush(stdout);
// free(ptr);
// __free_hook = &free_hook;
//}
// Define the function to be called when ctrl-c (SIGINT) signal is sent to process
void signal_handler(int signum)
{
if (s_exit)
{
QLOGI("Forcing an exit due to signal {}", signum);
abort();
}
s_exit = true;
QLOGI("Exitting due to signal {}", signum);
}
void out_of_memory_handler()
{
QLOGE("Out of memory");
std::abort();
}
int main(int argc, char const* argv[])
{
signal(SIGINT, signal_handler); // Trap basic signals (exit cleanly)
signal(SIGKILL, signal_handler);
signal(SIGUSR1, signal_handler);
signal(SIGQUIT, signal_handler);
// signal(SIGABRT, signal_handler);
signal(SIGTERM, signal_handler);
//__malloc_hook = &malloc_hook;
//__free_hook = &free_hook;
//set the new_handler
std::set_new_handler(out_of_memory_handler);
std::srand(std::time(0));
q::logging::add_logger(q::logging::Logger_uptr(new q::logging::Console_Logger()));
q::logging::set_decorations(q::logging::Decorations(q::logging::Decoration::TIMESTAMP, q::logging::Decoration::LEVEL, q::logging::Decoration::TOPIC));
QLOG_TOPIC("silk");
// namespace po = boost::program_options;
// po::options_description desc("Options");
// desc.add_options()
// ("help", "produce help message")
// ("blind", "no camera")
// ("test", po::value<size_t>(), "test");
// po::variables_map vm;
// po::store(po::parse_command_line(argc, argv, desc), vm);
// po::notify(vm);
// if (vm.count("help"))
// {
// std::cout << desc << "\n";
// return 1;
// }
// s_test = vm.count("test") ? vm["test"].as<size_t>() : size_t(0);
// //bool blind = vm.count("blind") != 0;
QLOGI("Creating io_service thread");
boost::shared_ptr<boost::asio::io_service::work> async_work(new boost::asio::io_service::work(s_async_io_service));
auto async_thread = boost::thread([]() { s_async_io_service.run(); });
#if defined RASPBERRY_PI
{
int policy = SCHED_FIFO;
struct sched_param param;
param.sched_priority = sched_get_priority_max(policy);
if (pthread_setschedparam(pthread_self(), policy, ¶m) != 0)
{
perror("Failed to set priority for main thread");
//exit(EXIT_FAILURE);
}
policy = SCHED_IDLE;
param.sched_priority = sched_get_priority_min(policy);
if (pthread_setschedparam(async_thread.native_handle(), policy, ¶m) != 0)
{
perror("Failed to set priority for async thread");
//exit(EXIT_FAILURE);
}
}
#endif
try
{
silk::HAL hal;
silk::RC_Comms rc_comms(hal);
silk::GS_Comms gs_comms(hal, rc_comms);
if (!hal.init(rc_comms, gs_comms))
{
QLOGE("Hardware failure! Aborting");
goto exit;
}
if (!rc_comms.start())
{
QLOGW("Cannot start rc communication channel!");
goto exit;
}
if (!gs_comms.start_udp(8005, 8006))
{
QLOGE("Cannot start gs communication channel! Aborting");
goto exit;
}
// while (!s_exit)
// {
// std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// QLOGI("Waiting for comms to connect...");
// if (comms.is_connected())
// {
// break;
// }
// }
QLOGI("All systems up. Ready to fly...");
{
constexpr std::chrono::microseconds PERIOD(5000);
auto last = Clock::now();
while (!s_exit)
{
auto start = Clock::now();
auto dt = start - last;
last = start;
#ifdef NDEBUG
if (dt > std::chrono::milliseconds(5))
#else
if (dt > std::chrono::milliseconds(50))
#endif
{
QLOGW("Process Latency of {}!!!!!", dt);
}
gs_comms.process();
rc_comms.process();
hal.process();
//No sleeping here!!! process as fast as possible as the nodes are not always in the ideal order
// and out of order nodes will be processes next 'frame'. So the quicker the frames, the smaller the lag between nodes
#ifndef RASPBERRY_PI
std::this_thread::sleep_for(std::chrono::milliseconds(1));
#endif
// {
// static Clock::time_point last_timestamp = Clock::now();
// auto now = Clock::now();
// auto dt = now - last_timestamp;
// last_timestamp = now;
// static Clock::duration min_dt, max_dt, avg_dt;
// static int xxx = 0;
// min_dt = std::min(min_dt, dt);
// max_dt = std::max(max_dt, dt);
// avg_dt += dt;
// xxx++;
// static Clock::time_point xxx_timestamp = Clock::now();
// if (now - xxx_timestamp >= std::chrono::milliseconds(1000))
// {
// xxx_timestamp = now;
// QLOGI("min {}, max {}, avg {}", min_dt, max_dt, avg_dt/ xxx);
// min_dt = dt;
// max_dt = dt;
// avg_dt = std::chrono::milliseconds(0);
// xxx = 0;
// }
// }
}
}
exit:
QLOGI("Stopping everything");
//stop threads
async_work.reset();
s_async_io_service.stop();
if (async_thread.joinable())
{
std::this_thread::yield();
async_thread.join();
}
hal.shutdown();
}
catch (std::exception const& e)
{
QLOGE("exception: {}", e.what());
abort();
}
QLOGI("Closing");
}
<|endoftext|>
|
<commit_before>/* This file is part of the Palabos library.
*
* Copyright (C) 2011-2015 FlowKit Sarl
* Route d'Oron 2
* 1010 Lausanne, Switzerland
* E-mail contact: contact@flowkit.com
*
* The most recent release of Palabos can be downloaded at
* <http://www.palabos.org/>
*
* The library Palabos is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* The 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Code 1.1 in the Palabos tutorial
*/
#include "palabos2D.h"
#ifndef PLB_PRECOMPILED // Unless precompiled version is used,
#include "palabos2D.hh" // include full template code
#endif
#include <vector>
#include <cmath>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace plb;
using namespace std;
typedef double T;
#define DESCRIPTOR plb::descriptors::D2Q9Descriptor
#define PI 3.14159265
// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics2D.h"
using namespace plb_acoustics;
// ---------------------------------------------
T rho0 = 1.;
T deltaRho = 1.e-4;
int main(int argc, char* argv[]) {
plbInit(&argc, &argv);
global::directories().setOutputDir("./tmp/");
plint numCores = global::mpi().getSize();
pcout << "Number of MPI threads: " << numCores << std::endl;
const plint maxIter = 3*150*sqrt(3); // Iterate during 1000 steps.
const plint nx = 300; // Choice of lattice dimensions.
const plint ny = 300;
const T omega = 1.98; // Choice of the relaxation parameter
MultiBlockLattice2D<T, DESCRIPTOR> lattice(nx, ny, new BGKdynamics<T,DESCRIPTOR>(omega));
lattice.periodicity().toggleAll(false); // Use periodic boundaries.
Array<T,2> u0((T)0,(T)0);
// Initialize constant density everywhere.
initializeAtEquilibrium(lattice, lattice.getBoundingBox(), rho0, u0);
lattice.initialize();
// Anechoic Condition
T size_anechoic_buffer = 30;
//left
plint orientation = 3;
Array<T,2> position_anechoic_wall((T)0,(T)0);
plint length_anechoic_wall = ny;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall, length_anechoic_wall);
//right
orientation = 1;
Array<T,2> position_anechoic_wall_2((T)nx - 32,(T)0);
length_anechoic_wall = ny;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall_2, length_anechoic_wall);
//top
orientation = 4;
Array<T,2> position_anechoic_wall_3((T) 20, (T)ny - 32);
length_anechoic_wall = nx - 40;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall_3, length_anechoic_wall);
//bottom
orientation = 2;
Array<T,2> position_anechoic_wall_1((T)20,(T)0);
length_anechoic_wall = nx - 40;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall_1, length_anechoic_wall);
//defineAnechoicWallOnTheLeftSide(nx, ny, lattice, size_anechoic_buffer, omega);
//defineAnechoicWallOnTheTopSide(nx, ny, lattice, size_anechoic_buffer, omega);
//defineAnechoicWallOnTheBottomSide(nx, ny, lattice, size_anechoic_buffer, omega);
//defineAnechoicWallOnTheRightSide(nx, ny, lattice, size_anechoic_buffer, omega);
//defineAnechoicWallOnTheLeftSide(nx, ny, lattice, size_anechoic_buffer, omega);
// Main loop over time iterations.
for (plint iT=0; iT<maxIter; ++iT) {
Box2D centralSquare (150, 150, 150, 150);
T lattice_speed_sound = 1/sqrt(3);
T rho_changing = 1. + deltaRho;//*sin(2*PI*(lattice_speed_sound/20)*iT);
if (iT != 0){
initializeAtEquilibrium (lattice, centralSquare, rho_changing, u0);
}
if (iT%20==0) { // Write an image every 40th time step.
pcout << "Writing GIF file at iT=" << iT << endl;
// Instantiate an image writer with the color map "leeloo".
ImageWriter<T> imageWriter("leeloo");
// Write a GIF file with colors rescaled to the range of values
// in the matrix
imageWriter.writeGif(createFileName("u", iT, 6), *computeDensity(lattice), (T) rho0 - deltaRho/1000, (T) rho0 + deltaRho/1000);
}
// Execute lattice Boltzmann iteration.
lattice.collideAndStream();
}
}
<commit_msg>Condition Anechoic works<commit_after>/* This file is part of the Palabos library.
*
* Copyright (C) 2011-2015 FlowKit Sarl
* Route d'Oron 2
* 1010 Lausanne, Switzerland
* E-mail contact: contact@flowkit.com
*
* The most recent release of Palabos can be downloaded at
* <http://www.palabos.org/>
*
* The library Palabos is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* The 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Code 1.1 in the Palabos tutorial
*/
#include "palabos2D.h"
#ifndef PLB_PRECOMPILED // Unless precompiled version is used,
#include "palabos2D.hh" // include full template code
#endif
#include <vector>
#include <cmath>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace plb;
using namespace std;
typedef double T;
#define DESCRIPTOR plb::descriptors::D2Q9Descriptor
#define PI 3.14159265
// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics2D.h"
using namespace plb_acoustics;
// ---------------------------------------------
T rho0 = 1.;
T deltaRho = 1.e-4;
int main(int argc, char* argv[]) {
plbInit(&argc, &argv);
global::directories().setOutputDir("./tmp/");
plint numCores = global::mpi().getSize();
pcout << "Number of MPI threads: " << numCores << std::endl;
const plint maxIter = 6*150*sqrt(3); // Iterate during 1000 steps.
const plint nx = 300; // Choice of lattice dimensions.
const plint ny = 300;
const T omega = 1.98; // Choice of the relaxation parameter
MultiBlockLattice2D<T, DESCRIPTOR> lattice(nx, ny, new BGKdynamics<T,DESCRIPTOR>(omega));
lattice.periodicity().toggleAll(false); // Use periodic boundaries.
Array<T,2> u0((T)0,(T)0);
// Initialize constant density everywhere.
initializeAtEquilibrium(lattice, lattice.getBoundingBox(), rho0, u0);
lattice.initialize();
// Anechoic Condition
T size_anechoic_buffer = 30;
//left
plint orientation = 3;
Array<T,2> position_anechoic_wall((T)0,(T)0);
plint length_anechoic_wall = ny;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall, length_anechoic_wall);
//right
orientation = 1;
Array<T,2> position_anechoic_wall_2((T)nx - 32,(T)0);
length_anechoic_wall = ny;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall_2, length_anechoic_wall);
//top
orientation = 4;
Array<T,2> position_anechoic_wall_3((T) 20, (T)ny - 32);
length_anechoic_wall = nx - 40;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall_3, length_anechoic_wall);
//bottom
orientation = 2;
Array<T,2> position_anechoic_wall_1((T)20,(T)0);
length_anechoic_wall = nx - 40 ;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall_1, length_anechoic_wall);
//defineAnechoicWallOnTheLeftSide(nx, ny, lattice, size_anechoic_buffer, omega);
//defineAnechoicWallOnTheTopSide(nx, ny, lattice, size_anechoic_buffer, omega);
//defineAnechoicWallOnTheBottomSide(nx, ny, lattice, size_anechoic_buffer, omega);
//defineAnechoicWallOnTheRightSide(nx, ny, lattice, size_anechoic_buffer, omega);
//defineAnechoicWallOnTheLeftSide(nx, ny, lattice, size_anechoic_buffer, omega);
// Main loop over time iterations.
plint x = 150;
plb_ofstream ofile("ponto_1.dat");
for (; x < 300; ++x){
}
for (plint iT=0; iT<maxIter; ++iT) {
Box2D centralSquare (150, 150, 150, 150);
T lattice_speed_sound = 1/sqrt(3);
T rho_changing = 1. + deltaRho;//*sin(2*PI*(lattice_speed_sound/20)*iT);
if (iT == 0){
initializeAtEquilibrium (lattice, centralSquare, rho_changing, u0);
}
if (iT%20==0) { // Write an image every 40th time step.
pcout << "Writing GIF file at iT=" << iT << endl;
// Instantiate an image writer with the color map "leeloo".
ImageWriter<T> imageWriter("leeloo");
// Write a GIF file with colors rescaled to the range of values
// in the matrix
//imageWriter.writeGif(createFileName("u", iT, 6), *computeDensity(lattice), (T) rho0 - deltaRho/1000, (T) rho0 + deltaRho/1000);
ofile << setprecision(10) << lattice.get(150, 150).computeDensity() - rho0 << endl;
}
// Execute lattice Boltzmann iteration.
lattice.collideAndStream();
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qremoteservicecontrol_p.h"
#include "ipcendpoint_p.h"
#include "objectendpoint_p.h"
#include <QLocalServer>
#include <QLocalSocket>
#include <QDataStream>
#include <QTimer>
#include <QProcess>
#include <time.h>
QTM_BEGIN_NAMESPACE
//IPC based on QLocalSocket
class LocalSocketEndPoint : public QServiceIpcEndPoint
{
Q_OBJECT
public:
LocalSocketEndPoint(QLocalSocket* s, QObject* parent = 0)
: QServiceIpcEndPoint(parent), socket(s)
{
Q_ASSERT(socket);
socket->setParent(this);
connect(s, SIGNAL(readyRead()), this, SLOT(readIncoming()));
connect(s, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
if (socket->bytesAvailable())
QTimer::singleShot(0, this, SLOT(readIncoming()));
}
~LocalSocketEndPoint()
{
}
protected:
void flushPackage(const QServicePackage& package)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_6);
out << package;
socket->write(block);
}
protected slots:
void readIncoming()
{
QDataStream in(socket);
in.setVersion(QDataStream::Qt_4_6);
while(socket->bytesAvailable()) {
QServicePackage package;
in >> package;
incoming.enqueue(package);
}
emit readyRead();
}
private:
QLocalSocket* socket;
};
QRemoteServiceControlPrivate::QRemoteServiceControlPrivate(QObject* parent)
: QObject(parent)
{
}
void QRemoteServiceControlPrivate::publishServices( const QString& ident)
{
createServiceEndPoint(ident) ;
}
void QRemoteServiceControlPrivate::processIncoming()
{
qDebug() << "Processing incoming connect";
if (localServer->hasPendingConnections()) {
QLocalSocket* s = localServer->nextPendingConnection();
//LocalSocketEndPoint owns socket
LocalSocketEndPoint* ipcEndPoint = new LocalSocketEndPoint(s);
ObjectEndPoint* endpoint = new ObjectEndPoint(ObjectEndPoint::Service, ipcEndPoint, this);
}
}
/*!
Creates endpoint on service side.
*/
bool QRemoteServiceControlPrivate::createServiceEndPoint(const QString& ident)
{
//other IPC mechanisms such as dbus may have to publish the
//meta object definition for all registered service types
QLocalServer::removeServer(ident);
qDebug() << "Start listening for incoming connections";
localServer = new QLocalServer(this);
if ( !localServer->listen(ident) ) {
qWarning() << "Cannot create local socket endpoint";
return false;
}
connect(localServer, SIGNAL(newConnection()), this, SLOT(processIncoming()));
if (localServer->hasPendingConnections())
QTimer::singleShot(0, this, SLOT(processIncoming()));
return true;
}
/*!
Creates endpoint on client side.
*/
QObject* QRemoteServiceControlPrivate::proxyForService(const QRemoteServiceIdentifier& typeIdent, const QString& location)
{
QLocalSocket* socket = new QLocalSocket();
//location format: protocol:address
QString address = location.section(':', 1, 1);
socket->connectToServer(address);
if (!socket->isValid()) {
qWarning() << "Cannot connect to remote service, trying to start service " << location;
// try starting the service by hand
QProcess *service = new QProcess();
service->start(address);
service->waitForStarted();
if(service->error() != QProcess::UnknownError || service->state() != QProcess::Running) {
qWarning() << "Unable to start service " << address << service->error() << service->errorString() << service->state();
return false;
}
int i;
socket->connectToServer(address);
for(i = 0; !socket->isValid() && i < 100; i++){
if(service->state() != QProcess::Running){
qWarning() << "Service died on startup" << service->errorString();
return false;
}
struct timespec tm;
tm.tv_sec = 0;
tm.tv_nsec = 1000000;
nanosleep(&tm, 0x0);
socket->connectToServer(address);
// keep trying for a while
}
qDebug() << "Number of loops: " << i;
if(!socket->isValid()){
qWarning() << "Server failed to start within waiting period";
return false;
}
}
LocalSocketEndPoint* ipcEndPoint = new LocalSocketEndPoint(socket);
ObjectEndPoint* endPoint = new ObjectEndPoint(ObjectEndPoint::Client, ipcEndPoint);
QObject *proxy = endPoint->constructProxy(typeIdent);
QObject::connect(proxy, SIGNAL(destroyed()), endPoint, SLOT(deleteLater()));
return proxy;
}
#include "moc_qremoteservicecontrol_p.cpp"
#include "qremoteservicecontrol_p.moc"
QTM_END_NAMESPACE
<commit_msg>Horrible hack for QLocalSocket startup on windows<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qremoteservicecontrol_p.h"
#include "ipcendpoint_p.h"
#include "objectendpoint_p.h"
#include <QLocalServer>
#include <QLocalSocket>
#include <QDataStream>
#include <QTimer>
#include <QProcess>
#include <time.h>
// Needed for ::Sleep, while we wait for a better solution
#ifdef Q_OS_WIN
#include <Windows.h>
#include <Winbase.h>
#endif
QTM_BEGIN_NAMESPACE
//IPC based on QLocalSocket
class LocalSocketEndPoint : public QServiceIpcEndPoint
{
Q_OBJECT
public:
LocalSocketEndPoint(QLocalSocket* s, QObject* parent = 0)
: QServiceIpcEndPoint(parent), socket(s)
{
Q_ASSERT(socket);
socket->setParent(this);
connect(s, SIGNAL(readyRead()), this, SLOT(readIncoming()));
connect(s, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
if (socket->bytesAvailable())
QTimer::singleShot(0, this, SLOT(readIncoming()));
}
~LocalSocketEndPoint()
{
}
protected:
void flushPackage(const QServicePackage& package)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_6);
out << package;
socket->write(block);
}
protected slots:
void readIncoming()
{
QDataStream in(socket);
in.setVersion(QDataStream::Qt_4_6);
while(socket->bytesAvailable()) {
QServicePackage package;
in >> package;
incoming.enqueue(package);
}
emit readyRead();
}
private:
QLocalSocket* socket;
};
QRemoteServiceControlPrivate::QRemoteServiceControlPrivate(QObject* parent)
: QObject(parent)
{
}
void QRemoteServiceControlPrivate::publishServices( const QString& ident)
{
createServiceEndPoint(ident) ;
}
void QRemoteServiceControlPrivate::processIncoming()
{
qDebug() << "Processing incoming connect";
if (localServer->hasPendingConnections()) {
QLocalSocket* s = localServer->nextPendingConnection();
//LocalSocketEndPoint owns socket
LocalSocketEndPoint* ipcEndPoint = new LocalSocketEndPoint(s);
ObjectEndPoint* endpoint = new ObjectEndPoint(ObjectEndPoint::Service, ipcEndPoint, this);
}
}
/*!
Creates endpoint on service side.
*/
bool QRemoteServiceControlPrivate::createServiceEndPoint(const QString& ident)
{
//other IPC mechanisms such as dbus may have to publish the
//meta object definition for all registered service types
QLocalServer::removeServer(ident);
qDebug() << "Start listening for incoming connections";
localServer = new QLocalServer(this);
if ( !localServer->listen(ident) ) {
qWarning() << "Cannot create local socket endpoint";
return false;
}
connect(localServer, SIGNAL(newConnection()), this, SLOT(processIncoming()));
if (localServer->hasPendingConnections())
QTimer::singleShot(0, this, SLOT(processIncoming()));
return true;
}
/*!
Creates endpoint on client side.
*/
QObject* QRemoteServiceControlPrivate::proxyForService(const QRemoteServiceIdentifier& typeIdent, const QString& location)
{
QLocalSocket* socket = new QLocalSocket();
//location format: protocol:address
QString address = location.section(':', 1, 1);
socket->connectToServer(address);
if (!socket->isValid()) {
qWarning() << "Cannot connect to remote service, trying to start service " << location;
// try starting the service by hand
QProcess *service = new QProcess();
service->start(address);
service->waitForStarted();
if(service->error() != QProcess::UnknownError || service->state() != QProcess::Running) {
qWarning() << "Unable to start service " << address << service->error() << service->errorString() << service->state();
return false;
}
int i;
socket->connectToServer(address);
for(i = 0; !socket->isValid() && i < 100; i++){
if(service->state() != QProcess::Running){
qWarning() << "Service died on startup" << service->errorString();
return false;
}
// Temporary hack till we can improve startup signaling
#ifdef Q_OS_WIN
::Sleep(10);
#else
struct timespec tm;
tm.tv_sec = 0;
tm.tv_nsec = 1000000;
nanosleep(&tm, 0x0);
#endif
socket->connectToServer(address);
// keep trying for a while
}
qDebug() << "Number of loops: " << i;
if(!socket->isValid()){
qWarning() << "Server failed to start within waiting period";
return false;
}
}
LocalSocketEndPoint* ipcEndPoint = new LocalSocketEndPoint(socket);
ObjectEndPoint* endPoint = new ObjectEndPoint(ObjectEndPoint::Client, ipcEndPoint);
QObject *proxy = endPoint->constructProxy(typeIdent);
QObject::connect(proxy, SIGNAL(destroyed()), endPoint, SLOT(deleteLater()));
return proxy;
}
#include "moc_qremoteservicecontrol_p.cpp"
#include "qremoteservicecontrol_p.moc"
QTM_END_NAMESPACE
<|endoftext|>
|
<commit_before>/**
* raftmath.tcc -
* @author: Jonathan Beard
* @version: Tue Apr 28 13:48:37 2015
*
* Copyright 2015 Jonathan Beard
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _RAFTMATH_TCC_
#define _RAFTMATH_TCC_ 1
namespace raft
{
/** START recursive templates for sum **/
template < class RETTYPE, class... PORTS > struct sum_helper{};
/** dummy template to end the recursion **/
template < class RETTYPE > struct sum_helper< RETTYPE >
{
constexpr static RETTYPE sum()
{
return( std::move< RETTYPE >( static_cast< RETTYPE >( 0 ) ) );
}
};
/** helper struct, for recursive template **/
template < class RETTYPE, class PORT, class... PORTS >
struct sum_helper< RETTYPE, PORT, PORTS... >
{
static RETTYPE sum( PORT &&port, PORTS&&... ports )
{
RETTYPE val;
port.pop( val );
return( std::move< RETTYPE >(
val + sum_helper< RETTYPE, PORTS... >::sum(
std::forward< PORTS >( ports )... ) ) );
}
};
/**
* sum - takes a set of ports in, pops the head off the FIFOs
* and adds them, moving the value to the return which is
* well the return.
*/
template < typename RETTYPE,
class... PORTS,
typename std::enable_if< std::is_arithmetic< RETTYPE >::value >::type* = nullptr
> static RETTYPE sum( PORTS&&... ports )
{
return( std::move< RETTYPE >( sum_helper< RETTYPE, PORTS... >::sum(
std::forward< PORTS >( ports )... ) ) );
};
/** START recursive templates for mult **/
template < class RETTYPE, class... PORTS > struct mult_helper{};
/** dummy template to end the recursion **/
template < class RETTYPE > struct mult_helper< RETTYPE >
{
constexpr static RETTYPE mult()
{
return( std::move< RETTYPE >( static_cast< RETTYPE >( 1 ) ) );
}
};
/** helper struct, for recursive template **/
template < class RETTYPE, class PORT, class... PORTS >
struct mult_helper< RETTYPE, PORT, PORTS... >
{
static RETTYPE mult( PORT &&port, PORTS&&... ports )
{
RETTYPE val;
port.pop( val );
return( std::move< RETTYPE >(
val * mult_helper< RETTYPE, PORTS... >::mult(
std::forward< PORTS >( ports )... ) ) );
}
};
/**
* mult - takes a set of ports in, pops the head off the FIFOs
* and adds them, moving the value to the return which is
* well the return.
*/
template < typename RETTYPE,
class... PORTS,
typename std::enable_if< std::is_arithmetic< RETTYPE >::value >::type* = nullptr
> static RETTYPE mult( PORTS&&... ports )
{
return( std::move< RETTYPE >( mult_helper< RETTYPE, PORTS... >::mult(
std::forward< PORTS >( ports )... ) ) );
};
} /** end namespace raft **/
#endif /* END _RAFTMATH_TCC_ */
<commit_msg>Remove more unnecessary semicolons<commit_after>/**
* raftmath.tcc -
* @author: Jonathan Beard
* @version: Tue Apr 28 13:48:37 2015
*
* Copyright 2015 Jonathan Beard
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _RAFTMATH_TCC_
#define _RAFTMATH_TCC_ 1
namespace raft
{
/** START recursive templates for sum **/
template < class RETTYPE, class... PORTS > struct sum_helper{};
/** dummy template to end the recursion **/
template < class RETTYPE > struct sum_helper< RETTYPE >
{
constexpr static RETTYPE sum()
{
return( std::move< RETTYPE >( static_cast< RETTYPE >( 0 ) ) );
}
};
/** helper struct, for recursive template **/
template < class RETTYPE, class PORT, class... PORTS >
struct sum_helper< RETTYPE, PORT, PORTS... >
{
static RETTYPE sum( PORT &&port, PORTS&&... ports )
{
RETTYPE val;
port.pop( val );
return( std::move< RETTYPE >(
val + sum_helper< RETTYPE, PORTS... >::sum(
std::forward< PORTS >( ports )... ) ) );
}
};
/**
* sum - takes a set of ports in, pops the head off the FIFOs
* and adds them, moving the value to the return which is
* well the return.
*/
template < typename RETTYPE,
class... PORTS,
typename std::enable_if< std::is_arithmetic< RETTYPE >::value >::type* = nullptr
> static RETTYPE sum( PORTS&&... ports )
{
return( std::move< RETTYPE >( sum_helper< RETTYPE, PORTS... >::sum(
std::forward< PORTS >( ports )... ) ) );
}
/** START recursive templates for mult **/
template < class RETTYPE, class... PORTS > struct mult_helper{};
/** dummy template to end the recursion **/
template < class RETTYPE > struct mult_helper< RETTYPE >
{
constexpr static RETTYPE mult()
{
return( std::move< RETTYPE >( static_cast< RETTYPE >( 1 ) ) );
}
};
/** helper struct, for recursive template **/
template < class RETTYPE, class PORT, class... PORTS >
struct mult_helper< RETTYPE, PORT, PORTS... >
{
static RETTYPE mult( PORT &&port, PORTS&&... ports )
{
RETTYPE val;
port.pop( val );
return( std::move< RETTYPE >(
val * mult_helper< RETTYPE, PORTS... >::mult(
std::forward< PORTS >( ports )... ) ) );
}
};
/**
* mult - takes a set of ports in, pops the head off the FIFOs
* and adds them, moving the value to the return which is
* well the return.
*/
template < typename RETTYPE,
class... PORTS,
typename std::enable_if< std::is_arithmetic< RETTYPE >::value >::type* = nullptr
> static RETTYPE mult( PORTS&&... ports )
{
return( std::move< RETTYPE >( mult_helper< RETTYPE, PORTS... >::mult(
std::forward< PORTS >( ports )... ) ) );
}
} /** end namespace raft **/
#endif /* END _RAFTMATH_TCC_ */
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/blob/blob_data.h"
#include "base/logging.h"
#include "base/time.h"
#include "third_party/WebKit/WebKit/chromium/public/WebBlobData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebCString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebData.h"
#include "webkit/glue/webkit_glue.h"
using WebKit::WebBlobData;
using WebKit::WebData;
using WebKit::WebString;
namespace {
// Time::FromDoubleT() does not return empty Time object when dt is 0.
// We have to work around this problem here.
base::Time DoubleTToTime(double dt) {
return dt ? base::Time::FromDoubleT(dt) : base::Time();
}
}
namespace webkit_blob {
BlobData::BlobData(const WebBlobData& data) {
size_t i = 0;
WebBlobData::Item item;
while (data.itemAt(i++, item)) {
switch (item.type) {
case WebBlobData::Item::TypeData:
if (!item.data.isEmpty()) {
// WebBlobData does not allow partial data.
DCHECK(!item.offset && item.length == -1);
AppendData(item.data);
}
break;
case WebBlobData::Item::TypeFile:
AppendFile(
webkit_glue::WebStringToFilePath(item.filePath),
static_cast<uint64>(item.offset),
static_cast<uint64>(item.length),
DoubleTToTime(item.expectedModificationTime));
break;
case WebBlobData::Item::TypeBlob:
if (item.length) {
AppendBlob(
item.blobURL,
static_cast<uint64>(item.offset),
static_cast<uint64>(item.length));
}
break;
default:
NOTREACHED();
}
}
content_type_= data.contentType().utf8().data();
content_disposition_ = data.contentDisposition().utf8().data();
}
} // namespace webkit_blob
<commit_msg>Remove the workaround that is not needed after the fix for Time::FromDoubleT is landed.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/blob/blob_data.h"
#include "base/logging.h"
#include "base/time.h"
#include "third_party/WebKit/WebKit/chromium/public/WebBlobData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebCString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebData.h"
#include "webkit/glue/webkit_glue.h"
using WebKit::WebBlobData;
using WebKit::WebData;
using WebKit::WebString;
namespace webkit_blob {
BlobData::BlobData(const WebBlobData& data) {
size_t i = 0;
WebBlobData::Item item;
while (data.itemAt(i++, item)) {
switch (item.type) {
case WebBlobData::Item::TypeData:
if (!item.data.isEmpty()) {
// WebBlobData does not allow partial data.
DCHECK(!item.offset && item.length == -1);
AppendData(item.data);
}
break;
case WebBlobData::Item::TypeFile:
AppendFile(
webkit_glue::WebStringToFilePath(item.filePath),
static_cast<uint64>(item.offset),
static_cast<uint64>(item.length),
base::Time::FromDoubleT(item.expectedModificationTime));
break;
case WebBlobData::Item::TypeBlob:
if (item.length) {
AppendBlob(
item.blobURL,
static_cast<uint64>(item.offset),
static_cast<uint64>(item.length));
}
break;
default:
NOTREACHED();
}
}
content_type_= data.contentType().utf8().data();
content_disposition_ = data.contentDisposition().utf8().data();
}
} // namespace webkit_blob
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SHARED_DATA_TYPE_HPP
#define SHARED_DATA_TYPE_HPP
#include "../../util/osrm_exception.hpp"
#include "../../util/simple_logger.hpp"
#include <cstdint>
#include <array>
namespace
{
// Added at the start and end of each block as sanity check
constexpr static const char CANARY[] = "OSRM";
}
struct SharedDataLayout
{
enum BlockID
{
NAME_OFFSETS = 0,
NAME_BLOCKS,
NAME_CHAR_LIST,
NAME_ID_LIST,
VIA_NODE_LIST,
GRAPH_NODE_LIST,
GRAPH_EDGE_LIST,
COORDINATE_LIST,
TURN_INSTRUCTION,
TRAVEL_MODE,
R_SEARCH_TREE,
GEOMETRIES_INDEX,
GEOMETRIES_LIST,
GEOMETRIES_INDICATORS,
HSGR_CHECKSUM,
TIMESTAMP,
FILE_INDEX_PATH,
NUM_BLOCKS
};
std::array<uint64_t, NUM_BLOCKS> num_entries;
std::array<uint64_t, NUM_BLOCKS> entry_size;
SharedDataLayout() : num_entries(), entry_size() {}
void PrintInformation() const
{
SimpleLogger().Write(logDEBUG) << "-";
SimpleLogger().Write(logDEBUG)
<< "name_offsets_size: " << num_entries[NAME_OFFSETS];
SimpleLogger().Write(logDEBUG)
<< "name_blocks_size: " << num_entries[NAME_BLOCKS];
SimpleLogger().Write(logDEBUG)
<< "name_char_list_size: " << num_entries[NAME_CHAR_LIST];
SimpleLogger().Write(logDEBUG)
<< "name_id_list_size: " << num_entries[NAME_ID_LIST];
SimpleLogger().Write(logDEBUG)
<< "via_node_list_size: " << num_entries[VIA_NODE_LIST];
SimpleLogger().Write(logDEBUG)
<< "graph_node_list_size: " << num_entries[GRAPH_NODE_LIST];
SimpleLogger().Write(logDEBUG)
<< "graph_edge_list_size: " << num_entries[GRAPH_EDGE_LIST];
SimpleLogger().Write(logDEBUG) << "timestamp_length: " << num_entries[TIMESTAMP];
SimpleLogger().Write(logDEBUG)
<< "coordinate_list_size: " << num_entries[COORDINATE_LIST];
SimpleLogger().Write(logDEBUG)
<< "turn_instruction_list_size: " << num_entries[TURN_INSTRUCTION];
SimpleLogger().Write(logDEBUG)
<< "travel_mode_list_size: " << num_entries[TRAVEL_MODE];
SimpleLogger().Write(logDEBUG)
<< "r_search_tree_size: " << num_entries[R_SEARCH_TREE];
SimpleLogger().Write(logDEBUG)
<< "geometries_indicators: " << num_entries[GEOMETRIES_INDICATORS] << "/"
<< ((num_entries[GEOMETRIES_INDICATORS] / 8) + 1);
SimpleLogger().Write(logDEBUG)
<< "geometries_index_list_size: " << num_entries[GEOMETRIES_INDEX];
SimpleLogger().Write(logDEBUG)
<< "geometries_list_size: " << num_entries[GEOMETRIES_LIST];
SimpleLogger().Write(logDEBUG)
<< "sizeof(checksum): " << entry_size[HSGR_CHECKSUM];
SimpleLogger().Write(logDEBUG) << "NAME_OFFSETS "
<< ": " << GetBlockSize(NAME_OFFSETS);
SimpleLogger().Write(logDEBUG) << "NAME_BLOCKS "
<< ": " << GetBlockSize(NAME_BLOCKS);
SimpleLogger().Write(logDEBUG) << "NAME_CHAR_LIST "
<< ": " << GetBlockSize(NAME_CHAR_LIST);
SimpleLogger().Write(logDEBUG) << "NAME_ID_LIST "
<< ": " << GetBlockSize(NAME_ID_LIST);
SimpleLogger().Write(logDEBUG) << "VIA_NODE_LIST "
<< ": " << GetBlockSize(VIA_NODE_LIST);
SimpleLogger().Write(logDEBUG) << "GRAPH_NODE_LIST "
<< ": " << GetBlockSize(GRAPH_NODE_LIST);
SimpleLogger().Write(logDEBUG) << "GRAPH_EDGE_LIST "
<< ": " << GetBlockSize(GRAPH_EDGE_LIST);
SimpleLogger().Write(logDEBUG) << "COORDINATE_LIST "
<< ": " << GetBlockSize(COORDINATE_LIST);
SimpleLogger().Write(logDEBUG) << "TURN_INSTRUCTION "
<< ": " << GetBlockSize(TURN_INSTRUCTION);
SimpleLogger().Write(logDEBUG) << "TRAVEL_MODE "
<< ": " << GetBlockSize(TRAVEL_MODE);
SimpleLogger().Write(logDEBUG) << "R_SEARCH_TREE "
<< ": " << GetBlockSize(R_SEARCH_TREE);
SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDEX "
<< ": " << GetBlockSize(GEOMETRIES_INDEX);
SimpleLogger().Write(logDEBUG) << "GEOMETRIES_LIST "
<< ": " << GetBlockSize(GEOMETRIES_LIST);
SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDICATORS"
<< ": " << GetBlockSize(GEOMETRIES_INDICATORS);
SimpleLogger().Write(logDEBUG) << "HSGR_CHECKSUM "
<< ": " << GetBlockSize(HSGR_CHECKSUM);
SimpleLogger().Write(logDEBUG) << "TIMESTAMP "
<< ": " << GetBlockSize(TIMESTAMP);
SimpleLogger().Write(logDEBUG) << "FILE_INDEX_PATH "
<< ": " << GetBlockSize(FILE_INDEX_PATH);
}
template <typename T> inline void SetBlockSize(BlockID bid, uint64_t entries)
{
num_entries[bid] = entries;
entry_size[bid] = sizeof(T);
}
inline uint64_t GetBlockSize(BlockID bid) const
{
// special encoding
if (bid == GEOMETRIES_INDICATORS)
{
return (num_entries[GEOMETRIES_INDICATORS] / 32 + 1) *
entry_size[GEOMETRIES_INDICATORS];
}
return num_entries[bid] * entry_size[bid];
}
inline uint64_t GetSizeOfLayout() const
{
return GetBlockOffset(NUM_BLOCKS) + NUM_BLOCKS * 2 * sizeof(CANARY);
}
inline uint64_t GetBlockOffset(BlockID bid) const
{
uint64_t result = sizeof(CANARY);
for (auto i = 0; i < bid; i++)
{
result += GetBlockSize((BlockID)i) + 2 * sizeof(CANARY);
}
return result;
}
template <typename T, bool WRITE_CANARY = false>
inline T *GetBlockPtr(char *shared_memory, BlockID bid)
{
T *ptr = (T *)(shared_memory + GetBlockOffset(bid));
if (WRITE_CANARY)
{
char *start_canary_ptr = shared_memory + GetBlockOffset(bid) - sizeof(CANARY);
char *end_canary_ptr = shared_memory + GetBlockOffset(bid) + GetBlockSize(bid);
std::copy(CANARY, CANARY + sizeof(CANARY), start_canary_ptr);
std::copy(CANARY, CANARY + sizeof(CANARY), end_canary_ptr);
}
else
{
char *start_canary_ptr = shared_memory + GetBlockOffset(bid) - sizeof(CANARY);
char *end_canary_ptr = shared_memory + GetBlockOffset(bid) + GetBlockSize(bid);
bool start_canary_alive = std::equal(CANARY, CANARY + sizeof(CANARY), start_canary_ptr);
bool end_canary_alive = std::equal(CANARY, CANARY + sizeof(CANARY), end_canary_ptr);
if (!start_canary_alive)
{
throw osrm::exception("Start canary of block corrupted.");
}
if (!end_canary_alive)
{
throw osrm::exception("End canary of block corrupted.");
}
}
return ptr;
}
};
enum SharedDataType
{
CURRENT_REGIONS,
LAYOUT_1,
DATA_1,
LAYOUT_2,
DATA_2,
LAYOUT_NONE,
DATA_NONE
};
struct SharedDataTimestamp
{
SharedDataType layout;
SharedDataType data;
unsigned timestamp;
};
#endif /* SHARED_DATA_TYPE_HPP */
<commit_msg>remove constexpr keyword that MSVC2013CTP isnt able to handle<commit_after>/*
Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SHARED_DATA_TYPE_HPP
#define SHARED_DATA_TYPE_HPP
#include "../../util/osrm_exception.hpp"
#include "../../util/simple_logger.hpp"
#include <cstdint>
#include <array>
namespace
{
// Added at the start and end of each block as sanity check
static const char CANARY[] = "OSRM";
}
struct SharedDataLayout
{
enum BlockID
{
NAME_OFFSETS = 0,
NAME_BLOCKS,
NAME_CHAR_LIST,
NAME_ID_LIST,
VIA_NODE_LIST,
GRAPH_NODE_LIST,
GRAPH_EDGE_LIST,
COORDINATE_LIST,
TURN_INSTRUCTION,
TRAVEL_MODE,
R_SEARCH_TREE,
GEOMETRIES_INDEX,
GEOMETRIES_LIST,
GEOMETRIES_INDICATORS,
HSGR_CHECKSUM,
TIMESTAMP,
FILE_INDEX_PATH,
NUM_BLOCKS
};
std::array<uint64_t, NUM_BLOCKS> num_entries;
std::array<uint64_t, NUM_BLOCKS> entry_size;
SharedDataLayout() : num_entries(), entry_size() {}
void PrintInformation() const
{
SimpleLogger().Write(logDEBUG) << "-";
SimpleLogger().Write(logDEBUG)
<< "name_offsets_size: " << num_entries[NAME_OFFSETS];
SimpleLogger().Write(logDEBUG)
<< "name_blocks_size: " << num_entries[NAME_BLOCKS];
SimpleLogger().Write(logDEBUG)
<< "name_char_list_size: " << num_entries[NAME_CHAR_LIST];
SimpleLogger().Write(logDEBUG)
<< "name_id_list_size: " << num_entries[NAME_ID_LIST];
SimpleLogger().Write(logDEBUG)
<< "via_node_list_size: " << num_entries[VIA_NODE_LIST];
SimpleLogger().Write(logDEBUG)
<< "graph_node_list_size: " << num_entries[GRAPH_NODE_LIST];
SimpleLogger().Write(logDEBUG)
<< "graph_edge_list_size: " << num_entries[GRAPH_EDGE_LIST];
SimpleLogger().Write(logDEBUG) << "timestamp_length: " << num_entries[TIMESTAMP];
SimpleLogger().Write(logDEBUG)
<< "coordinate_list_size: " << num_entries[COORDINATE_LIST];
SimpleLogger().Write(logDEBUG)
<< "turn_instruction_list_size: " << num_entries[TURN_INSTRUCTION];
SimpleLogger().Write(logDEBUG)
<< "travel_mode_list_size: " << num_entries[TRAVEL_MODE];
SimpleLogger().Write(logDEBUG)
<< "r_search_tree_size: " << num_entries[R_SEARCH_TREE];
SimpleLogger().Write(logDEBUG)
<< "geometries_indicators: " << num_entries[GEOMETRIES_INDICATORS] << "/"
<< ((num_entries[GEOMETRIES_INDICATORS] / 8) + 1);
SimpleLogger().Write(logDEBUG)
<< "geometries_index_list_size: " << num_entries[GEOMETRIES_INDEX];
SimpleLogger().Write(logDEBUG)
<< "geometries_list_size: " << num_entries[GEOMETRIES_LIST];
SimpleLogger().Write(logDEBUG)
<< "sizeof(checksum): " << entry_size[HSGR_CHECKSUM];
SimpleLogger().Write(logDEBUG) << "NAME_OFFSETS "
<< ": " << GetBlockSize(NAME_OFFSETS);
SimpleLogger().Write(logDEBUG) << "NAME_BLOCKS "
<< ": " << GetBlockSize(NAME_BLOCKS);
SimpleLogger().Write(logDEBUG) << "NAME_CHAR_LIST "
<< ": " << GetBlockSize(NAME_CHAR_LIST);
SimpleLogger().Write(logDEBUG) << "NAME_ID_LIST "
<< ": " << GetBlockSize(NAME_ID_LIST);
SimpleLogger().Write(logDEBUG) << "VIA_NODE_LIST "
<< ": " << GetBlockSize(VIA_NODE_LIST);
SimpleLogger().Write(logDEBUG) << "GRAPH_NODE_LIST "
<< ": " << GetBlockSize(GRAPH_NODE_LIST);
SimpleLogger().Write(logDEBUG) << "GRAPH_EDGE_LIST "
<< ": " << GetBlockSize(GRAPH_EDGE_LIST);
SimpleLogger().Write(logDEBUG) << "COORDINATE_LIST "
<< ": " << GetBlockSize(COORDINATE_LIST);
SimpleLogger().Write(logDEBUG) << "TURN_INSTRUCTION "
<< ": " << GetBlockSize(TURN_INSTRUCTION);
SimpleLogger().Write(logDEBUG) << "TRAVEL_MODE "
<< ": " << GetBlockSize(TRAVEL_MODE);
SimpleLogger().Write(logDEBUG) << "R_SEARCH_TREE "
<< ": " << GetBlockSize(R_SEARCH_TREE);
SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDEX "
<< ": " << GetBlockSize(GEOMETRIES_INDEX);
SimpleLogger().Write(logDEBUG) << "GEOMETRIES_LIST "
<< ": " << GetBlockSize(GEOMETRIES_LIST);
SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDICATORS"
<< ": " << GetBlockSize(GEOMETRIES_INDICATORS);
SimpleLogger().Write(logDEBUG) << "HSGR_CHECKSUM "
<< ": " << GetBlockSize(HSGR_CHECKSUM);
SimpleLogger().Write(logDEBUG) << "TIMESTAMP "
<< ": " << GetBlockSize(TIMESTAMP);
SimpleLogger().Write(logDEBUG) << "FILE_INDEX_PATH "
<< ": " << GetBlockSize(FILE_INDEX_PATH);
}
template <typename T> inline void SetBlockSize(BlockID bid, uint64_t entries)
{
num_entries[bid] = entries;
entry_size[bid] = sizeof(T);
}
inline uint64_t GetBlockSize(BlockID bid) const
{
// special encoding
if (bid == GEOMETRIES_INDICATORS)
{
return (num_entries[GEOMETRIES_INDICATORS] / 32 + 1) *
entry_size[GEOMETRIES_INDICATORS];
}
return num_entries[bid] * entry_size[bid];
}
inline uint64_t GetSizeOfLayout() const
{
return GetBlockOffset(NUM_BLOCKS) + NUM_BLOCKS * 2 * sizeof(CANARY);
}
inline uint64_t GetBlockOffset(BlockID bid) const
{
uint64_t result = sizeof(CANARY);
for (auto i = 0; i < bid; i++)
{
result += GetBlockSize((BlockID)i) + 2 * sizeof(CANARY);
}
return result;
}
template <typename T, bool WRITE_CANARY = false>
inline T *GetBlockPtr(char *shared_memory, BlockID bid)
{
T *ptr = (T *)(shared_memory + GetBlockOffset(bid));
if (WRITE_CANARY)
{
char *start_canary_ptr = shared_memory + GetBlockOffset(bid) - sizeof(CANARY);
char *end_canary_ptr = shared_memory + GetBlockOffset(bid) + GetBlockSize(bid);
std::copy(CANARY, CANARY + sizeof(CANARY), start_canary_ptr);
std::copy(CANARY, CANARY + sizeof(CANARY), end_canary_ptr);
}
else
{
char *start_canary_ptr = shared_memory + GetBlockOffset(bid) - sizeof(CANARY);
char *end_canary_ptr = shared_memory + GetBlockOffset(bid) + GetBlockSize(bid);
bool start_canary_alive = std::equal(CANARY, CANARY + sizeof(CANARY), start_canary_ptr);
bool end_canary_alive = std::equal(CANARY, CANARY + sizeof(CANARY), end_canary_ptr);
if (!start_canary_alive)
{
throw osrm::exception("Start canary of block corrupted.");
}
if (!end_canary_alive)
{
throw osrm::exception("End canary of block corrupted.");
}
}
return ptr;
}
};
enum SharedDataType
{
CURRENT_REGIONS,
LAYOUT_1,
DATA_1,
LAYOUT_2,
DATA_2,
LAYOUT_NONE,
DATA_NONE
};
struct SharedDataTimestamp
{
SharedDataType layout;
SharedDataType data;
unsigned timestamp;
};
#endif /* SHARED_DATA_TYPE_HPP */
<|endoftext|>
|
<commit_before>//===--- swift-reflection-dump.cpp - Reflection testing application -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This is a host-side tool to dump remote reflection sections in swift
// binaries.
//===----------------------------------------------------------------------===//
#include "swift/ABI/MetadataValues.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Reflection/ReflectionContext.h"
#include "swift/Reflection/TypeRef.h"
#include "swift/Reflection/TypeRefBuilder.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/ELF.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Support/CommandLine.h"
#if defined(_WIN32)
#include <io.h>
#else
#include <unistd.h>
#endif
#include <algorithm>
#include <csignal>
#include <iostream>
using llvm::ArrayRef;
using llvm::dyn_cast;
using llvm::StringRef;
using namespace llvm::object;
using namespace swift;
using namespace swift::reflection;
using namespace swift::remote;
using namespace Demangle;
enum class ActionType { DumpReflectionSections, DumpTypeLowering };
namespace options {
static llvm::cl::opt<ActionType> Action(
llvm::cl::desc("Mode:"),
llvm::cl::values(
clEnumValN(ActionType::DumpReflectionSections,
"dump-reflection-sections",
"Dump the field reflection section"),
clEnumValN(
ActionType::DumpTypeLowering, "dump-type-lowering",
"Dump the field layout for typeref strings read from stdin")),
llvm::cl::init(ActionType::DumpReflectionSections));
static llvm::cl::list<std::string>
BinaryFilename("binary-filename",
llvm::cl::desc("Filenames of the binary files"),
llvm::cl::OneOrMore);
static llvm::cl::opt<std::string>
Architecture("arch",
llvm::cl::desc("Architecture to inspect in the binary"),
llvm::cl::Required);
} // end namespace options
template <typename T> static T unwrap(llvm::Expected<T> value) {
if (value)
return std::move(value.get());
llvm::errs() << "swift-reflection-test error: " << toString(value.takeError())
<< "\n";
exit(EXIT_FAILURE);
}
static void reportError(std::error_code EC) {
assert(EC);
llvm::errs() << "swift-reflection-test error: " << EC.message() << ".\n";
exit(EXIT_FAILURE);
}
using NativeReflectionContext =
swift::reflection::ReflectionContext<External<RuntimeTarget<sizeof(uintptr_t)>>>;
using ReadBytesResult = swift::remote::MemoryReader::ReadBytesResult;
static uint64_t getSectionAddress(SectionRef S) {
// See COFFObjectFile.cpp for the implementation of
// COFFObjectFile::getSectionAddress. The image base address is added
// to all the addresses of the sections, thus the behavior is slightly different from
// the other platforms.
if (auto C = dyn_cast<COFFObjectFile>(S.getObject()))
return S.getAddress() - C->getImageBase();
return S.getAddress();
}
static bool needToRelocate(SectionRef S) {
if (!getSectionAddress(S))
return false;
if (auto EO = dyn_cast<ELFObjectFileBase>(S.getObject())) {
static const llvm::StringSet<> ELFSectionsList = {
".data", ".rodata", "swift5_protocols", "swift5_protocol_conformances",
"swift5_typeref", "swift5_reflstr", "swift5_assocty", "swift5_replace",
"swift5_type_metadata", "swift5_fieldmd", "swift5_capture", "swift5_builtin"
};
StringRef Name;
if (auto EC = S.getName(Name))
reportError(EC);
return ELFSectionsList.count(Name);
}
return true;
}
class Image {
std::vector<char> Memory;
public:
explicit Image(const ObjectFile *O) {
uint64_t VASize = O->getData().size();
for (SectionRef S : O->sections()) {
if (auto SectionAddr = getSectionAddress(S))
VASize = std::max(VASize, SectionAddr + S.getSize());
}
Memory.resize(VASize);
std::memcpy(&Memory[0], O->getData().data(), O->getData().size());
for (SectionRef S : O->sections()) {
if (!needToRelocate(S))
continue;
StringRef Content;
if (auto EC = S.getContents(Content))
reportError(EC);
std::memcpy(&Memory[getSectionAddress(S)], Content.data(),
Content.size());
}
}
RemoteAddress getStartAddress() const {
return RemoteAddress((uintptr_t)Memory.data());
}
bool isAddressValid(RemoteAddress Addr, uint64_t Size) const {
return (uintptr_t)Memory.data() <= Addr.getAddressData() &&
Addr.getAddressData() + Size <=
(uintptr_t)Memory.data() + Memory.size();
}
ReadBytesResult readBytes(RemoteAddress Addr, uint64_t Size) {
if (!isAddressValid(Addr, Size))
return ReadBytesResult(nullptr, [](const void *) {});
return ReadBytesResult((const void *)(Addr.getAddressData()),
[](const void *) {});
}
};
class ObjectMemoryReader : public MemoryReader {
std::vector<Image> Images;
public:
explicit ObjectMemoryReader(
const std::vector<const ObjectFile *> &ObjectFiles) {
for (const ObjectFile *O : ObjectFiles)
Images.emplace_back(O);
}
const std::vector<Image> &getImages() const { return Images; }
bool queryDataLayout(DataLayoutQueryType type, void *inBuffer,
void *outBuffer) override {
switch (type) {
case DLQ_GetPointerSize: {
auto result = static_cast<uint8_t *>(outBuffer);
*result = sizeof(void *);
return true;
}
case DLQ_GetSizeSize: {
auto result = static_cast<uint8_t *>(outBuffer);
*result = sizeof(size_t);
return true;
}
}
return false;
}
RemoteAddress getSymbolAddress(const std::string &name) override {
return RemoteAddress(nullptr);
}
ReadBytesResult readBytes(RemoteAddress Addr, uint64_t Size) override {
auto I = std::find_if(Images.begin(), Images.end(), [=](const Image &I) {
return I.isAddressValid(Addr, Size);
});
return I == Images.end() ? ReadBytesResult(nullptr, [](const void *) {})
: I->readBytes(Addr, Size);
}
bool readString(RemoteAddress Addr, std::string &Dest) override {
ReadBytesResult R = readBytes(Addr, 1);
if (!R)
return false;
StringRef Str((const char *)R.get());
Dest.append(Str.begin(), Str.end());
return true;
}
};
static int doDumpReflectionSections(ArrayRef<std::string> BinaryFilenames,
StringRef Arch, ActionType Action,
std::ostream &OS) {
// Note: binaryOrError and objectOrError own the memory for our ObjectFile;
// once they go out of scope, we can no longer do anything.
std::vector<OwningBinary<Binary>> BinaryOwners;
std::vector<std::unique_ptr<ObjectFile>> ObjectOwners;
std::vector<const ObjectFile *> ObjectFiles;
for (const std::string &BinaryFilename : BinaryFilenames) {
auto BinaryOwner = unwrap(createBinary(BinaryFilename));
Binary *BinaryFile = BinaryOwner.getBinary();
// The object file we are doing lookups in -- either the binary itself, or
// a particular slice of a universal binary.
std::unique_ptr<ObjectFile> ObjectOwner;
const ObjectFile *O = dyn_cast<ObjectFile>(BinaryFile);
if (!O) {
auto Universal = cast<MachOUniversalBinary>(BinaryFile);
ObjectOwner = unwrap(Universal->getObjectForArch(Arch));
O = ObjectOwner.get();
}
// Retain the objects that own section memory
BinaryOwners.push_back(std::move(BinaryOwner));
ObjectOwners.push_back(std::move(ObjectOwner));
ObjectFiles.push_back(O);
}
auto Reader = std::make_shared<ObjectMemoryReader>(ObjectFiles);
NativeReflectionContext Context(Reader);
for (const Image &I : Reader->getImages())
Context.addImage(I.getStartAddress());
switch (Action) {
case ActionType::DumpReflectionSections:
// Dump everything
Context.getBuilder().dumpAllSections(OS);
break;
case ActionType::DumpTypeLowering: {
for (std::string Line; std::getline(std::cin, Line);) {
if (Line.empty())
continue;
if (StringRef(Line).startswith("//"))
continue;
Demangle::Demangler Dem;
auto Demangled = Dem.demangleType(Line);
auto *TypeRef =
swift::Demangle::decodeMangledType(Context.getBuilder(), Demangled);
if (TypeRef == nullptr) {
OS << "Invalid typeref: " << Line << "\n";
continue;
}
TypeRef->dump(OS);
auto *TypeInfo =
Context.getBuilder().getTypeConverter().getTypeInfo(TypeRef);
if (TypeInfo == nullptr) {
OS << "Invalid lowering\n";
continue;
}
TypeInfo->dump(OS);
}
break;
}
}
return EXIT_SUCCESS;
}
int main(int argc, char *argv[]) {
PROGRAM_START(argc, argv);
llvm::cl::ParseCommandLineOptions(argc, argv, "Swift Reflection Dump\n");
return doDumpReflectionSections(options::BinaryFilename,
options::Architecture, options::Action,
std::cout);
}
<commit_msg>swift-reflection-dump: Virtualize logical-to-physical address mapping.<commit_after>//===--- swift-reflection-dump.cpp - Reflection testing application -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This is a host-side tool to dump remote reflection sections in swift
// binaries.
//===----------------------------------------------------------------------===//
#include "swift/ABI/MetadataValues.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Reflection/ReflectionContext.h"
#include "swift/Reflection/TypeRef.h"
#include "swift/Reflection/TypeRefBuilder.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/ELF.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Support/CommandLine.h"
#if defined(_WIN32)
#include <io.h>
#else
#include <unistd.h>
#endif
#include <algorithm>
#include <csignal>
#include <iostream>
using llvm::ArrayRef;
using llvm::dyn_cast;
using llvm::StringRef;
using namespace llvm::object;
using namespace swift;
using namespace swift::reflection;
using namespace swift::remote;
using namespace Demangle;
enum class ActionType { DumpReflectionSections, DumpTypeLowering };
namespace options {
static llvm::cl::opt<ActionType> Action(
llvm::cl::desc("Mode:"),
llvm::cl::values(
clEnumValN(ActionType::DumpReflectionSections,
"dump-reflection-sections",
"Dump the field reflection section"),
clEnumValN(
ActionType::DumpTypeLowering, "dump-type-lowering",
"Dump the field layout for typeref strings read from stdin")),
llvm::cl::init(ActionType::DumpReflectionSections));
static llvm::cl::list<std::string>
BinaryFilename("binary-filename",
llvm::cl::desc("Filenames of the binary files"),
llvm::cl::OneOrMore);
static llvm::cl::opt<std::string>
Architecture("arch",
llvm::cl::desc("Architecture to inspect in the binary"),
llvm::cl::Required);
} // end namespace options
template <typename T> static T unwrap(llvm::Expected<T> value) {
if (value)
return std::move(value.get());
llvm::errs() << "swift-reflection-test error: " << toString(value.takeError())
<< "\n";
exit(EXIT_FAILURE);
}
static void reportError(std::error_code EC) {
assert(EC);
llvm::errs() << "swift-reflection-test error: " << EC.message() << ".\n";
exit(EXIT_FAILURE);
}
using NativeReflectionContext =
swift::reflection::ReflectionContext<External<RuntimeTarget<sizeof(uintptr_t)>>>;
using ReadBytesResult = swift::remote::MemoryReader::ReadBytesResult;
static uint64_t getSectionAddress(SectionRef S) {
// See COFFObjectFile.cpp for the implementation of
// COFFObjectFile::getSectionAddress. The image base address is added
// to all the addresses of the sections, thus the behavior is slightly different from
// the other platforms.
if (auto C = dyn_cast<COFFObjectFile>(S.getObject()))
return S.getAddress() - C->getImageBase();
return S.getAddress();
}
static bool needToRelocate(SectionRef S) {
if (!getSectionAddress(S))
return false;
if (auto EO = dyn_cast<ELFObjectFileBase>(S.getObject())) {
static const llvm::StringSet<> ELFSectionsList = {
".data", ".rodata", "swift5_protocols", "swift5_protocol_conformances",
"swift5_typeref", "swift5_reflstr", "swift5_assocty", "swift5_replace",
"swift5_type_metadata", "swift5_fieldmd", "swift5_capture", "swift5_builtin"
};
StringRef Name;
if (auto EC = S.getName(Name))
reportError(EC);
return ELFSectionsList.count(Name);
}
return true;
}
class Image {
const ObjectFile *O;
uint64_t VASize;
struct RelocatedRegion {
uint64_t Start, Size;
const char *Base;
};
std::vector<RelocatedRegion> RelocatedRegions;
public:
explicit Image(const ObjectFile *O) : O(O), VASize(O->getData().size()) {
for (SectionRef S : O->sections()) {
if (!needToRelocate(S))
continue;
StringRef Content;
auto SectionAddr = getSectionAddress(S);
if (SectionAddr)
VASize = std::max(VASize, SectionAddr + S.getSize());
if (auto EC = S.getContents(Content))
reportError(EC);
auto PhysOffset = (uintptr_t)Content.data() - (uintptr_t)O->getData().data();
if (PhysOffset == SectionAddr) {
continue;
}
RelocatedRegions.push_back(RelocatedRegion{
SectionAddr,
Content.size(),
Content.data()});
}
}
RemoteAddress getStartAddress() const {
return RemoteAddress((uintptr_t)O->getData().data());
}
bool isAddressValid(RemoteAddress Addr, uint64_t Size) const {
auto start = getStartAddress().getAddressData();
return start <= Addr.getAddressData()
&& Addr.getAddressData() + Size <= start + VASize;
}
ReadBytesResult readBytes(RemoteAddress Addr, uint64_t Size) {
if (!isAddressValid(Addr, Size))
return ReadBytesResult(nullptr, [](const void *) {});
auto addrValue = Addr.getAddressData();
auto base = O->getData().data();
auto offset = addrValue - (uint64_t)base;
for (auto ®ion : RelocatedRegions) {
if (region.Start <= offset && offset < region.Start + region.Size) {
// Read shouldn't need to straddle section boundaries.
if (offset + Size > region.Start + region.Size)
return ReadBytesResult(nullptr, [](const void *) {});
offset -= region.Start;
base = region.Base;
break;
}
}
return ReadBytesResult(base + offset, [](const void *) {});
}
};
class ObjectMemoryReader : public MemoryReader {
std::vector<Image> Images;
public:
explicit ObjectMemoryReader(
const std::vector<const ObjectFile *> &ObjectFiles) {
for (const ObjectFile *O : ObjectFiles)
Images.emplace_back(O);
}
const std::vector<Image> &getImages() const { return Images; }
bool queryDataLayout(DataLayoutQueryType type, void *inBuffer,
void *outBuffer) override {
switch (type) {
case DLQ_GetPointerSize: {
auto result = static_cast<uint8_t *>(outBuffer);
*result = sizeof(void *);
return true;
}
case DLQ_GetSizeSize: {
auto result = static_cast<uint8_t *>(outBuffer);
*result = sizeof(size_t);
return true;
}
}
return false;
}
RemoteAddress getSymbolAddress(const std::string &name) override {
return RemoteAddress(nullptr);
}
ReadBytesResult readBytes(RemoteAddress Addr, uint64_t Size) override {
auto I = std::find_if(Images.begin(), Images.end(), [=](const Image &I) {
return I.isAddressValid(Addr, Size);
});
return I == Images.end() ? ReadBytesResult(nullptr, [](const void *) {})
: I->readBytes(Addr, Size);
}
bool readString(RemoteAddress Addr, std::string &Dest) override {
ReadBytesResult R = readBytes(Addr, 1);
if (!R)
return false;
StringRef Str((const char *)R.get());
Dest.append(Str.begin(), Str.end());
return true;
}
};
static int doDumpReflectionSections(ArrayRef<std::string> BinaryFilenames,
StringRef Arch, ActionType Action,
std::ostream &OS) {
// Note: binaryOrError and objectOrError own the memory for our ObjectFile;
// once they go out of scope, we can no longer do anything.
std::vector<OwningBinary<Binary>> BinaryOwners;
std::vector<std::unique_ptr<ObjectFile>> ObjectOwners;
std::vector<const ObjectFile *> ObjectFiles;
for (const std::string &BinaryFilename : BinaryFilenames) {
auto BinaryOwner = unwrap(createBinary(BinaryFilename));
Binary *BinaryFile = BinaryOwner.getBinary();
// The object file we are doing lookups in -- either the binary itself, or
// a particular slice of a universal binary.
std::unique_ptr<ObjectFile> ObjectOwner;
const ObjectFile *O = dyn_cast<ObjectFile>(BinaryFile);
if (!O) {
auto Universal = cast<MachOUniversalBinary>(BinaryFile);
ObjectOwner = unwrap(Universal->getObjectForArch(Arch));
O = ObjectOwner.get();
}
// Retain the objects that own section memory
BinaryOwners.push_back(std::move(BinaryOwner));
ObjectOwners.push_back(std::move(ObjectOwner));
ObjectFiles.push_back(O);
}
auto Reader = std::make_shared<ObjectMemoryReader>(ObjectFiles);
NativeReflectionContext Context(Reader);
for (const Image &I : Reader->getImages())
Context.addImage(I.getStartAddress());
switch (Action) {
case ActionType::DumpReflectionSections:
// Dump everything
Context.getBuilder().dumpAllSections(OS);
break;
case ActionType::DumpTypeLowering: {
for (std::string Line; std::getline(std::cin, Line);) {
if (Line.empty())
continue;
if (StringRef(Line).startswith("//"))
continue;
Demangle::Demangler Dem;
auto Demangled = Dem.demangleType(Line);
auto *TypeRef =
swift::Demangle::decodeMangledType(Context.getBuilder(), Demangled);
if (TypeRef == nullptr) {
OS << "Invalid typeref: " << Line << "\n";
continue;
}
TypeRef->dump(OS);
auto *TypeInfo =
Context.getBuilder().getTypeConverter().getTypeInfo(TypeRef);
if (TypeInfo == nullptr) {
OS << "Invalid lowering\n";
continue;
}
TypeInfo->dump(OS);
}
break;
}
}
return EXIT_SUCCESS;
}
int main(int argc, char *argv[]) {
PROGRAM_START(argc, argv);
llvm::cl::ParseCommandLineOptions(argc, argv, "Swift Reflection Dump\n");
return doDumpReflectionSections(options::BinaryFilename,
options::Architecture, options::Action,
std::cout);
}
<|endoftext|>
|
<commit_before>//===- InlineCoast.cpp - Cost analysis for inliner ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements inline cost analysis.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/InlineCost.h"
#include "llvm/Support/CallSite.h"
#include "llvm/CallingConv.h"
#include "llvm/IntrinsicInst.h"
using namespace llvm;
// CountCodeReductionForConstant - Figure out an approximation for how many
// instructions will be constant folded if the specified value is constant.
//
unsigned InlineCostAnalyzer::FunctionInfo::
CountCodeReductionForConstant(Value *V) {
unsigned Reduction = 0;
for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
if (isa<BranchInst>(*UI))
Reduction += 40; // Eliminating a conditional branch is a big win
else if (SwitchInst *SI = dyn_cast<SwitchInst>(*UI))
// Eliminating a switch is a big win, proportional to the number of edges
// deleted.
Reduction += (SI->getNumSuccessors()-1) * 40;
else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
// Turning an indirect call into a direct call is a BIG win
Reduction += CI->getCalledValue() == V ? 500 : 0;
} else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
// Turning an indirect call into a direct call is a BIG win
Reduction += II->getCalledValue() == V ? 500 : 0;
} else {
// Figure out if this instruction will be removed due to simple constant
// propagation.
Instruction &Inst = cast<Instruction>(**UI);
bool AllOperandsConstant = true;
for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i)
if (!isa<Constant>(Inst.getOperand(i)) && Inst.getOperand(i) != V) {
AllOperandsConstant = false;
break;
}
if (AllOperandsConstant) {
// We will get to remove this instruction...
Reduction += 7;
// And any other instructions that use it which become constants
// themselves.
Reduction += CountCodeReductionForConstant(&Inst);
}
}
return Reduction;
}
// CountCodeReductionForAlloca - Figure out an approximation of how much smaller
// the function will be if it is inlined into a context where an argument
// becomes an alloca.
//
unsigned InlineCostAnalyzer::FunctionInfo::
CountCodeReductionForAlloca(Value *V) {
if (!isa<PointerType>(V->getType())) return 0; // Not a pointer
unsigned Reduction = 0;
for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Instruction *I = cast<Instruction>(*UI);
if (isa<LoadInst>(I) || isa<StoreInst>(I))
Reduction += 10;
else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
// If the GEP has variable indices, we won't be able to do much with it.
for (Instruction::op_iterator I = GEP->op_begin()+1, E = GEP->op_end();
I != E; ++I)
if (!isa<Constant>(*I)) return 0;
Reduction += CountCodeReductionForAlloca(GEP)+15;
} else {
// If there is some other strange instruction, we're not going to be able
// to do much if we inline this.
return 0;
}
}
return Reduction;
}
/// analyzeFunction - Fill in the current structure with information gleaned
/// from the specified function.
void InlineCostAnalyzer::FunctionInfo::analyzeFunction(Function *F) {
unsigned NumInsts = 0, NumBlocks = 0;
// Look at the size of the callee. Each basic block counts as 20 units, and
// each instruction counts as 10.
for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
for (BasicBlock::const_iterator II = BB->begin(), E = BB->end();
II != E; ++II) {
if (isa<DbgInfoIntrinsic>(II)) continue; // Debug intrinsics don't count.
// Noop casts, including ptr <-> int, don't count.
if (const CastInst *CI = dyn_cast<CastInst>(II)) {
if (CI->isLosslessCast() || isa<IntToPtrInst>(CI) ||
isa<PtrToIntInst>(CI))
continue;
} else if (const GetElementPtrInst *GEPI =
dyn_cast<GetElementPtrInst>(II)) {
// If a GEP has all constant indices, it will probably be folded with
// a load/store.
bool AllConstant = true;
for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
if (!isa<ConstantInt>(GEPI->getOperand(i))) {
AllConstant = false;
break;
}
if (AllConstant) continue;
}
++NumInsts;
}
++NumBlocks;
}
this->NumBlocks = NumBlocks;
this->NumInsts = NumInsts;
// Check out all of the arguments to the function, figuring out how much
// code can be eliminated if one of the arguments is a constant.
for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
ArgumentWeights.push_back(ArgInfo(CountCodeReductionForConstant(I),
CountCodeReductionForAlloca(I)));
}
// getInlineCost - The heuristic used to determine if we should inline the
// function call or not.
//
int InlineCostAnalyzer::getInlineCost(CallSite CS, SmallPtrSet<const Function *, 16> &NeverInline) {
Instruction *TheCall = CS.getInstruction();
Function *Callee = CS.getCalledFunction();
const Function *Caller = TheCall->getParent()->getParent();
// Don't inline a directly recursive call.
if (Caller == Callee ||
// Don't inline functions which can be redefined at link-time to mean
// something else. link-once linkage is ok though.
Callee->hasWeakLinkage() ||
// Don't inline functions marked noinline.
NeverInline.count(Callee))
return 2000000000;
// InlineCost - This value measures how good of an inline candidate this call
// site is to inline. A lower inline cost make is more likely for the call to
// be inlined. This value may go negative.
//
int InlineCost = 0;
// If there is only one call of the function, and it has internal linkage,
// make it almost guaranteed to be inlined.
//
if (Callee->hasInternalLinkage() && Callee->hasOneUse())
InlineCost -= 30000;
// If this function uses the coldcc calling convention, prefer not to inline
// it.
if (Callee->getCallingConv() == CallingConv::Cold)
InlineCost += 2000;
// If the instruction after the call, or if the normal destination of the
// invoke is an unreachable instruction, the function is noreturn. As such,
// there is little point in inlining this.
if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
if (isa<UnreachableInst>(II->getNormalDest()->begin()))
InlineCost += 10000;
} else if (isa<UnreachableInst>(++BasicBlock::iterator(TheCall)))
InlineCost += 10000;
// Get information about the callee...
FunctionInfo &CalleeFI = CachedFunctionInfo[Callee];
// If we haven't calculated this information yet, do so now.
if (CalleeFI.NumBlocks == 0)
CalleeFI.analyzeFunction(Callee);
// Add to the inline quality for properties that make the call valuable to
// inline. This includes factors that indicate that the result of inlining
// the function will be optimizable. Currently this just looks at arguments
// passed into the function.
//
unsigned ArgNo = 0;
for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
I != E; ++I, ++ArgNo) {
// Each argument passed in has a cost at both the caller and the callee
// sides. This favors functions that take many arguments over functions
// that take few arguments.
InlineCost -= 20;
// If this is a function being passed in, it is very likely that we will be
// able to turn an indirect function call into a direct function call.
if (isa<Function>(I))
InlineCost -= 100;
// If an alloca is passed in, inlining this function is likely to allow
// significant future optimization possibilities (like scalar promotion, and
// scalarization), so encourage the inlining of the function.
//
else if (isa<AllocaInst>(I)) {
if (ArgNo < CalleeFI.ArgumentWeights.size())
InlineCost -= CalleeFI.ArgumentWeights[ArgNo].AllocaWeight;
// If this is a constant being passed into the function, use the argument
// weights calculated for the callee to determine how much will be folded
// away with this information.
} else if (isa<Constant>(I)) {
if (ArgNo < CalleeFI.ArgumentWeights.size())
InlineCost -= CalleeFI.ArgumentWeights[ArgNo].ConstantWeight;
}
}
// Now that we have considered all of the factors that make the call site more
// likely to be inlined, look at factors that make us not want to inline it.
// Don't inline into something too big, which would make it bigger. Here, we
// count each basic block as a single unit.
//
InlineCost += Caller->size()/20;
// Look at the size of the callee. Each basic block counts as 20 units, and
// each instruction counts as 5.
InlineCost += CalleeFI.NumInsts*5 + CalleeFI.NumBlocks*20;
return InlineCost;
}
<commit_msg>Fix comment.<commit_after>//===- InlineCoast.cpp - Cost analysis for inliner ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements inline cost analysis.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/InlineCost.h"
#include "llvm/Support/CallSite.h"
#include "llvm/CallingConv.h"
#include "llvm/IntrinsicInst.h"
using namespace llvm;
// CountCodeReductionForConstant - Figure out an approximation for how many
// instructions will be constant folded if the specified value is constant.
//
unsigned InlineCostAnalyzer::FunctionInfo::
CountCodeReductionForConstant(Value *V) {
unsigned Reduction = 0;
for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
if (isa<BranchInst>(*UI))
Reduction += 40; // Eliminating a conditional branch is a big win
else if (SwitchInst *SI = dyn_cast<SwitchInst>(*UI))
// Eliminating a switch is a big win, proportional to the number of edges
// deleted.
Reduction += (SI->getNumSuccessors()-1) * 40;
else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
// Turning an indirect call into a direct call is a BIG win
Reduction += CI->getCalledValue() == V ? 500 : 0;
} else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
// Turning an indirect call into a direct call is a BIG win
Reduction += II->getCalledValue() == V ? 500 : 0;
} else {
// Figure out if this instruction will be removed due to simple constant
// propagation.
Instruction &Inst = cast<Instruction>(**UI);
bool AllOperandsConstant = true;
for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i)
if (!isa<Constant>(Inst.getOperand(i)) && Inst.getOperand(i) != V) {
AllOperandsConstant = false;
break;
}
if (AllOperandsConstant) {
// We will get to remove this instruction...
Reduction += 7;
// And any other instructions that use it which become constants
// themselves.
Reduction += CountCodeReductionForConstant(&Inst);
}
}
return Reduction;
}
// CountCodeReductionForAlloca - Figure out an approximation of how much smaller
// the function will be if it is inlined into a context where an argument
// becomes an alloca.
//
unsigned InlineCostAnalyzer::FunctionInfo::
CountCodeReductionForAlloca(Value *V) {
if (!isa<PointerType>(V->getType())) return 0; // Not a pointer
unsigned Reduction = 0;
for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Instruction *I = cast<Instruction>(*UI);
if (isa<LoadInst>(I) || isa<StoreInst>(I))
Reduction += 10;
else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
// If the GEP has variable indices, we won't be able to do much with it.
for (Instruction::op_iterator I = GEP->op_begin()+1, E = GEP->op_end();
I != E; ++I)
if (!isa<Constant>(*I)) return 0;
Reduction += CountCodeReductionForAlloca(GEP)+15;
} else {
// If there is some other strange instruction, we're not going to be able
// to do much if we inline this.
return 0;
}
}
return Reduction;
}
/// analyzeFunction - Fill in the current structure with information gleaned
/// from the specified function.
void InlineCostAnalyzer::FunctionInfo::analyzeFunction(Function *F) {
unsigned NumInsts = 0, NumBlocks = 0;
// Look at the size of the callee. Each basic block counts as 20 units, and
// each instruction counts as 5.
for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
for (BasicBlock::const_iterator II = BB->begin(), E = BB->end();
II != E; ++II) {
if (isa<DbgInfoIntrinsic>(II)) continue; // Debug intrinsics don't count.
// Noop casts, including ptr <-> int, don't count.
if (const CastInst *CI = dyn_cast<CastInst>(II)) {
if (CI->isLosslessCast() || isa<IntToPtrInst>(CI) ||
isa<PtrToIntInst>(CI))
continue;
} else if (const GetElementPtrInst *GEPI =
dyn_cast<GetElementPtrInst>(II)) {
// If a GEP has all constant indices, it will probably be folded with
// a load/store.
bool AllConstant = true;
for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
if (!isa<ConstantInt>(GEPI->getOperand(i))) {
AllConstant = false;
break;
}
if (AllConstant) continue;
}
++NumInsts;
}
++NumBlocks;
}
this->NumBlocks = NumBlocks;
this->NumInsts = NumInsts;
// Check out all of the arguments to the function, figuring out how much
// code can be eliminated if one of the arguments is a constant.
for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
ArgumentWeights.push_back(ArgInfo(CountCodeReductionForConstant(I),
CountCodeReductionForAlloca(I)));
}
// getInlineCost - The heuristic used to determine if we should inline the
// function call or not.
//
int InlineCostAnalyzer::getInlineCost(CallSite CS, SmallPtrSet<const Function *, 16> &NeverInline) {
Instruction *TheCall = CS.getInstruction();
Function *Callee = CS.getCalledFunction();
const Function *Caller = TheCall->getParent()->getParent();
// Don't inline a directly recursive call.
if (Caller == Callee ||
// Don't inline functions which can be redefined at link-time to mean
// something else. link-once linkage is ok though.
Callee->hasWeakLinkage() ||
// Don't inline functions marked noinline.
NeverInline.count(Callee))
return 2000000000;
// InlineCost - This value measures how good of an inline candidate this call
// site is to inline. A lower inline cost make is more likely for the call to
// be inlined. This value may go negative.
//
int InlineCost = 0;
// If there is only one call of the function, and it has internal linkage,
// make it almost guaranteed to be inlined.
//
if (Callee->hasInternalLinkage() && Callee->hasOneUse())
InlineCost -= 30000;
// If this function uses the coldcc calling convention, prefer not to inline
// it.
if (Callee->getCallingConv() == CallingConv::Cold)
InlineCost += 2000;
// If the instruction after the call, or if the normal destination of the
// invoke is an unreachable instruction, the function is noreturn. As such,
// there is little point in inlining this.
if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
if (isa<UnreachableInst>(II->getNormalDest()->begin()))
InlineCost += 10000;
} else if (isa<UnreachableInst>(++BasicBlock::iterator(TheCall)))
InlineCost += 10000;
// Get information about the callee...
FunctionInfo &CalleeFI = CachedFunctionInfo[Callee];
// If we haven't calculated this information yet, do so now.
if (CalleeFI.NumBlocks == 0)
CalleeFI.analyzeFunction(Callee);
// Add to the inline quality for properties that make the call valuable to
// inline. This includes factors that indicate that the result of inlining
// the function will be optimizable. Currently this just looks at arguments
// passed into the function.
//
unsigned ArgNo = 0;
for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
I != E; ++I, ++ArgNo) {
// Each argument passed in has a cost at both the caller and the callee
// sides. This favors functions that take many arguments over functions
// that take few arguments.
InlineCost -= 20;
// If this is a function being passed in, it is very likely that we will be
// able to turn an indirect function call into a direct function call.
if (isa<Function>(I))
InlineCost -= 100;
// If an alloca is passed in, inlining this function is likely to allow
// significant future optimization possibilities (like scalar promotion, and
// scalarization), so encourage the inlining of the function.
//
else if (isa<AllocaInst>(I)) {
if (ArgNo < CalleeFI.ArgumentWeights.size())
InlineCost -= CalleeFI.ArgumentWeights[ArgNo].AllocaWeight;
// If this is a constant being passed into the function, use the argument
// weights calculated for the callee to determine how much will be folded
// away with this information.
} else if (isa<Constant>(I)) {
if (ArgNo < CalleeFI.ArgumentWeights.size())
InlineCost -= CalleeFI.ArgumentWeights[ArgNo].ConstantWeight;
}
}
// Now that we have considered all of the factors that make the call site more
// likely to be inlined, look at factors that make us not want to inline it.
// Don't inline into something too big, which would make it bigger. Here, we
// count each basic block as a single unit.
//
InlineCost += Caller->size()/20;
// Look at the size of the callee. Each basic block counts as 20 units, and
// each instruction counts as 5.
InlineCost += CalleeFI.NumInsts*5 + CalleeFI.NumBlocks*20;
return InlineCost;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrBatchFontCache.h"
#include "GrFontAtlasSizes.h"
#include "GrGpu.h"
#include "GrRectanizer.h"
#include "GrSurfacePriv.h"
#include "SkString.h"
#include "SkDistanceFieldGen.h"
///////////////////////////////////////////////////////////////////////////////
static GrBatchAtlas* make_atlas(GrContext* context, GrPixelConfig config,
int textureWidth, int textureHeight,
int numPlotsX, int numPlotsY) {
GrSurfaceDesc desc;
desc.fFlags = kNone_GrSurfaceFlags;
desc.fWidth = textureWidth;
desc.fHeight = textureHeight;
desc.fConfig = config;
// We don't want to flush the context so we claim we're in the middle of flushing so as to
// guarantee we do not recieve a texture with pending IO
GrTexture* texture = context->textureProvider()->refScratchTexture(
desc, GrTextureProvider::kApprox_ScratchTexMatch, true);
if (!texture) {
return NULL;
}
return SkNEW_ARGS(GrBatchAtlas, (texture, numPlotsX, numPlotsY));
}
bool GrBatchFontCache::initAtlas(GrMaskFormat format) {
int index = MaskFormatToAtlasIndex(format);
if (!fAtlases[index]) {
GrPixelConfig config = this->getPixelConfig(format);
if (kA8_GrMaskFormat == format) {
fAtlases[index] = make_atlas(fContext, config,
GR_FONT_ATLAS_A8_TEXTURE_WIDTH,
GR_FONT_ATLAS_TEXTURE_HEIGHT,
GR_FONT_ATLAS_A8_NUM_PLOTS_X,
GR_FONT_ATLAS_NUM_PLOTS_Y);
} else {
fAtlases[index] = make_atlas(fContext, config,
GR_FONT_ATLAS_TEXTURE_WIDTH,
GR_FONT_ATLAS_TEXTURE_HEIGHT,
GR_FONT_ATLAS_NUM_PLOTS_X,
GR_FONT_ATLAS_NUM_PLOTS_Y);
}
// Atlas creation can fail
if (fAtlases[index]) {
fAtlases[index]->registerEvictionCallback(&GrBatchFontCache::HandleEviction,
(void*)this);
} else {
return false;
}
}
return true;
}
GrBatchFontCache::GrBatchFontCache(GrContext* context)
: fContext(context)
, fPreserveStrike(NULL) {
for (int i = 0; i < kMaskFormatCount; ++i) {
fAtlases[i] = NULL;
}
}
GrBatchFontCache::~GrBatchFontCache() {
SkTDynamicHash<GrBatchTextStrike, GrFontDescKey>::Iter iter(&fCache);
while (!iter.done()) {
(*iter).unref();
++iter;
}
for (int i = 0; i < kMaskFormatCount; ++i) {
SkDELETE(fAtlases[i]);
}
}
void GrBatchFontCache::freeAll() {
SkTDynamicHash<GrBatchTextStrike, GrFontDescKey>::Iter iter(&fCache);
while (!iter.done()) {
(*iter).unref();
++iter;
}
fCache.rewind();
for (int i = 0; i < kMaskFormatCount; ++i) {
SkDELETE(fAtlases[i]);
fAtlases[i] = NULL;
}
}
GrPixelConfig GrBatchFontCache::getPixelConfig(GrMaskFormat format) const {
static const GrPixelConfig kPixelConfigs[] = {
kAlpha_8_GrPixelConfig,
kRGB_565_GrPixelConfig,
kSkia8888_GrPixelConfig
};
SK_COMPILE_ASSERT(SK_ARRAY_COUNT(kPixelConfigs) == kMaskFormatCount, array_size_mismatch);
return kPixelConfigs[format];
}
void GrBatchFontCache::HandleEviction(GrBatchAtlas::AtlasID id, void* ptr) {
GrBatchFontCache* fontCache = reinterpret_cast<GrBatchFontCache*>(ptr);
SkTDynamicHash<GrBatchTextStrike, GrFontDescKey>::Iter iter(&fontCache->fCache);
for (; !iter.done(); ++iter) {
GrBatchTextStrike* strike = &*iter;
strike->removeID(id);
// clear out any empty strikes. We will preserve the strike whose call to addToAtlas
// triggered the eviction
if (strike != fontCache->fPreserveStrike && 0 == strike->fAtlasedGlyphs) {
fontCache->fCache.remove(*(strike->fFontScalerKey));
strike->fIsAbandoned = true;
strike->unref();
}
}
}
void GrBatchFontCache::dump() const {
static int gDumpCount = 0;
for (int i = 0; i < kMaskFormatCount; ++i) {
if (fAtlases[i]) {
GrTexture* texture = fAtlases[i]->getTexture();
if (texture) {
SkString filename;
#ifdef SK_BUILD_FOR_ANDROID
filename.printf("/sdcard/fontcache_%d%d.png", gDumpCount, i);
#else
filename.printf("fontcache_%d%d.png", gDumpCount, i);
#endif
texture->surfacePriv().savePixels(filename.c_str());
}
}
}
++gDumpCount;
}
///////////////////////////////////////////////////////////////////////////////
/*
The text strike is specific to a given font/style/matrix setup, which is
represented by the GrHostFontScaler object we are given in getGlyph().
We map a 32bit glyphID to a GrGlyph record, which in turn points to a
atlas and a position within that texture.
*/
GrBatchTextStrike::GrBatchTextStrike(GrBatchFontCache* cache, const GrFontDescKey* key)
: fFontScalerKey(SkRef(key))
, fPool(9/*start allocations at 512 bytes*/)
, fAtlasedGlyphs(0)
, fIsAbandoned(false) {
fBatchFontCache = cache; // no need to ref, it won't go away before we do
}
GrBatchTextStrike::~GrBatchTextStrike() {
SkTDynamicHash<GrGlyph, GrGlyph::PackedID>::Iter iter(&fCache);
while (!iter.done()) {
(*iter).free();
++iter;
}
}
GrGlyph* GrBatchTextStrike::generateGlyph(GrGlyph::PackedID packed,
GrFontScaler* scaler) {
SkIRect bounds;
if (GrGlyph::kDistance_MaskStyle == GrGlyph::UnpackMaskStyle(packed)) {
if (!scaler->getPackedGlyphDFBounds(packed, &bounds)) {
return NULL;
}
} else {
if (!scaler->getPackedGlyphBounds(packed, &bounds)) {
return NULL;
}
}
GrMaskFormat format = scaler->getPackedGlyphMaskFormat(packed);
GrGlyph* glyph = (GrGlyph*)fPool.alloc(sizeof(GrGlyph), SK_MALLOC_THROW);
glyph->init(packed, bounds, format);
fCache.add(glyph);
return glyph;
}
void GrBatchTextStrike::removeID(GrBatchAtlas::AtlasID id) {
SkTDynamicHash<GrGlyph, GrGlyph::PackedID>::Iter iter(&fCache);
while (!iter.done()) {
if (id == (*iter).fID) {
(*iter).fID = GrBatchAtlas::kInvalidAtlasID;
fAtlasedGlyphs--;
SkASSERT(fAtlasedGlyphs >= 0);
}
++iter;
}
}
bool GrBatchTextStrike::addGlyphToAtlas(GrBatchTarget* batchTarget, GrGlyph* glyph,
GrFontScaler* scaler) {
SkASSERT(glyph);
SkASSERT(scaler);
SkASSERT(fCache.find(glyph->fPackedID));
SkASSERT(NULL == glyph->fPlot);
SkAutoUnref ar(SkSafeRef(scaler));
int bytesPerPixel = GrMaskFormatBytesPerPixel(glyph->fMaskFormat);
size_t size = glyph->fBounds.area() * bytesPerPixel;
GrAutoMalloc<1024> storage(size);
if (GrGlyph::kDistance_MaskStyle == GrGlyph::UnpackMaskStyle(glyph->fPackedID)) {
if (!scaler->getPackedGlyphDFImage(glyph->fPackedID, glyph->width(),
glyph->height(),
storage.get())) {
return false;
}
} else {
if (!scaler->getPackedGlyphImage(glyph->fPackedID, glyph->width(),
glyph->height(),
glyph->width() * bytesPerPixel,
storage.get())) {
return false;
}
}
bool success = fBatchFontCache->addToAtlas(this, &glyph->fID, batchTarget, glyph->fMaskFormat,
glyph->width(), glyph->height(),
storage.get(), &glyph->fAtlasLocation);
if (success) {
fAtlasedGlyphs++;
}
return success;
}
<commit_msg>fix for atlas is abandoned text corruption<commit_after>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrBatchFontCache.h"
#include "GrFontAtlasSizes.h"
#include "GrGpu.h"
#include "GrRectanizer.h"
#include "GrSurfacePriv.h"
#include "SkString.h"
#include "SkDistanceFieldGen.h"
///////////////////////////////////////////////////////////////////////////////
static GrBatchAtlas* make_atlas(GrContext* context, GrPixelConfig config,
int textureWidth, int textureHeight,
int numPlotsX, int numPlotsY) {
GrSurfaceDesc desc;
desc.fFlags = kNone_GrSurfaceFlags;
desc.fWidth = textureWidth;
desc.fHeight = textureHeight;
desc.fConfig = config;
// We don't want to flush the context so we claim we're in the middle of flushing so as to
// guarantee we do not recieve a texture with pending IO
GrTexture* texture = context->textureProvider()->refScratchTexture(
desc, GrTextureProvider::kApprox_ScratchTexMatch, true);
if (!texture) {
return NULL;
}
return SkNEW_ARGS(GrBatchAtlas, (texture, numPlotsX, numPlotsY));
}
bool GrBatchFontCache::initAtlas(GrMaskFormat format) {
int index = MaskFormatToAtlasIndex(format);
if (!fAtlases[index]) {
GrPixelConfig config = this->getPixelConfig(format);
if (kA8_GrMaskFormat == format) {
fAtlases[index] = make_atlas(fContext, config,
GR_FONT_ATLAS_A8_TEXTURE_WIDTH,
GR_FONT_ATLAS_TEXTURE_HEIGHT,
GR_FONT_ATLAS_A8_NUM_PLOTS_X,
GR_FONT_ATLAS_NUM_PLOTS_Y);
} else {
fAtlases[index] = make_atlas(fContext, config,
GR_FONT_ATLAS_TEXTURE_WIDTH,
GR_FONT_ATLAS_TEXTURE_HEIGHT,
GR_FONT_ATLAS_NUM_PLOTS_X,
GR_FONT_ATLAS_NUM_PLOTS_Y);
}
// Atlas creation can fail
if (fAtlases[index]) {
fAtlases[index]->registerEvictionCallback(&GrBatchFontCache::HandleEviction,
(void*)this);
} else {
return false;
}
}
return true;
}
GrBatchFontCache::GrBatchFontCache(GrContext* context)
: fContext(context)
, fPreserveStrike(NULL) {
for (int i = 0; i < kMaskFormatCount; ++i) {
fAtlases[i] = NULL;
}
}
GrBatchFontCache::~GrBatchFontCache() {
SkTDynamicHash<GrBatchTextStrike, GrFontDescKey>::Iter iter(&fCache);
while (!iter.done()) {
(*iter).fIsAbandoned = true;
(*iter).unref();
++iter;
}
for (int i = 0; i < kMaskFormatCount; ++i) {
SkDELETE(fAtlases[i]);
}
}
void GrBatchFontCache::freeAll() {
SkTDynamicHash<GrBatchTextStrike, GrFontDescKey>::Iter iter(&fCache);
while (!iter.done()) {
(*iter).fIsAbandoned = true;
(*iter).unref();
++iter;
}
fCache.rewind();
for (int i = 0; i < kMaskFormatCount; ++i) {
SkDELETE(fAtlases[i]);
fAtlases[i] = NULL;
}
}
GrPixelConfig GrBatchFontCache::getPixelConfig(GrMaskFormat format) const {
static const GrPixelConfig kPixelConfigs[] = {
kAlpha_8_GrPixelConfig,
kRGB_565_GrPixelConfig,
kSkia8888_GrPixelConfig
};
SK_COMPILE_ASSERT(SK_ARRAY_COUNT(kPixelConfigs) == kMaskFormatCount, array_size_mismatch);
return kPixelConfigs[format];
}
void GrBatchFontCache::HandleEviction(GrBatchAtlas::AtlasID id, void* ptr) {
GrBatchFontCache* fontCache = reinterpret_cast<GrBatchFontCache*>(ptr);
SkTDynamicHash<GrBatchTextStrike, GrFontDescKey>::Iter iter(&fontCache->fCache);
for (; !iter.done(); ++iter) {
GrBatchTextStrike* strike = &*iter;
strike->removeID(id);
// clear out any empty strikes. We will preserve the strike whose call to addToAtlas
// triggered the eviction
if (strike != fontCache->fPreserveStrike && 0 == strike->fAtlasedGlyphs) {
fontCache->fCache.remove(*(strike->fFontScalerKey));
strike->fIsAbandoned = true;
strike->unref();
}
}
}
void GrBatchFontCache::dump() const {
static int gDumpCount = 0;
for (int i = 0; i < kMaskFormatCount; ++i) {
if (fAtlases[i]) {
GrTexture* texture = fAtlases[i]->getTexture();
if (texture) {
SkString filename;
#ifdef SK_BUILD_FOR_ANDROID
filename.printf("/sdcard/fontcache_%d%d.png", gDumpCount, i);
#else
filename.printf("fontcache_%d%d.png", gDumpCount, i);
#endif
texture->surfacePriv().savePixels(filename.c_str());
}
}
}
++gDumpCount;
}
///////////////////////////////////////////////////////////////////////////////
/*
The text strike is specific to a given font/style/matrix setup, which is
represented by the GrHostFontScaler object we are given in getGlyph().
We map a 32bit glyphID to a GrGlyph record, which in turn points to a
atlas and a position within that texture.
*/
GrBatchTextStrike::GrBatchTextStrike(GrBatchFontCache* cache, const GrFontDescKey* key)
: fFontScalerKey(SkRef(key))
, fPool(9/*start allocations at 512 bytes*/)
, fAtlasedGlyphs(0)
, fIsAbandoned(false) {
fBatchFontCache = cache; // no need to ref, it won't go away before we do
}
GrBatchTextStrike::~GrBatchTextStrike() {
SkTDynamicHash<GrGlyph, GrGlyph::PackedID>::Iter iter(&fCache);
while (!iter.done()) {
(*iter).free();
++iter;
}
}
GrGlyph* GrBatchTextStrike::generateGlyph(GrGlyph::PackedID packed,
GrFontScaler* scaler) {
SkIRect bounds;
if (GrGlyph::kDistance_MaskStyle == GrGlyph::UnpackMaskStyle(packed)) {
if (!scaler->getPackedGlyphDFBounds(packed, &bounds)) {
return NULL;
}
} else {
if (!scaler->getPackedGlyphBounds(packed, &bounds)) {
return NULL;
}
}
GrMaskFormat format = scaler->getPackedGlyphMaskFormat(packed);
GrGlyph* glyph = (GrGlyph*)fPool.alloc(sizeof(GrGlyph), SK_MALLOC_THROW);
glyph->init(packed, bounds, format);
fCache.add(glyph);
return glyph;
}
void GrBatchTextStrike::removeID(GrBatchAtlas::AtlasID id) {
SkTDynamicHash<GrGlyph, GrGlyph::PackedID>::Iter iter(&fCache);
while (!iter.done()) {
if (id == (*iter).fID) {
(*iter).fID = GrBatchAtlas::kInvalidAtlasID;
fAtlasedGlyphs--;
SkASSERT(fAtlasedGlyphs >= 0);
}
++iter;
}
}
bool GrBatchTextStrike::addGlyphToAtlas(GrBatchTarget* batchTarget, GrGlyph* glyph,
GrFontScaler* scaler) {
SkASSERT(glyph);
SkASSERT(scaler);
SkASSERT(fCache.find(glyph->fPackedID));
SkASSERT(NULL == glyph->fPlot);
SkAutoUnref ar(SkSafeRef(scaler));
int bytesPerPixel = GrMaskFormatBytesPerPixel(glyph->fMaskFormat);
size_t size = glyph->fBounds.area() * bytesPerPixel;
GrAutoMalloc<1024> storage(size);
if (GrGlyph::kDistance_MaskStyle == GrGlyph::UnpackMaskStyle(glyph->fPackedID)) {
if (!scaler->getPackedGlyphDFImage(glyph->fPackedID, glyph->width(),
glyph->height(),
storage.get())) {
return false;
}
} else {
if (!scaler->getPackedGlyphImage(glyph->fPackedID, glyph->width(),
glyph->height(),
glyph->width() * bytesPerPixel,
storage.get())) {
return false;
}
}
bool success = fBatchFontCache->addToAtlas(this, &glyph->fID, batchTarget, glyph->fMaskFormat,
glyph->width(), glyph->height(),
storage.get(), &glyph->fAtlasLocation);
if (success) {
fAtlasedGlyphs++;
}
return success;
}
<|endoftext|>
|
<commit_before>#include "colorpickerscene.hpp"
#include <QApplication>
#include <QClipboard>
#include <QGraphicsEllipseItem>
#include <QGraphicsPixmapItem>
#include <QGraphicsTextItem>
#include <QTimer>
ColorPickerScene::ColorPickerScene(QPixmap *pixmap, QWidget *parentWidget)
: QGraphicsScene(), QGraphicsView(this, parentWidget) {
setFrameShape(QFrame::NoFrame); // Time taken to solve: A george99g and 38 minutes.
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing);
setCursor(QCursor(Qt::CrossCursor));
setMouseTracking(true);
pItem = addPixmap(*pixmap);
pItem->setZValue(-2);
ellipse = addEllipse(QRectF(QCursor::pos(), QSize(20, 20)), QPen(Qt::cyan), Qt::NoBrush);
QFont font("Monospace");
font.setStyleHint(QFont::Monospace);
text = addText("#hiyouu", font);
textBackground = addRect(text->boundingRect(), Qt::NoPen, QBrush(Qt::black));
text->setPos(QCursor::pos() + QPoint(25, 0));
textBackground->setPos(text->pos());
textBackground->setZValue(-1);
color = pItem->pixmap().toImage().pixelColor(QCursor::pos());
text->setPlainText(color.name());
ellipse->setBrush(color);
}
void ColorPickerScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
ellipse->setRect(QRectF(event->scenePos(), QSize(20, 20)));
color = pItem->pixmap().toImage().pixelColor(event->scenePos().toPoint());
text->setPos(QCursor::pos() + QPoint(25, 0));
text->setPlainText(color.name());
textBackground->setPos(text->pos());
ellipse->setBrush(color);
}
void ColorPickerScene::keyPressEvent(QKeyEvent *event) {
if (event->key() == Qt::Key_Return) QApplication::clipboard()->setText(color.name());
if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Escape) close();
}
void ColorPickerScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *) {
QApplication::clipboard()->setText(color.name());
close();
}
<commit_msg>Make the scope and text stay in the screen<commit_after>#include "colorpickerscene.hpp"
#include <QApplication>
#include <QClipboard>
#include <QGraphicsEllipseItem>
#include <QGraphicsPixmapItem>
#include <QGraphicsTextItem>
#include <QTimer>
ColorPickerScene::ColorPickerScene(QPixmap *pixmap, QWidget *parentWidget)
: QGraphicsScene(), QGraphicsView(this, parentWidget) {
setFrameShape(QFrame::NoFrame); // Time taken to solve: A george99g and 38 minutes.
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing);
setCursor(QCursor(Qt::CrossCursor));
setMouseTracking(true);
pItem = addPixmap(*pixmap);
pItem->setZValue(-2);
ellipse = addEllipse(QRectF(QCursor::pos(), QSize(20, 20)), QPen(Qt::cyan), Qt::NoBrush);
QFont font("Monospace");
font.setStyleHint(QFont::Monospace);
text = addText("#hiyouu", font);
textBackground = addRect(text->boundingRect(), Qt::NoPen, QBrush(Qt::black));
text->setPos(QCursor::pos() + QPoint(25, 0));
textBackground->setPos(text->pos());
textBackground->setZValue(-1);
color = pItem->pixmap().toImage().pixelColor(QCursor::pos());
text->setPlainText(color.name());
ellipse->setBrush(color);
}
void ColorPickerScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
color = pItem->pixmap().toImage().pixelColor(event->scenePos().toPoint());
text->setPlainText(color.name());
ellipse->setBrush(color);
qreal bottom = rect().bottom(); // max y
qreal right = rect().right(); // max x
qreal width = text->boundingRect().width();
qreal height = text->boundingRect().height();
QPointF origPoint = event->scenePos() + QPoint(25, 0);
QPointF scopePoint = event->scenePos();
QPointF resPoint = origPoint;
if (origPoint.x() + width > right) {
scopePoint -= QPoint(20, 0);
resPoint -= QPoint(50 + width, 0);
}
if (origPoint.y() + height > bottom) {
scopePoint -= QPoint(0, 20);
resPoint -= QPoint(0, height);
}
ellipse->setRect(QRectF(scopePoint, QSize(20, 20)));
text->setPos(resPoint);
textBackground->setPos(text->pos());
// How does this work? I have no clue....
// I mean.. It kinda makes sense when you look through it carefully
// But it's still a mess.
}
void ColorPickerScene::keyPressEvent(QKeyEvent *event) {
if (event->key() == Qt::Key_Return) QApplication::clipboard()->setText(color.name());
if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Escape) close();
}
void ColorPickerScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *) {
QApplication::clipboard()->setText(color.name());
close();
}
<|endoftext|>
|
<commit_before>#include "Fullback.hpp"
#include <Constants.hpp>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>
#include "../../Window.hpp"
#include <Geometry2d/util.h>
using namespace std;
Gameplay::Behaviors::Fullback::Fullback(GameplayModule *gameplay, Side side):
Behavior(gameplay, 1),
_side(side)
{
}
bool Gameplay::Behaviors::Fullback::assign(set<Robot *> &available)
{
_robots.clear();
if (!takeBest(available))
{
return false;
}
//Initial state
_state = Init;
//initialize windowevaluator
_winEval = boost::make_shared<Gameplay::WindowEvaluator>(Behavior::gameplay()->state());
_winEval->debug = false;
return _robots.size() >= _minRobots;
}
bool Gameplay::Behaviors::Fullback::run()
{
if (!assigned() || !allVisible() || !_winEval)
{
return false;
}
Geometry2d::Point ballFuture = ball().pos + ball().vel;
//goal line, for intersection detection
Geometry2d::Segment goalLine(Geometry2d::Point(-Constants::Field::GoalWidth / 2.0f, 0),
Geometry2d::Point(Constants::Field::GoalWidth / 2.0f, 0));
// Update the target window
_winEval->exclude.clear();
_winEval->exclude.push_back(Behavior::robot()->pos());
//exclude robots that arn't the fullback
//_winEval->run(ball().pos, goalLine);
BOOST_FOREACH(Fullback *f, otherFullbacks)
{
if (f->robot())
{
_winEval->exclude.push_back(f->robot()->pos());
}
}
_winEval->run(ballFuture, goalLine);
Window* best = 0;
Behavior* goalie = _gameplay->goalie();
bool needTask = false;
//pick biggest window on appropriate side
if (goalie && goalie->robot())
{
BOOST_FOREACH(Window* window, _winEval->windows)
{
if (_side == Left)
{
if (!best || window->segment.center().x < goalie->robot()->pos().x)
{
best = window;
}
}
else if (_side == Right)
{
if (!best || window->segment.center().x > goalie->robot()->pos().x)
{
best = window;
}
}
}
}
else
{
//if no side parameter...stay in the middle
float bestDist = 0;
BOOST_FOREACH(Window* window, _winEval->windows)
{
Geometry2d::Segment seg(window->segment.center(), ball().pos);
float newDist = seg.distTo(Behavior::robot()->pos());
if (!best || newDist < bestDist)
{
best = window;
bestDist = newDist;
}
}
}
if (best && ((_side==Left&&ball().pos.x>=0) || (_side==Right&&ball().pos.x<0)))
{
Geometry2d::Segment shootLine(ball().pos, ball().pos + ball().vel.normalized() * 7.0);
Geometry2d::Segment& winSeg = best->segment;
if (ball().vel.magsq() > 0.03 && winSeg.intersects(shootLine))
{
robot()->move(shootLine.nearestPoint(Behavior::robot()->pos()));
robot()->faceNone();
}
else
{
const float winSize = winSeg.length();
if (winSize < Constants::Ball::Radius)
{
needTask = true;
}
else
{
const float radius = .7;
Geometry2d::Circle arc(Geometry2d::Point(), radius);
Geometry2d::Line shot(winSeg.center(), ballFuture);
Geometry2d::Point dest[2];
bool intersected = shot.intersects(arc, &dest[0], &dest[1]);
if (intersected)
{
if (dest[0].y > 0)
{
Behavior::robot()->move(dest[0]);
}
else
{
Behavior::robot()->move(dest[1]);
}
Behavior::robot()->face(ballFuture);
}
else
{
needTask = true;
}
}
}
}
else
{
needTask = true;
}
bool debug = (robot()->id() == 3);
if (debug) printf("\nneedTask %d\n", needTask);
if(needTask){
//goal line, for intersection detection
Geometry2d::Segment goalLine(Geometry2d::Point(-Constants::Field::GoalWidth / 2.0f, 0),
Geometry2d::Point(Constants::Field::GoalWidth / 2.0f, 0));
//goal arc
const float radius = .7;
Geometry2d::Circle arc(Geometry2d::Point(), radius);
//opponent with ball
Robot* oppWithBall = 0;
float minDist = 999;
BOOST_FOREACH(Robot *r, _gameplay->opp)
{
float dist = r->pos().distTo(ball().pos);
if(dist < minDist)
{
minDist = dist;
oppWithBall = r;
}
}
if (debug) printf("oppWithBall %p\n", oppWithBall);
if(oppWithBall == 0)
return false; // need opp to block
// block opponents that are pointed towards our goal and are on our side (left or right) and do not have the ball
BOOST_FOREACH(Robot *r, _gameplay->opp)
{
if(r == oppWithBall)
continue;
bool sameSide = ((_side==Left&&r->pos().x<=0) || (_side==Right&&r->pos().x>=0));
bool nonDefender = (r->pos().y < 3*Constants::Field::Length/4);
bool facingGoal;
Geometry2d::Point facing(cos(DegreesToRadians * r->angle()),sin(DegreesToRadians * r->angle())); // make sure not degrees!
facing *= 20;
Geometry2d::Segment los(facing, r->pos());
Geometry2d::Point intr;
facingGoal = los.intersects(goalLine,&intr);
if (debug) printf("%d: sameSide %d nonDefender %d facingGoal %d\n", r->id(), sameSide, nonDefender, facingGoal);
if(sameSide && nonDefender && facingGoal)
{
Geometry2d::Point dest[2];
Geometry2d::Line losLine(facing,r->pos());
bool ballTravelIntersects = losLine.intersects(arc, &dest[0], &dest[1]);
if (debug) printf("ballTravelIntersects %d\n", ballTravelIntersects);
if(!ballTravelIntersects)
continue;
Geometry2d::Point blockPoint = (dest[0].y > 0 ? dest[0] : dest[1]);
Behavior::robot()->move(blockPoint);
Behavior::robot()->face(r->pos());
return true;
}
}
}
if(needTask) //TODO: look at this in detail. Hacked together so that robots don't sit around
{
//if no side parameter...stay in the middle
float bestDist = 0;
BOOST_FOREACH(Window* window, _winEval->windows)
{
Geometry2d::Segment seg(window->segment.center(), ball().pos);
float newDist = seg.distTo(Behavior::robot()->pos());
if (!best || newDist < bestDist)
{
best = window;
bestDist = newDist;
}
}
Geometry2d::Segment shootLine(ball().pos, ball().pos + ball().vel.normalized() * 7.0);
Geometry2d::Segment& winSeg = best->segment;
robot()->move(shootLine.nearestPoint(Behavior::robot()->pos()));
robot()->faceNone();
}
return false;
}
float Gameplay::Behaviors::Fullback::score(Robot* robot)
{
//robot closest to the back line wins
return robot->pos().y;
}
<commit_msg>Clean up debug output in Fullback<commit_after>#include "Fullback.hpp"
#include <Constants.hpp>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>
#include "../../Window.hpp"
#include <Geometry2d/util.h>
using namespace std;
Gameplay::Behaviors::Fullback::Fullback(GameplayModule *gameplay, Side side):
Behavior(gameplay, 1),
_side(side)
{
}
bool Gameplay::Behaviors::Fullback::assign(set<Robot *> &available)
{
_robots.clear();
if (!takeBest(available))
{
return false;
}
//Initial state
_state = Init;
//initialize windowevaluator
_winEval = boost::make_shared<Gameplay::WindowEvaluator>(Behavior::gameplay()->state());
_winEval->debug = false;
return _robots.size() >= _minRobots;
}
bool Gameplay::Behaviors::Fullback::run()
{
if (!assigned() || !allVisible() || !_winEval)
{
return false;
}
Geometry2d::Point ballFuture = ball().pos + ball().vel;
//goal line, for intersection detection
Geometry2d::Segment goalLine(Geometry2d::Point(-Constants::Field::GoalWidth / 2.0f, 0),
Geometry2d::Point(Constants::Field::GoalWidth / 2.0f, 0));
// Update the target window
_winEval->exclude.clear();
_winEval->exclude.push_back(Behavior::robot()->pos());
//exclude robots that arn't the fullback
//_winEval->run(ball().pos, goalLine);
BOOST_FOREACH(Fullback *f, otherFullbacks)
{
if (f->robot())
{
_winEval->exclude.push_back(f->robot()->pos());
}
}
_winEval->run(ballFuture, goalLine);
Window* best = 0;
Behavior* goalie = _gameplay->goalie();
bool needTask = false;
//pick biggest window on appropriate side
if (goalie && goalie->robot())
{
BOOST_FOREACH(Window* window, _winEval->windows)
{
if (_side == Left)
{
if (!best || window->segment.center().x < goalie->robot()->pos().x)
{
best = window;
}
}
else if (_side == Right)
{
if (!best || window->segment.center().x > goalie->robot()->pos().x)
{
best = window;
}
}
}
}
else
{
//if no side parameter...stay in the middle
float bestDist = 0;
BOOST_FOREACH(Window* window, _winEval->windows)
{
Geometry2d::Segment seg(window->segment.center(), ball().pos);
float newDist = seg.distTo(Behavior::robot()->pos());
if (!best || newDist < bestDist)
{
best = window;
bestDist = newDist;
}
}
}
if (best && ((_side==Left&&ball().pos.x>=0) || (_side==Right&&ball().pos.x<0)))
{
Geometry2d::Segment shootLine(ball().pos, ball().pos + ball().vel.normalized() * 7.0);
Geometry2d::Segment& winSeg = best->segment;
if (ball().vel.magsq() > 0.03 && winSeg.intersects(shootLine))
{
robot()->move(shootLine.nearestPoint(Behavior::robot()->pos()));
robot()->faceNone();
}
else
{
const float winSize = winSeg.length();
if (winSize < Constants::Ball::Radius)
{
needTask = true;
}
else
{
const float radius = .7;
Geometry2d::Circle arc(Geometry2d::Point(), radius);
Geometry2d::Line shot(winSeg.center(), ballFuture);
Geometry2d::Point dest[2];
bool intersected = shot.intersects(arc, &dest[0], &dest[1]);
if (intersected)
{
if (dest[0].y > 0)
{
Behavior::robot()->move(dest[0]);
}
else
{
Behavior::robot()->move(dest[1]);
}
Behavior::robot()->face(ballFuture);
}
else
{
needTask = true;
}
}
}
}
else
{
needTask = true;
}
if(needTask){
//goal line, for intersection detection
Geometry2d::Segment goalLine(Geometry2d::Point(-Constants::Field::GoalWidth / 2.0f, 0),
Geometry2d::Point(Constants::Field::GoalWidth / 2.0f, 0));
//goal arc
const float radius = .7;
Geometry2d::Circle arc(Geometry2d::Point(), radius);
//opponent with ball
Robot* oppWithBall = 0;
float minDist = 999;
BOOST_FOREACH(Robot *r, _gameplay->opp)
{
float dist = r->pos().distTo(ball().pos);
if(dist < minDist)
{
minDist = dist;
oppWithBall = r;
}
}
if(oppWithBall == 0)
return false; // need opp to block
// block opponents that are pointed towards our goal and are on our side (left or right) and do not have the ball
BOOST_FOREACH(Robot *r, _gameplay->opp)
{
if(r == oppWithBall)
continue;
bool sameSide = ((_side==Left&&r->pos().x<=0) || (_side==Right&&r->pos().x>=0));
bool nonDefender = (r->pos().y < 3*Constants::Field::Length/4);
bool facingGoal;
Geometry2d::Point facing(cos(DegreesToRadians * r->angle()),sin(DegreesToRadians * r->angle())); // make sure not degrees!
facing *= 20;
Geometry2d::Segment los(facing, r->pos());
Geometry2d::Point intr;
facingGoal = los.intersects(goalLine,&intr);
printf("%d: sameSide %d nonDefender %d facingGoal %d\n", r->id(), sameSide, nonDefender, facingGoal);
if(sameSide && nonDefender && facingGoal)
{
Geometry2d::Point dest[2];
Geometry2d::Line losLine(facing,r->pos());
bool ballTravelIntersects = losLine.intersects(arc, &dest[0], &dest[1]);
printf("ballTravelIntersects %d\n", ballTravelIntersects);
if(!ballTravelIntersects)
continue;
Geometry2d::Point blockPoint = (dest[0].y > 0 ? dest[0] : dest[1]);
Behavior::robot()->move(blockPoint);
Behavior::robot()->face(r->pos());
return true;
}
}
}
if(needTask) //TODO: look at this in detail. Hacked together so that robots don't sit around
{
//if no side parameter...stay in the middle
float bestDist = 0;
BOOST_FOREACH(Window* window, _winEval->windows)
{
Geometry2d::Segment seg(window->segment.center(), ball().pos);
float newDist = seg.distTo(Behavior::robot()->pos());
if (!best || newDist < bestDist)
{
best = window;
bestDist = newDist;
}
}
Geometry2d::Segment shootLine(ball().pos, ball().pos + ball().vel.normalized() * 7.0);
Geometry2d::Segment& winSeg = best->segment;
robot()->move(shootLine.nearestPoint(Behavior::robot()->pos()));
robot()->faceNone();
}
return false;
}
float Gameplay::Behaviors::Fullback::score(Robot* robot)
{
//robot closest to the back line wins
return robot->pos().y;
}
<|endoftext|>
|
<commit_before>#ifndef ALEPH_TOPOLOGY_IO_EDGE_LISTS_HH__
#define ALEPH_TOPOLOGY_IO_EDGE_LISTS_HH__
#include <algorithm>
#include <fstream>
#include <set>
#include <string>
#include <vector>
#include "utilities/String.hh"
namespace aleph
{
namespace io
{
class EdgeListReader
{
public:
bool readWeights() const noexcept { return _readWeights; }
bool trimLines() const noexcept { return _trimLines; }
void setReadWeights( bool value = true ) noexcept { _readWeights = value; }
void setTrimLines( bool value = true ) noexcept { _trimLines = value; }
template <class SimplicialComplex> void operator()( std::ifstream& in, SimplicialComplex& K )
{
using namespace utilities;
using Simplex = typename SimplicialComplex::ValueType;
using DataType = typename Simplex::DataType;
using VertexType = typename Simplex::VertexType;
std::string line;
std::set<Simplex> vertices;
std::vector<Simplex> edges;
while( in )
{
std::getline( in, line );
if( _trimLines )
line = trim( line );
// TODO: Make this configurable and permit splitting by different
// tokens such as commas
auto tokens = split( line );
// Skip empty lines and comments
if( line.empty() || std::find( _commentTokens.begin(), _commentTokens.end(), line.front() ) != _commentTokens.end() )
continue;
if( tokens.size() >= 2 )
{
// TODO: Make order of vertices & weights configurable?
VertexType u = convert<VertexType>( tokens[0] );
VertexType v = convert<VertexType>( tokens[1] );
DataType w = DataType();
if( tokens.size() >= 3 && _readWeights )
w = convert<DataType>( tokens[2] );
edges.push_back( Simplex( { u, v }, w ) );
vertices.insert( Simplex( u ) );
vertices.insert( Simplex( v ) );
}
else
{
// TODO: Throw error?
}
}
std::vector<Simplex> simplices;
simplices.reserve( vertices.size() + edges.size() );
simplices.insert( simplices.end(), vertices.begin(), vertices.end() );
simplices.insert( simplices.end(), edges.begin(), edges.end() );
K = SimplicialComplex( simplices.begin(), simplices.end() );
}
private:
std::vector<char> _commentTokens = { '#', '%', '\"', '*' };
bool _readWeights = true;
bool _trimLines = true;
};
}
}
#endif
<commit_msg>Preventing creation of duplicate simplices<commit_after>#ifndef ALEPH_TOPOLOGY_IO_EDGE_LISTS_HH__
#define ALEPH_TOPOLOGY_IO_EDGE_LISTS_HH__
#include <algorithm>
#include <fstream>
#include <set>
#include <string>
#include <vector>
#include "utilities/String.hh"
namespace aleph
{
namespace io
{
class EdgeListReader
{
public:
bool readWeights() const noexcept { return _readWeights; }
bool trimLines() const noexcept { return _trimLines; }
void setReadWeights( bool value = true ) noexcept { _readWeights = value; }
void setTrimLines( bool value = true ) noexcept { _trimLines = value; }
template <class SimplicialComplex> void operator()( std::ifstream& in, SimplicialComplex& K )
{
using namespace utilities;
using Simplex = typename SimplicialComplex::ValueType;
using DataType = typename Simplex::DataType;
using VertexType = typename Simplex::VertexType;
std::string line;
std::set<Simplex> vertices;
std::vector<Simplex> edges;
while( in )
{
std::getline( in, line );
if( _trimLines )
line = trim( line );
// TODO: Make this configurable and permit splitting by different
// tokens such as commas
auto tokens = split( line );
// Skip empty lines and comments
if( line.empty() || std::find( _commentTokens.begin(), _commentTokens.end(), line.front() ) != _commentTokens.end() )
continue;
if( tokens.size() >= 2 )
{
// TODO: Make order of vertices & weights configurable?
VertexType u = convert<VertexType>( tokens[0] );
VertexType v = convert<VertexType>( tokens[1] );
DataType w = DataType();
if( tokens.size() >= 3 && _readWeights )
w = convert<DataType>( tokens[2] );
edges.push_back( Simplex( { u, v }, w ) );
vertices.insert( Simplex( u ) );
vertices.insert( Simplex( v ) );
}
else
{
// TODO: Throw error?
}
}
// Using a set has the advantage of ensuring that duplicate
// simplices are deleted automatically. A duplicate simplex
// is usually created by the input data set itself. It must
// not be considered for any subsequent analysis.
std::set<Simplex> simplices;
simplices.insert( vertices.begin(), vertices.end() );
simplices.insert( edges.begin(), edges.end() );
K = SimplicialComplex( simplices.begin(), simplices.end() );
}
private:
std::vector<char> _commentTokens = { '#', '%', '\"', '*' };
bool _readWeights = true;
bool _trimLines = true;
};
}
}
#endif
<|endoftext|>
|
<commit_before>/* Rapicorn
* Copyright (C) 2008 Tim Janik
*
* 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.
*
* A copy of the GNU Lesser General Public License should ship along
* with this library; if not, see http://www.gnu.org/copyleft/.
*/
#include "blitfuncs.hh"
#ifdef __MMX__
#include <mmintrin.h>
#endif /* __MMX__ */
namespace Rapicorn {
namespace Blit {
#ifdef __MMX__
void
render_optimize_mmx (void)
{
}
#else /* !__MMX__ */
void
render_optimize_mmx (void)
{}
#endif /* !__MMX__ */
} // Blit
} // Rapicorn
<commit_msg>Use MMX for gradient rendering.<commit_after>/* Rapicorn
* Copyright (C) 2008 Tim Janik
*
* 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.
*
* A copy of the GNU Lesser General Public License should ship along
* with this library; if not, see http://www.gnu.org/copyleft/.
*/
#include "blitfuncs.hh"
#ifdef __MMX__
#include <mmintrin.h>
#endif /* __MMX__ */
namespace Rapicorn {
namespace Blit {
#ifdef __MMX__
#define mmx_zero ((__m64) 0x0000000000000000ULL)
#define mmx_shiftl(v,bits) (_mm_slli_si64 ((v), (bits))) // v << bits
#define mmx_shiftr(v,bits) (_mm_srli_si64 ((v), (bits))) // v >> bits
static inline __m64
load_hi32lo32 (uint32_t a,
uint32_t b)
{
__m64 mhi = _mm_cvtsi32_si64 (a); // 00 00 00 00 a3 a2 a1 a0
__m64 mlo = _mm_cvtsi32_si64 (b); // 00 00 00 00 b3 b2 b1 b0
mhi = mmx_shiftl (mhi, 32); // a3 a2 a1 a0 00 00 00 00
return _mm_or_si64 (mhi, mlo); // a3 a2 a1 a0 b3 b2 b1 b0
}
static inline __m64
packbyte_8x8 (__m64 a, // 4x16
__m64 c) // 4x16
{
// US = unsigned saturation, i.e. with (uint8) CLAMP (uint16), produce:
// US (c7c6) US (c5c4) US (c3c2) US (c1c0) US (a7a6) US (a5a4) US (a3a2) US (a1a0)
return _mm_packs_pu16 (a, c); // US: CCccCCcc AAaaAAaa
}
static inline uint32
store_00008888 (__m64 vv) // vv = AA aa BB bb CC cc DD dd
{
__m64 zz = _mm_setzero_si64(); // zz = 00 00 00 00 00 00 00 00
__m64 ip = packbyte_8x8 (vv, zz); // ip = US (ZZzzZZzz AaBbCcDd)
return _mm_cvtsi64_si32 (ip); // return 0x00000000ffffffff & ip
}
static inline uint32_t
color_agrb24 (__m64 ag24, // 00 aa .. .. 00 gg .. ..
__m64 rb24) // 00 rr .. .. 00 bb .. ..
{
const __m64 mmx_f0f0 = (__m64) 0xffff0000ffff0000ULL;
ag24 = _mm_and_si64 (ag24, mmx_f0f0); // 00 aa 00 00 00 gg 00 00
rb24 = _mm_and_si64 (rb24, mmx_f0f0); // 00 rr 00 00 00 bb 00 00
rb24 = mmx_shiftr (rb24, 16); // 00 00 00 rr 00 00 00 bb
__m64 mtmp = _mm_or_si64 (ag24, rb24); // 00 aa 00 rr 00 gg 00 bb
return store_00008888 (mtmp); // argb
}
static inline __m64
mmx_dither_rand (__m64 maccu)
{
// 2^14-period mod16 generator: accu = (accu * 47989) & 0xffff;
const __m64 mfact = (__m64) 0xbb75bb75bb75bb75ULL;
return _mm_mullo_pi16 (maccu, mfact); // maccu_ * mfact_
}
static __m64 mmx_dither_accu = (__m64) 0xa9d1878556c9bcddULL; // 4095-steps apart seeds
static void
mmx_gradient_line (uint32 *pixel,
uint32 *bound,
uint32 col1,
uint32 col2)
{
uint32 Ca = COLA (col1) << 16, Cr = COLR (col1) << 16, Cg = COLG (col1) << 16, Cb = COLB (col1) << 16;
int32 Da = (COLA (col2) << 16) - Ca, Dr = (COLR (col2) << 16) - Cr;
int32 Dg = (COLG (col2) << 16) - Cg, Db = (COLB (col2) << 16) - Cb;
int delta = bound - pixel - 1;
if (delta)
{
Da /= delta;
Dr /= delta;
Dg /= delta;
Db /= delta;
}
const bool ditherp = 1;
const uint32 roundoffs = ditherp ? 0 : 0x7fff; // rounding offset when not dithering
__m64 maccu = mmx_dither_accu;
__m64 mdag = load_hi32lo32 (Da, Dg); // 00 aa .. .. 00 gg .. .. (mdag = alpha green)
__m64 mdrb = load_hi32lo32 (Dr, Db); // 00 rr .. .. 00 bb .. .. (mdrb = red blue)
__m64 mcag = load_hi32lo32 (Ca + roundoffs, Cg + roundoffs); // 00 aa 7f ff 00 gg 7f ff (mcag = alpha green)
__m64 mcrb = load_hi32lo32 (Cr + roundoffs, Cb + roundoffs); // 00 rr 7f ff 00 bb 7f ff (mcrb = red blue)
while (pixel < bound)
{
maccu = mmx_dither_rand (maccu); // rand3 rand2 rand1 rand0
__m64 mvag = _mm_unpacklo_pi16 (maccu, mmx_zero); // 00 00 rand1 00 00 rand0
__m64 mvrb = _mm_unpackhi_pi16 (maccu, mmx_zero); // 00 00 rand3 00 00 rand2
mvag = _mm_add_pi32 (mcag, mvag); // mcag_ + dither
mvrb = _mm_add_pi32 (mcrb, mvrb); // mcrb_ + dither
if (ditherp)
*pixel = color_agrb24 (mvag, mvrb);
else
*pixel = color_agrb24 (mcag, mcrb);
mcag = _mm_add_pi32 (mcag, mdag); // mcag += mdag
mcrb = _mm_add_pi32 (mcrb, mdrb); // mcrb += mdrb
// printf ("pixel(%p): 0x%08x\n", pixel, *pixel);
pixel++;
}
mmx_dither_accu = maccu;
_mm_empty(); // cleanup FPU after MMX use
}
void
render_optimize_mmx (void)
{
render.gradient_line = mmx_gradient_line;
}
#else /* !__MMX__ */
void
render_optimize_mmx (void)
{}
#endif /* !__MMX__ */
} // Blit
} // Rapicorn
<|endoftext|>
|
<commit_before>/**
* @file
* @copyright defined in eos/LICENSE
*/
#pragma once
#include <eosio/chain/transaction.hpp>
#include <eosio/chain/types.hpp>
#include <boost/asio/io_context.hpp>
#include <future>
namespace boost { namespace asio {
class thread_pool;
}}
namespace eosio { namespace chain {
class transaction_metadata;
using transaction_metadata_ptr = std::shared_ptr<transaction_metadata>;
using signing_keys_future_value_type = std::tuple<chain_id_type, fc::microseconds, std::shared_ptr<flat_set<public_key_type>>>;
using signing_keys_future_type = std::shared_future<signing_keys_future_value_type>;
using recovery_keys_type = std::pair<fc::microseconds, std::shared_ptr<flat_set<public_key_type>>>;
/**
* This data structure should store context-free cached data about a transaction such as
* packed/unpacked/compressed and recovered keys
*/
class transaction_metadata {
private:
const packed_transaction_ptr _packed_trx;
const transaction_id_type _id;
const transaction_id_type _signed_id;
mutable std::mutex _signing_keys_future_mtx;
mutable signing_keys_future_type _signing_keys_future;
public:
bool accepted = false; // not thread safe
bool implicit = false; // not thread safe
bool scheduled = false; // not thread safe
transaction_metadata() = delete;
transaction_metadata(const transaction_metadata&) = delete;
transaction_metadata(transaction_metadata&&) = delete;
transaction_metadata operator=(transaction_metadata&) = delete;
transaction_metadata operator=(transaction_metadata&&) = delete;
explicit transaction_metadata( const signed_transaction& t, uint32_t max_variable_sig_size = UINT32_MAX, packed_transaction::compression_type c = packed_transaction::compression_type::none )
: _packed_trx( std::make_shared<packed_transaction>( t, c ) )
, _id( t.id() )
, _signed_id( digest_type::hash( *_packed_trx ) ) {
check_variable_sig_size(max_variable_sig_size);
}
explicit transaction_metadata( const packed_transaction_ptr& ptrx, uint32_t max_variable_sig_size = UINT32_MAX )
: _packed_trx( ptrx )
, _id( ptrx->id() )
, _signed_id( digest_type::hash( *_packed_trx ) ) {
check_variable_sig_size(max_variable_sig_size);
}
void check_variable_sig_size(uint32_t max) {
for(const signature_type& sig : _packed_trx->get_signed_transaction().signatures)
EOS_ASSERT(sig.variable_size() <= max, sig_variable_size_limit_exception, "signature variable length component size (${s}) greater than subjective maximum (${m})", ("s", sig.variable_size())("m", max));
}
const packed_transaction_ptr& packed_trx()const { return _packed_trx; }
const transaction_id_type& id()const { return _id; }
// can be called from any thread. It is recommended that next() immediately post to application thread for
// future processing since next() will be called from the thread_pool.
static void start_recover_keys( const transaction_metadata_ptr& mtrx, boost::asio::io_context& thread_pool,
const chain_id_type& chain_id, fc::microseconds time_limit,
std::function<void()> next = std::function<void()>() );
// start_recover_keys can be called first to begin key recovery
// if time_limit of start_recover_keys exceeded (or any other exception) then this can throw
recovery_keys_type recover_keys( const chain_id_type& chain_id ) const;
};
} } // eosio::chain
<commit_msg>Remove unneeded signed_id<commit_after>/**
* @file
* @copyright defined in eos/LICENSE
*/
#pragma once
#include <eosio/chain/transaction.hpp>
#include <eosio/chain/types.hpp>
#include <boost/asio/io_context.hpp>
#include <future>
namespace boost { namespace asio {
class thread_pool;
}}
namespace eosio { namespace chain {
class transaction_metadata;
using transaction_metadata_ptr = std::shared_ptr<transaction_metadata>;
using signing_keys_future_value_type = std::tuple<chain_id_type, fc::microseconds, std::shared_ptr<flat_set<public_key_type>>>;
using signing_keys_future_type = std::shared_future<signing_keys_future_value_type>;
using recovery_keys_type = std::pair<fc::microseconds, std::shared_ptr<flat_set<public_key_type>>>;
/**
* This data structure should store context-free cached data about a transaction such as
* packed/unpacked/compressed and recovered keys
*/
class transaction_metadata {
private:
const packed_transaction_ptr _packed_trx;
const transaction_id_type _id;
mutable std::mutex _signing_keys_future_mtx;
mutable signing_keys_future_type _signing_keys_future;
public:
bool accepted = false; // not thread safe
bool implicit = false; // not thread safe
bool scheduled = false; // not thread safe
transaction_metadata() = delete;
transaction_metadata(const transaction_metadata&) = delete;
transaction_metadata(transaction_metadata&&) = delete;
transaction_metadata operator=(transaction_metadata&) = delete;
transaction_metadata operator=(transaction_metadata&&) = delete;
explicit transaction_metadata( const signed_transaction& t, uint32_t max_variable_sig_size = UINT32_MAX, packed_transaction::compression_type c = packed_transaction::compression_type::none )
: _packed_trx( std::make_shared<packed_transaction>( t, c ) )
, _id( t.id() ) {
check_variable_sig_size(max_variable_sig_size);
}
explicit transaction_metadata( const packed_transaction_ptr& ptrx, uint32_t max_variable_sig_size = UINT32_MAX )
: _packed_trx( ptrx )
, _id( ptrx->id() ) {
check_variable_sig_size(max_variable_sig_size);
}
void check_variable_sig_size(uint32_t max) {
for(const signature_type& sig : _packed_trx->get_signed_transaction().signatures)
EOS_ASSERT(sig.variable_size() <= max, sig_variable_size_limit_exception, "signature variable length component size (${s}) greater than subjective maximum (${m})", ("s", sig.variable_size())("m", max));
}
const packed_transaction_ptr& packed_trx()const { return _packed_trx; }
const transaction_id_type& id()const { return _id; }
// can be called from any thread. It is recommended that next() immediately post to application thread for
// future processing since next() will be called from the thread_pool.
static void start_recover_keys( const transaction_metadata_ptr& mtrx, boost::asio::io_context& thread_pool,
const chain_id_type& chain_id, fc::microseconds time_limit,
std::function<void()> next = std::function<void()>() );
// start_recover_keys can be called first to begin key recovery
// if time_limit of start_recover_keys exceeded (or any other exception) then this can throw
recovery_keys_type recover_keys( const chain_id_type& chain_id ) const;
};
} } // eosio::chain
<|endoftext|>
|
<commit_before>/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "DefragmentText.h"
#include <vector>
#include <utility>
#include "core/Resource.h"
#include "serialization/PayloadSerializer.h"
#include "TextFragmentUtils.h"
#include "utils/gsl.h"
#include "utils/StringUtils.h"
namespace org::apache::nifi::minifi::processors {
const core::Relationship DefragmentText::Success("success", "Flowfiles that have been successfully defragmented");
const core::Relationship DefragmentText::Failure("failure", "Flowfiles that failed the defragmentation process");
const core::Relationship DefragmentText::Self("__self__", "Marks the FlowFile to be owned by this processor");
const core::Property DefragmentText::Pattern(
core::PropertyBuilder::createProperty("Pattern")
->withDescription("A regular expression to match at the start or end of messages.")
->isRequired(true)->build());
const core::Property DefragmentText::PatternLoc(
core::PropertyBuilder::createProperty("Pattern Location")->withDescription("Whether the pattern is located at the start or at the end of the messages.")
->withAllowableValues(PatternLocation::values())
->withDefaultValue(toString(PatternLocation::START_OF_MESSAGE))->build());
const core::Property DefragmentText::MaxBufferSize(
core::PropertyBuilder::createProperty("Max Buffer Size")
->withDescription("The maximum buffer size, if the buffer exceeds this, it will be transferred to failure. Expected format is <size> <data unit>")
->withType(core::StandardValidators::get().DATA_SIZE_VALIDATOR)->build());
const core::Property DefragmentText::MaxBufferAge(
core::PropertyBuilder::createProperty("Max Buffer Age")->
withDescription("The maximum age of the buffer after which it will be transferred to success when matching Start of Message patterns or to failure when matching End of Message patterns. "
"Expected format is <duration> <time unit>")
->withDefaultValue("10 min")
->build());
void DefragmentText::initialize() {
setSupportedRelationships({Success, Failure});
setSupportedProperties({Pattern, PatternLoc, MaxBufferAge, MaxBufferSize});
}
void DefragmentText::onSchedule(core::ProcessContext* context, core::ProcessSessionFactory*) {
gsl_Expects(context);
std::string max_buffer_age_str;
if (context->getProperty(MaxBufferAge.getName(), max_buffer_age_str)) {
core::TimeUnit unit;
uint64_t max_buffer_age;
if (core::Property::StringToTime(max_buffer_age_str, max_buffer_age, unit) && core::Property::ConvertTimeUnitToMS(max_buffer_age, unit, max_buffer_age)) {
buffer_.setMaxAge(std::chrono::milliseconds(max_buffer_age));
logger_->log_trace("The Buffer maximum age is configured to be %" PRIu64 " ms", max_buffer_age);
}
}
std::string max_buffer_size_str;
if (context->getProperty(MaxBufferSize.getName(), max_buffer_size_str)) {
uint64_t max_buffer_size = core::DataSizeValue(max_buffer_size_str).getValue();
if (max_buffer_size > 0) {
buffer_.setMaxSize(max_buffer_size);
logger_->log_trace("The Buffer maximum size is configured to be %" PRIu64 " B", max_buffer_size);
}
}
context->getProperty(PatternLoc.getName(), pattern_location_);
std::string pattern_str;
if (context->getProperty(Pattern.getName(), pattern_str) && !pattern_str.empty()) {
pattern_ = std::regex(pattern_str);
logger_->log_trace("The Pattern is configured to be %s", pattern_str);
} else {
throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Pattern property missing or invalid");
}
}
void DefragmentText::onTrigger(core::ProcessContext*, core::ProcessSession* session) {
gsl_Expects(session);
auto flowFiles = flow_file_store_.getNewFlowFiles();
for (auto& file : flowFiles) {
if (file)
processNextFragment(session, gsl::not_null(std::move(file)));
}
{
std::shared_ptr<core::FlowFile> original_flow_file = session->get();
if (original_flow_file)
processNextFragment(session, gsl::not_null(std::move(original_flow_file)));
}
if (buffer_.maxSizeReached()) {
buffer_.flushAndReplace(session, Failure, nullptr);
return;
}
if (buffer_.maxAgeReached()) {
if (pattern_location_ == PatternLocation::START_OF_MESSAGE)
buffer_.flushAndReplace(session, Success, nullptr);
else
buffer_.flushAndReplace(session, Failure, nullptr);
}
}
void DefragmentText::processNextFragment(core::ProcessSession *session, const gsl::not_null<std::shared_ptr<core::FlowFile>>& next_fragment) {
if (!buffer_.isCompatible(*next_fragment)) {
buffer_.flushAndReplace(session, Failure, nullptr);
session->transfer(next_fragment, Failure);
return;
}
std::shared_ptr<core::FlowFile> split_before_last_pattern;
std::shared_ptr<core::FlowFile> split_after_last_pattern;
bool found_pattern = splitFlowFileAtLastPattern(session, next_fragment, split_before_last_pattern,
split_after_last_pattern);
if (split_before_last_pattern)
buffer_.append(session, gsl::not_null(std::move(split_before_last_pattern)));
if (found_pattern) {
buffer_.flushAndReplace(session, Success, split_after_last_pattern);
}
session->remove(next_fragment);
}
void DefragmentText::updateAttributesForSplitFiles(const core::FlowFile& original_flow_file,
const std::shared_ptr<core::FlowFile>& split_before_last_pattern,
const std::shared_ptr<core::FlowFile>& split_after_last_pattern,
const size_t split_position) const {
std::string base_name, post_name, offset_str;
if (!original_flow_file.getAttribute(textfragmentutils::BASE_NAME_ATTRIBUTE, base_name))
return;
if (!original_flow_file.getAttribute(textfragmentutils::POST_NAME_ATTRIBUTE, post_name))
return;
if (!original_flow_file.getAttribute(textfragmentutils::OFFSET_ATTRIBUTE, offset_str))
return;
size_t fragment_offset = std::stoi(offset_str);
if (split_before_last_pattern) {
std::string first_part_name = textfragmentutils::createFileName(base_name, post_name, fragment_offset, split_before_last_pattern->getSize());
split_before_last_pattern->setAttribute(core::SpecialFlowAttribute::FILENAME, first_part_name);
}
if (split_after_last_pattern) {
std::string second_part_name = textfragmentutils::createFileName(base_name, post_name, fragment_offset + split_position, split_after_last_pattern->getSize());
split_after_last_pattern->setAttribute(core::SpecialFlowAttribute::FILENAME, second_part_name);
split_after_last_pattern->setAttribute(textfragmentutils::OFFSET_ATTRIBUTE, std::to_string(fragment_offset + split_position));
}
}
namespace {
class AppendFlowFileToFlowFile : public OutputStreamCallback {
public:
explicit AppendFlowFileToFlowFile(const gsl::not_null<std::shared_ptr<core::FlowFile>>& flow_file_to_append, PayloadSerializer& serializer)
: flow_file_to_append_(flow_file_to_append), serializer_(serializer) {}
int64_t process(const std::shared_ptr<io::BaseStream> &stream) override {
return serializer_.serialize(flow_file_to_append_, stream);
}
private:
const gsl::not_null<std::shared_ptr<core::FlowFile>>& flow_file_to_append_;
PayloadSerializer& serializer_;
};
void updateAppendedAttributes(core::FlowFile& buffered_ff) {
std::string base_name, post_name, offset_str;
if (!buffered_ff.getAttribute(textfragmentutils::BASE_NAME_ATTRIBUTE, base_name))
return;
if (!buffered_ff.getAttribute(textfragmentutils::POST_NAME_ATTRIBUTE, post_name))
return;
if (!buffered_ff.getAttribute(textfragmentutils::OFFSET_ATTRIBUTE, offset_str))
return;
size_t fragment_offset = std::stoi(offset_str);
std::string buffer_new_name = textfragmentutils::createFileName(base_name, post_name, fragment_offset, buffered_ff.getSize());
buffered_ff.setAttribute(core::SpecialFlowAttribute::FILENAME, buffer_new_name);
}
struct ReadFlowFileContent : public InputStreamCallback {
std::string content;
int64_t process(const std::shared_ptr<io::BaseStream> &stream) override {
content.resize(stream->size());
const auto ret = stream->read(reinterpret_cast<uint8_t *>(content.data()), stream->size());
if (io::isError(ret))
return -1;
return gsl::narrow<int64_t>(ret);
}
};
size_t getSplitPosition(const std::smatch& last_match, DefragmentText::PatternLocation pattern_location) {
size_t split_position = last_match.position(0);
if (pattern_location == DefragmentText::PatternLocation::END_OF_MESSAGE) {
split_position += last_match.length(0);
}
return split_position;
}
} // namespace
bool DefragmentText::splitFlowFileAtLastPattern(core::ProcessSession *session,
const gsl::not_null<std::shared_ptr<core::FlowFile>> &original_flow_file,
std::shared_ptr<core::FlowFile> &split_before_last_pattern,
std::shared_ptr<core::FlowFile> &split_after_last_pattern) const {
ReadFlowFileContent read_flow_file_content;
session->read(original_flow_file, &read_flow_file_content);
auto last_regex_match = utils::StringUtils::getLastRegexMatch(read_flow_file_content.content, pattern_);
if (!last_regex_match.ready()) {
split_before_last_pattern = session->clone(original_flow_file);
split_after_last_pattern = nullptr;
return false;
}
auto split_position = getSplitPosition(last_regex_match, pattern_location_);
if (split_position != 0) {
split_before_last_pattern = session->clone(original_flow_file, 0, split_position);
}
if (split_position != original_flow_file->getSize()) {
split_after_last_pattern = session->clone(original_flow_file, split_position, original_flow_file->getSize() - split_position);
}
updateAttributesForSplitFiles(*original_flow_file, split_before_last_pattern, split_after_last_pattern, split_position);
return true;
}
void DefragmentText::restore(const std::shared_ptr<core::FlowFile>& flowFile) {
if (!flowFile)
return;
flow_file_store_.put(flowFile);
}
std::set<std::shared_ptr<core::Connectable>> DefragmentText::getOutGoingConnections(const std::string &relationship) const {
auto result = core::Connectable::getOutGoingConnections(relationship);
if (relationship == Self.getName()) {
result.insert(std::static_pointer_cast<core::Connectable>(std::const_pointer_cast<core::Processor>(shared_from_this())));
}
return result;
}
void DefragmentText::Buffer::append(core::ProcessSession* session, const gsl::not_null<std::shared_ptr<core::FlowFile>>& flow_file_to_append) {
if (empty()) {
store(session, flow_file_to_append);
return;
}
auto flowFileReader = [&] (const std::shared_ptr<core::FlowFile>& ff, InputStreamCallback* cb) {
return session->read(ff, cb);
};
PayloadSerializer serializer(flowFileReader);
AppendFlowFileToFlowFile append_flow_file_to_flow_file(flow_file_to_append, serializer);
session->add(buffered_flow_file_);
session->append(buffered_flow_file_, &append_flow_file_to_flow_file);
updateAppendedAttributes(*buffered_flow_file_);
session->transfer(buffered_flow_file_, Self);
session->remove(flow_file_to_append);
}
bool DefragmentText::Buffer::maxSizeReached() const {
return !empty()
&& max_size_.has_value()
&& (max_size_.value() < buffered_flow_file_->getSize());
}
bool DefragmentText::Buffer::maxAgeReached() const {
return !empty()
&& max_age_.has_value()
&& (creation_time_ + max_age_.value() < std::chrono::steady_clock::now());
}
void DefragmentText::Buffer::setMaxAge(std::chrono::milliseconds max_age) {
max_age_ = max_age;
}
void DefragmentText::Buffer::setMaxSize(size_t max_size) {
max_size_ = max_size;
}
void DefragmentText::Buffer::flushAndReplace(core::ProcessSession* session, const core::Relationship& relationship,
const std::shared_ptr<core::FlowFile>& new_buffered_flow_file) {
if (!empty()) {
session->add(buffered_flow_file_);
session->transfer(buffered_flow_file_, relationship);
}
store(session, new_buffered_flow_file);
}
void DefragmentText::Buffer::store(core::ProcessSession* session, const std::shared_ptr<core::FlowFile>& new_buffered_flow_file) {
buffered_flow_file_ = new_buffered_flow_file;
creation_time_ = std::chrono::steady_clock::now();
if (!empty()) {
session->add(buffered_flow_file_);
session->transfer(buffered_flow_file_, Self);
}
}
bool DefragmentText::Buffer::isCompatible(const core::FlowFile& fragment) const {
if (empty())
return true;
if (buffered_flow_file_->getAttribute(textfragmentutils::BASE_NAME_ATTRIBUTE)
!= fragment.getAttribute(textfragmentutils::BASE_NAME_ATTRIBUTE)) {
return false;
}
if (buffered_flow_file_->getAttribute(textfragmentutils::POST_NAME_ATTRIBUTE)
!= fragment.getAttribute(textfragmentutils::POST_NAME_ATTRIBUTE)) {
return false;
}
std::string current_offset_str, append_offset_str;
if (buffered_flow_file_->getAttribute(textfragmentutils::OFFSET_ATTRIBUTE, current_offset_str)
!= fragment.getAttribute(textfragmentutils::OFFSET_ATTRIBUTE, append_offset_str)) {
return false;
}
if (!current_offset_str.empty() && !append_offset_str.empty()) {
size_t current_offset = std::stoi(current_offset_str);
size_t append_offset = std::stoi(append_offset_str);
if (current_offset + buffered_flow_file_->getSize() != append_offset)
return false;
}
return true;
}
REGISTER_RESOURCE(DefragmentText, "DefragmentText splits and merges incoming flowfiles so cohesive messages are not split between them");
} // namespace org::apache::nifi::minifi::processors
<commit_msg>MINIFICPP-1681 DefragmentText should trigger when empty if Maximum Buffer Age is set<commit_after>/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "DefragmentText.h"
#include <vector>
#include <utility>
#include "core/Resource.h"
#include "serialization/PayloadSerializer.h"
#include "TextFragmentUtils.h"
#include "utils/gsl.h"
#include "utils/StringUtils.h"
namespace org::apache::nifi::minifi::processors {
const core::Relationship DefragmentText::Success("success", "Flowfiles that have been successfully defragmented");
const core::Relationship DefragmentText::Failure("failure", "Flowfiles that failed the defragmentation process");
const core::Relationship DefragmentText::Self("__self__", "Marks the FlowFile to be owned by this processor");
const core::Property DefragmentText::Pattern(
core::PropertyBuilder::createProperty("Pattern")
->withDescription("A regular expression to match at the start or end of messages.")
->isRequired(true)->build());
const core::Property DefragmentText::PatternLoc(
core::PropertyBuilder::createProperty("Pattern Location")->withDescription("Whether the pattern is located at the start or at the end of the messages.")
->withAllowableValues(PatternLocation::values())
->withDefaultValue(toString(PatternLocation::START_OF_MESSAGE))->build());
const core::Property DefragmentText::MaxBufferSize(
core::PropertyBuilder::createProperty("Max Buffer Size")
->withDescription("The maximum buffer size, if the buffer exceeds this, it will be transferred to failure. Expected format is <size> <data unit>")
->withType(core::StandardValidators::get().DATA_SIZE_VALIDATOR)->build());
const core::Property DefragmentText::MaxBufferAge(
core::PropertyBuilder::createProperty("Max Buffer Age")->
withDescription("The maximum age of the buffer after which it will be transferred to success when matching Start of Message patterns or to failure when matching End of Message patterns. "
"Expected format is <duration> <time unit>")
->withDefaultValue("10 min")
->build());
void DefragmentText::initialize() {
setSupportedRelationships({Success, Failure});
setSupportedProperties({Pattern, PatternLoc, MaxBufferAge, MaxBufferSize});
}
void DefragmentText::onSchedule(core::ProcessContext* context, core::ProcessSessionFactory*) {
gsl_Expects(context);
std::string max_buffer_age_str;
if (context->getProperty(MaxBufferAge.getName(), max_buffer_age_str)) {
core::TimeUnit unit;
uint64_t max_buffer_age;
if (core::Property::StringToTime(max_buffer_age_str, max_buffer_age, unit) && core::Property::ConvertTimeUnitToMS(max_buffer_age, unit, max_buffer_age)) {
buffer_.setMaxAge(std::chrono::milliseconds(max_buffer_age));
setTriggerWhenEmpty(true);
logger_->log_trace("The Buffer maximum age is configured to be %" PRIu64 " ms", max_buffer_age);
}
}
std::string max_buffer_size_str;
if (context->getProperty(MaxBufferSize.getName(), max_buffer_size_str)) {
uint64_t max_buffer_size = core::DataSizeValue(max_buffer_size_str).getValue();
if (max_buffer_size > 0) {
buffer_.setMaxSize(max_buffer_size);
logger_->log_trace("The Buffer maximum size is configured to be %" PRIu64 " B", max_buffer_size);
}
}
context->getProperty(PatternLoc.getName(), pattern_location_);
std::string pattern_str;
if (context->getProperty(Pattern.getName(), pattern_str) && !pattern_str.empty()) {
pattern_ = std::regex(pattern_str);
logger_->log_trace("The Pattern is configured to be %s", pattern_str);
} else {
throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Pattern property missing or invalid");
}
}
void DefragmentText::onTrigger(core::ProcessContext*, core::ProcessSession* session) {
gsl_Expects(session);
auto flowFiles = flow_file_store_.getNewFlowFiles();
for (auto& file : flowFiles) {
if (file)
processNextFragment(session, gsl::not_null(std::move(file)));
}
{
std::shared_ptr<core::FlowFile> original_flow_file = session->get();
if (original_flow_file)
processNextFragment(session, gsl::not_null(std::move(original_flow_file)));
}
if (buffer_.maxSizeReached()) {
buffer_.flushAndReplace(session, Failure, nullptr);
return;
}
if (buffer_.maxAgeReached()) {
if (pattern_location_ == PatternLocation::START_OF_MESSAGE)
buffer_.flushAndReplace(session, Success, nullptr);
else
buffer_.flushAndReplace(session, Failure, nullptr);
}
}
void DefragmentText::processNextFragment(core::ProcessSession *session, const gsl::not_null<std::shared_ptr<core::FlowFile>>& next_fragment) {
if (!buffer_.isCompatible(*next_fragment)) {
buffer_.flushAndReplace(session, Failure, nullptr);
session->transfer(next_fragment, Failure);
return;
}
std::shared_ptr<core::FlowFile> split_before_last_pattern;
std::shared_ptr<core::FlowFile> split_after_last_pattern;
bool found_pattern = splitFlowFileAtLastPattern(session, next_fragment, split_before_last_pattern,
split_after_last_pattern);
if (split_before_last_pattern)
buffer_.append(session, gsl::not_null(std::move(split_before_last_pattern)));
if (found_pattern) {
buffer_.flushAndReplace(session, Success, split_after_last_pattern);
}
session->remove(next_fragment);
}
void DefragmentText::updateAttributesForSplitFiles(const core::FlowFile& original_flow_file,
const std::shared_ptr<core::FlowFile>& split_before_last_pattern,
const std::shared_ptr<core::FlowFile>& split_after_last_pattern,
const size_t split_position) const {
std::string base_name, post_name, offset_str;
if (!original_flow_file.getAttribute(textfragmentutils::BASE_NAME_ATTRIBUTE, base_name))
return;
if (!original_flow_file.getAttribute(textfragmentutils::POST_NAME_ATTRIBUTE, post_name))
return;
if (!original_flow_file.getAttribute(textfragmentutils::OFFSET_ATTRIBUTE, offset_str))
return;
size_t fragment_offset = std::stoi(offset_str);
if (split_before_last_pattern) {
std::string first_part_name = textfragmentutils::createFileName(base_name, post_name, fragment_offset, split_before_last_pattern->getSize());
split_before_last_pattern->setAttribute(core::SpecialFlowAttribute::FILENAME, first_part_name);
}
if (split_after_last_pattern) {
std::string second_part_name = textfragmentutils::createFileName(base_name, post_name, fragment_offset + split_position, split_after_last_pattern->getSize());
split_after_last_pattern->setAttribute(core::SpecialFlowAttribute::FILENAME, second_part_name);
split_after_last_pattern->setAttribute(textfragmentutils::OFFSET_ATTRIBUTE, std::to_string(fragment_offset + split_position));
}
}
namespace {
class AppendFlowFileToFlowFile : public OutputStreamCallback {
public:
explicit AppendFlowFileToFlowFile(const gsl::not_null<std::shared_ptr<core::FlowFile>>& flow_file_to_append, PayloadSerializer& serializer)
: flow_file_to_append_(flow_file_to_append), serializer_(serializer) {}
int64_t process(const std::shared_ptr<io::BaseStream> &stream) override {
return serializer_.serialize(flow_file_to_append_, stream);
}
private:
const gsl::not_null<std::shared_ptr<core::FlowFile>>& flow_file_to_append_;
PayloadSerializer& serializer_;
};
void updateAppendedAttributes(core::FlowFile& buffered_ff) {
std::string base_name, post_name, offset_str;
if (!buffered_ff.getAttribute(textfragmentutils::BASE_NAME_ATTRIBUTE, base_name))
return;
if (!buffered_ff.getAttribute(textfragmentutils::POST_NAME_ATTRIBUTE, post_name))
return;
if (!buffered_ff.getAttribute(textfragmentutils::OFFSET_ATTRIBUTE, offset_str))
return;
size_t fragment_offset = std::stoi(offset_str);
std::string buffer_new_name = textfragmentutils::createFileName(base_name, post_name, fragment_offset, buffered_ff.getSize());
buffered_ff.setAttribute(core::SpecialFlowAttribute::FILENAME, buffer_new_name);
}
struct ReadFlowFileContent : public InputStreamCallback {
std::string content;
int64_t process(const std::shared_ptr<io::BaseStream> &stream) override {
content.resize(stream->size());
const auto ret = stream->read(reinterpret_cast<uint8_t *>(content.data()), stream->size());
if (io::isError(ret))
return -1;
return gsl::narrow<int64_t>(ret);
}
};
size_t getSplitPosition(const std::smatch& last_match, DefragmentText::PatternLocation pattern_location) {
size_t split_position = last_match.position(0);
if (pattern_location == DefragmentText::PatternLocation::END_OF_MESSAGE) {
split_position += last_match.length(0);
}
return split_position;
}
} // namespace
bool DefragmentText::splitFlowFileAtLastPattern(core::ProcessSession *session,
const gsl::not_null<std::shared_ptr<core::FlowFile>> &original_flow_file,
std::shared_ptr<core::FlowFile> &split_before_last_pattern,
std::shared_ptr<core::FlowFile> &split_after_last_pattern) const {
ReadFlowFileContent read_flow_file_content;
session->read(original_flow_file, &read_flow_file_content);
auto last_regex_match = utils::StringUtils::getLastRegexMatch(read_flow_file_content.content, pattern_);
if (!last_regex_match.ready()) {
split_before_last_pattern = session->clone(original_flow_file);
split_after_last_pattern = nullptr;
return false;
}
auto split_position = getSplitPosition(last_regex_match, pattern_location_);
if (split_position != 0) {
split_before_last_pattern = session->clone(original_flow_file, 0, split_position);
}
if (split_position != original_flow_file->getSize()) {
split_after_last_pattern = session->clone(original_flow_file, split_position, original_flow_file->getSize() - split_position);
}
updateAttributesForSplitFiles(*original_flow_file, split_before_last_pattern, split_after_last_pattern, split_position);
return true;
}
void DefragmentText::restore(const std::shared_ptr<core::FlowFile>& flowFile) {
if (!flowFile)
return;
flow_file_store_.put(flowFile);
}
std::set<std::shared_ptr<core::Connectable>> DefragmentText::getOutGoingConnections(const std::string &relationship) const {
auto result = core::Connectable::getOutGoingConnections(relationship);
if (relationship == Self.getName()) {
result.insert(std::static_pointer_cast<core::Connectable>(std::const_pointer_cast<core::Processor>(shared_from_this())));
}
return result;
}
void DefragmentText::Buffer::append(core::ProcessSession* session, const gsl::not_null<std::shared_ptr<core::FlowFile>>& flow_file_to_append) {
if (empty()) {
store(session, flow_file_to_append);
return;
}
auto flowFileReader = [&] (const std::shared_ptr<core::FlowFile>& ff, InputStreamCallback* cb) {
return session->read(ff, cb);
};
PayloadSerializer serializer(flowFileReader);
AppendFlowFileToFlowFile append_flow_file_to_flow_file(flow_file_to_append, serializer);
session->add(buffered_flow_file_);
session->append(buffered_flow_file_, &append_flow_file_to_flow_file);
updateAppendedAttributes(*buffered_flow_file_);
session->transfer(buffered_flow_file_, Self);
session->remove(flow_file_to_append);
}
bool DefragmentText::Buffer::maxSizeReached() const {
return !empty()
&& max_size_.has_value()
&& (max_size_.value() < buffered_flow_file_->getSize());
}
bool DefragmentText::Buffer::maxAgeReached() const {
return !empty()
&& max_age_.has_value()
&& (creation_time_ + max_age_.value() < std::chrono::steady_clock::now());
}
void DefragmentText::Buffer::setMaxAge(std::chrono::milliseconds max_age) {
max_age_ = max_age;
}
void DefragmentText::Buffer::setMaxSize(size_t max_size) {
max_size_ = max_size;
}
void DefragmentText::Buffer::flushAndReplace(core::ProcessSession* session, const core::Relationship& relationship,
const std::shared_ptr<core::FlowFile>& new_buffered_flow_file) {
if (!empty()) {
session->add(buffered_flow_file_);
session->transfer(buffered_flow_file_, relationship);
}
store(session, new_buffered_flow_file);
}
void DefragmentText::Buffer::store(core::ProcessSession* session, const std::shared_ptr<core::FlowFile>& new_buffered_flow_file) {
buffered_flow_file_ = new_buffered_flow_file;
creation_time_ = std::chrono::steady_clock::now();
if (!empty()) {
session->add(buffered_flow_file_);
session->transfer(buffered_flow_file_, Self);
}
}
bool DefragmentText::Buffer::isCompatible(const core::FlowFile& fragment) const {
if (empty())
return true;
if (buffered_flow_file_->getAttribute(textfragmentutils::BASE_NAME_ATTRIBUTE)
!= fragment.getAttribute(textfragmentutils::BASE_NAME_ATTRIBUTE)) {
return false;
}
if (buffered_flow_file_->getAttribute(textfragmentutils::POST_NAME_ATTRIBUTE)
!= fragment.getAttribute(textfragmentutils::POST_NAME_ATTRIBUTE)) {
return false;
}
std::string current_offset_str, append_offset_str;
if (buffered_flow_file_->getAttribute(textfragmentutils::OFFSET_ATTRIBUTE, current_offset_str)
!= fragment.getAttribute(textfragmentutils::OFFSET_ATTRIBUTE, append_offset_str)) {
return false;
}
if (!current_offset_str.empty() && !append_offset_str.empty()) {
size_t current_offset = std::stoi(current_offset_str);
size_t append_offset = std::stoi(append_offset_str);
if (current_offset + buffered_flow_file_->getSize() != append_offset)
return false;
}
return true;
}
REGISTER_RESOURCE(DefragmentText, "DefragmentText splits and merges incoming flowfiles so cohesive messages are not split between them");
} // namespace org::apache::nifi::minifi::processors
<|endoftext|>
|
<commit_before>#include <plasp/pddl/TranslatorASP.h>
#include <plasp/utils/TranslatorException.h>
namespace plasp
{
namespace pddl
{
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// TranslatorASP
//
////////////////////////////////////////////////////////////////////////////////////////////////////
TranslatorASP::TranslatorASP(const Description &description)
: m_description(description)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void TranslatorASP::translate(std::ostream &ostream) const
{
translateDomain(ostream);
if (m_description.containsProblem())
translateProblem(ostream);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void TranslatorASP::translateDomain(std::ostream &ostream) const
{
ostream
<< "%---------------------------------------" << std::endl
<< "% domain" << std::endl
<< "%---------------------------------------" << std::endl << std::endl;
const auto &domain = m_description.domain();
// Types
ostream << "% types";
const auto &types = domain.types();
std::for_each(types.cbegin(), types.cend(),
[&](const auto &type)
{
ostream << std::endl;
ostream << "type(" << type->name() << ")." << std::endl;
const auto &parentTypes = type->parentTypes();
std::for_each(parentTypes.cbegin(), parentTypes.cend(),
[&](const auto &parentType)
{
ostream << "inherits(type(" << type->name() << "), type(" << parentType->name() << "))." << std::endl;
});
});
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void TranslatorASP::translateProblem(std::ostream &ostream) const
{
ostream << std::endl
<< "%---------------------------------------" << std::endl
<< "% problem" << std::endl
<< "%---------------------------------------" << std::endl << std::endl;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
<commit_msg>Implemented translation of PDDL domain constants.<commit_after>#include <plasp/pddl/TranslatorASP.h>
#include <plasp/utils/TranslatorException.h>
namespace plasp
{
namespace pddl
{
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// TranslatorASP
//
////////////////////////////////////////////////////////////////////////////////////////////////////
TranslatorASP::TranslatorASP(const Description &description)
: m_description(description)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void TranslatorASP::translate(std::ostream &ostream) const
{
translateDomain(ostream);
if (m_description.containsProblem())
translateProblem(ostream);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void TranslatorASP::translateDomain(std::ostream &ostream) const
{
ostream
<< "%---------------------------------------" << std::endl
<< "% domain" << std::endl
<< "%---------------------------------------" << std::endl;
const auto &domain = m_description.domain();
// Types
ostream << std::endl;
ostream << "% types";
const auto &types = domain.types();
std::for_each(types.cbegin(), types.cend(),
[&](const auto &type)
{
ostream << std::endl;
ostream << "type(" << type->name() << ")." << std::endl;
const auto &parentTypes = type->parentTypes();
std::for_each(parentTypes.cbegin(), parentTypes.cend(),
[&](const auto &parentType)
{
ostream << "inherits(type(" << type->name() << "), type(" << parentType->name() << "))." << std::endl;
});
});
// Constants
ostream << std::endl;
ostream << "% constants";
const auto &constants = domain.constants();
std::for_each(constants.cbegin(), constants.cend(),
[&](const auto &constant)
{
ostream << std::endl;
ostream << "constant(" << constant->name() << ")." << std::endl;
const auto *type = constant->type();
if (type == nullptr)
return;
ostream << "hasType(constant(" << constant->name() << "), type(" << type->name() << "))." << std::endl;
});
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void TranslatorASP::translateProblem(std::ostream &ostream) const
{
ostream << std::endl
<< "%---------------------------------------" << std::endl
<< "% problem" << std::endl
<< "%---------------------------------------" << std::endl;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id$
/////////////////////////////////////////////////////////////////////////
//
// Copyright 2003 by David N. Welton <davidw@dedasys.com>.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// 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
#define BX_PLUGGABLE
#include "iodev.h"
#include "speaker.h"
#ifdef __linux__
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/kd.h>
#endif
#define LOG_THIS theSpeaker->
bx_speaker_c *theSpeaker= NULL;
int
libspeaker_LTX_plugin_init(plugin_t *plugin, plugintype_t type, int argc, char *argv[])
{
theSpeaker = new bx_speaker_c ();
bx_devices.pluginSpeaker = theSpeaker;
BX_REGISTER_DEVICE_DEVMODEL(plugin, type, theSpeaker, BX_PLUGIN_SPEAKER);
return(0); // Success
}
void
libspeaker_LTX_plugin_fini(void)
{
}
bx_speaker_c::bx_speaker_c() {
put("SPEAKER");
settype(SPEAKERLOG);
beep_frequency = 0.0; // Off
#ifdef __linux__
consolefd = open("/dev/console", O_WRONLY);
#endif
}
bx_speaker_c::~bx_speaker_c() {
#ifdef __linux__
if (consolefd) {
ioctl(consolefd, KIOCSOUND, 0);
close(consolefd);
}
#endif
}
void
bx_speaker_c::init(void)
{
#ifdef __linux__
if (consolefd != -1) {
BX_INFO(("Open /dev/console successfully"));
} else {
BX_INFO(("Failed to open /dev/console: %s", strerror(errno)));
BX_INFO(("Deactivating beep on console"));
}
#endif
this->beep_off();
}
void
bx_speaker_c::reset(unsigned type)
{
beep_off();
}
void bx_speaker_c::beep_on(float frequency)
{
beep_frequency = frequency;
#ifdef __linux__
if (consolefd != -1) {
this->info("pc speaker on with frequency %f", frequency);
ioctl(consolefd, KIOCSOUND, (int)(clock_tick_rate/frequency));
}
#elif defined(WIN32)
usec_start = bx_pc_system.time_usec();
#endif
// give the gui a chance to signal beep off
bx_gui->beep_on(frequency);
}
#if defined(WIN32)
struct {
DWORD frequency;
DWORD msec;
} beep_info;
DWORD WINAPI BeepThread(LPVOID)
{
static BOOL threadActive = FALSE;
while (threadActive) Sleep(10);
threadActive = TRUE;
Beep(beep_info.frequency, beep_info.msec);
threadActive = FALSE;
}
#endif
void bx_speaker_c::beep_off()
{
if (beep_frequency != 0.0) {
#ifdef __linux__
if (consolefd != -1) {
ioctl(consolefd, KIOCSOUND, 0);
}
#elif defined(WIN32)
// FIXME: sound should start at beep_on() and end here
DWORD threadID;
beep_info.msec = (DWORD)((bx_pc_system.time_usec() - usec_start) / 1000);
beep_info.frequency = (DWORD)beep_frequency;
CreateThread(NULL, 0, BeepThread, NULL, 0, &threadID);
#endif
// give the gui a chance to signal beep off
bx_gui->beep_off();
beep_frequency = 0.0;
}
}
<commit_msg>- missing return value added<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id$
/////////////////////////////////////////////////////////////////////////
//
// Copyright 2003 by David N. Welton <davidw@dedasys.com>.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// 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
#define BX_PLUGGABLE
#include "iodev.h"
#include "speaker.h"
#ifdef __linux__
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/kd.h>
#endif
#define LOG_THIS theSpeaker->
bx_speaker_c *theSpeaker= NULL;
int
libspeaker_LTX_plugin_init(plugin_t *plugin, plugintype_t type, int argc, char *argv[])
{
theSpeaker = new bx_speaker_c ();
bx_devices.pluginSpeaker = theSpeaker;
BX_REGISTER_DEVICE_DEVMODEL(plugin, type, theSpeaker, BX_PLUGIN_SPEAKER);
return(0); // Success
}
void
libspeaker_LTX_plugin_fini(void)
{
}
bx_speaker_c::bx_speaker_c() {
put("SPEAKER");
settype(SPEAKERLOG);
beep_frequency = 0.0; // Off
#ifdef __linux__
consolefd = open("/dev/console", O_WRONLY);
#endif
}
bx_speaker_c::~bx_speaker_c() {
#ifdef __linux__
if (consolefd) {
ioctl(consolefd, KIOCSOUND, 0);
close(consolefd);
}
#endif
}
void
bx_speaker_c::init(void)
{
#ifdef __linux__
if (consolefd != -1) {
BX_INFO(("Open /dev/console successfully"));
} else {
BX_INFO(("Failed to open /dev/console: %s", strerror(errno)));
BX_INFO(("Deactivating beep on console"));
}
#endif
this->beep_off();
}
void
bx_speaker_c::reset(unsigned type)
{
beep_off();
}
void bx_speaker_c::beep_on(float frequency)
{
beep_frequency = frequency;
#ifdef __linux__
if (consolefd != -1) {
this->info("pc speaker on with frequency %f", frequency);
ioctl(consolefd, KIOCSOUND, (int)(clock_tick_rate/frequency));
}
#elif defined(WIN32)
usec_start = bx_pc_system.time_usec();
#endif
// give the gui a chance to signal beep off
bx_gui->beep_on(frequency);
}
#if defined(WIN32)
struct {
DWORD frequency;
DWORD msec;
} beep_info;
DWORD WINAPI BeepThread(LPVOID)
{
static BOOL threadActive = FALSE;
while (threadActive) Sleep(10);
threadActive = TRUE;
Beep(beep_info.frequency, beep_info.msec);
threadActive = FALSE;
return 0;
}
#endif
void bx_speaker_c::beep_off()
{
if (beep_frequency != 0.0) {
#ifdef __linux__
if (consolefd != -1) {
ioctl(consolefd, KIOCSOUND, 0);
}
#elif defined(WIN32)
// FIXME: sound should start at beep_on() and end here
DWORD threadID;
beep_info.msec = (DWORD)((bx_pc_system.time_usec() - usec_start) / 1000);
beep_info.frequency = (DWORD)beep_frequency;
CreateThread(NULL, 0, BeepThread, NULL, 0, &threadID);
#endif
// give the gui a chance to signal beep off
bx_gui->beep_off();
beep_frequency = 0.0;
}
}
<|endoftext|>
|
<commit_before>/* Begin CVS Header
$Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/stochastic-testsuite/copasi_wrapper.cpp,v $
$Revision: 1.3 $
$Name: $
$Author: gauges $
$Date: 2006/04/24 14:18:25 $
End CVS Header */
#define COPASI_MAIN
#include <iostream>
#include <stdlib.h>
#include "copasi.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiContainer.h"
#include "model/CMetab.h"
#include "report/CCopasiObjectName.h"
#include "utilities/CCopasiVector.h"
#include "model/CModel.h"
#include "utilities/CCopasiException.h"
#include "commandline/COptionParser.h"
#include "commandline/COptions.h"
#include "trajectory/CTrajectoryTask.h"
#include "trajectory/CTrajectoryMethod.h"
#include "trajectory/CTrajectoryProblem.h"
#include "report/CReportDefinitionVector.h"
#include "report/CReportDefinition.h"
#include "scan/CScanTask.h"
#include "scan/CScanProblem.h"
int main(int argc, char *argv[])
{
// Parse the commandline options
// first argument is the SBML filename
// second argument is the endtime
// third argument is the step number
// fourth argument is the filename where the results are to be written
// fifth argument is the tmp directory (this is not needed)
// the rest of the arguments are species names for the result
try
{
// Parse the commandline options
COptions::init(argc, argv);
}
catch (copasi::autoexcept &e)
{}
catch (copasi::option_error &e)
{}
if (argc < 5)
{
std::cout << "Usage: stochastic-testsuite SBMLFILENAME ENDTIME STEPNUMBER REPEATS OUTFILENAME SPECIESID1 SPECIESID2 ..." << std::endl;
exit(1);
}
char* pSBMLFilename = argv[1];
char* pEndTime = argv[2];
char* pStepNumber = argv[3];
char* pRepeats = argv[4];
char* pOutputFilename = argv[5];
unsigned int NUMARGS = 6;
/*
std::cout << "Input : " << pSBMLFilename << std::endl;
std::cout << "Endtime : " << pEndTime << std::endl;
std::cout << "Stepnumber: " << pStepNumber << std::endl;
std::cout << "Repeats : " << pRepeats << std::endl;
std::cout << "Output file: " << pOutputFilename << std::endl;
*/
char** pSBMLSpeciesIds = new char * [argc - NUMARGS];
unsigned int i, iMax = argc;
CTrajectoryTask* pTrajectoryTask = NULL;
CScanTask* pScanTask = NULL;
std::string CWD = COptions::getPWD();
double endTime = strtod(pEndTime, &pEndTime);
double stepNumber = strtod(pStepNumber, &pStepNumber);
long int repeats = strtol(pRepeats, &pRepeats , 10);
if (endTime == 0.0)
{
std::cerr << "Invalid endtime " << pEndTime << std::endl;
exit(1);
}
if (stepNumber == 0.0)
{
std::cerr << "Invalid step number " << pStepNumber << std::endl;
exit(1);
}
for (i = NUMARGS; i < iMax;++i)
{
pSBMLSpeciesIds[i - NUMARGS] = argv[i];
//std::cout << "Copying pointer to " << argv[i] << "." << std::endl;
}
try
{
// Create the root container.
CCopasiContainer::init();
// Create the global data model.
CCopasiDataModel::Global = new CCopasiDataModel;
// Import the SBML File
CCopasiDataModel::Global->importSBML(pSBMLFilename);
//CCopasiDataModel::Global->getModel()->forceCompile();
// create a report with the correct filename and all the species against
// time.
CReportDefinitionVector* pReports = CCopasiDataModel::Global->getReportDefinitionList();
CReportDefinition* pReport = pReports->createReportDefinition("Report", "Output for stochastic testsuite run");
pReport->setTaskType(CCopasiTask::timeCourse);
pReport->setIsTable(true);
std::vector<CRegisteredObjectName>* pTable = pReport->getTableAddr();
pTable->push_back(CCopasiObjectName(CCopasiDataModel::Global->getModel()->getCN() + ",Reference=Time"));
iMax = iMax - NUMARGS;
const CCopasiVector<CMetab>& metabolites = CCopasiDataModel::Global->getModel()->getMetabolites();
for (i = 0; i < iMax;++i)
{
unsigned int j, jMax = metabolites.size();
for (j = 0; j < jMax;++j)
{
if (metabolites[j]->getSBMLId() == pSBMLSpeciesIds[i])
{
pTable->push_back(metabolites[j]->getObject(CCopasiObjectName("Reference=ParticleNumber"))->getCN());
//std::cout << "adding metabolite " << metabolites[j]->getObjectName() << " to report." << std::endl;
break;
}
}
if (j == jMax)
{
std::cerr << "Could not find a metabolite for the SBML id \"" << pSBMLSpeciesIds[i] << "\"" << std::endl;
exit(1);
}
}
// create a trajectory task
pTrajectoryTask = new CTrajectoryTask();
pTrajectoryTask->setMethodType(CCopasiMethod::stochastic);
pTrajectoryTask->getProblem()->setModel(CCopasiDataModel::Global->getModel());
pTrajectoryTask->setScheduled(false);
//pTrajectoryTask->getReport().setReportDefinition(pReport);
//pTrajectoryTask->getReport().setTarget(CWD + "/" + pOutputFilename);
//pTrajectoryTask->getReport().setAppend(false);
CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem*>(pTrajectoryTask->getProblem());
pProblem->setStepNumber((const unsigned C_INT32)stepNumber);
pProblem->setDuration((const C_FLOAT64)endTime);
pProblem->setTimeSeriesRequested(true);
//pProblem->setInitialState(CCopasiDataModel::Global->getModel()->getInitialState());
CStochMethod* pMethod = dynamic_cast<CStochMethod*>(pTrajectoryTask->getMethod());
pMethod->getParameter("STOCH.UseRandomSeed")->setValue(false);
CCopasiVectorN< CCopasiTask > & TaskList = * CCopasiDataModel::Global->getTaskList();
TaskList.remove("Time-Course");
TaskList.add(pTrajectoryTask, true);
// create a scan task
pScanTask = new CScanTask();
CScanProblem* pScanProblem = dynamic_cast<CScanProblem*>(pScanTask->getProblem());
pScanProblem->setModel(CCopasiDataModel::Global->getModel());
pScanTask->setScheduled(true);
pScanTask->getReport().setReportDefinition(pReport);
pScanTask->getReport().setTarget(CWD + "/" + pOutputFilename);
pScanTask->getReport().setAppend(false);
pScanProblem->setSubtask(CCopasiTask::timeCourse);
pScanProblem->createScanItem(CScanProblem::SCAN_REPEAT, repeats);
pScanProblem->setOutputInSubtask(true);
pScanProblem->setAdjustInitialConditions(false);
TaskList.remove("Scan");
TaskList.add(pScanTask, true);
// save the file for control purposes
std::string saveFilename = pSBMLFilename;
saveFilename = saveFilename.substr(0, saveFilename.length() - 4) + ".cps";
CCopasiDataModel::Global->saveModel(saveFilename, true);
// Run the trajectory task
pScanTask->initialize(CCopasiTask::OUTPUT_COMPLETE, NULL);
pScanTask->process(true);
pScanTask->restore();
// create another report that will write to the directory where the input file came from
// this can be used for debugging
// create a trajectory task
pScanTask->getReport().setTarget(pOutputFilename);
pScanTask->initialize(CCopasiTask::OUTPUT_COMPLETE, NULL);
pScanTask->process(true);
pScanTask->restore();
}
catch (CCopasiException Exception)
{
std::cerr << Exception.getMessage().getText() << std::endl;
}
pdelete(CCopasiDataModel::Global);
pdelete(CCopasiContainer::Root);
return 0;
}
<commit_msg>Fixed compilation error.<commit_after>/* Begin CVS Header
$Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/stochastic-testsuite/copasi_wrapper.cpp,v $
$Revision: 1.4 $
$Name: $
$Author: shoops $
$Date: 2006/05/09 12:13:51 $
End CVS Header */
// Copyright 2005 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#define COPASI_MAIN
#include <iostream>
#include <stdlib.h>
#include "copasi.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiContainer.h"
#include "model/CMetab.h"
#include "report/CCopasiObjectName.h"
#include "utilities/CCopasiVector.h"
#include "model/CModel.h"
#include "utilities/CCopasiException.h"
#include "commandline/COptionParser.h"
#include "commandline/COptions.h"
#include "trajectory/CTrajectoryTask.h"
#include "trajectory/CTrajectoryMethod.h"
#include "trajectory/CTrajectoryProblem.h"
#include "report/CReportDefinitionVector.h"
#include "report/CReportDefinition.h"
#include "scan/CScanTask.h"
#include "scan/CScanProblem.h"
int main(int argc, char *argv[])
{
// Parse the commandline options
// first argument is the SBML filename
// second argument is the endtime
// third argument is the step number
// fourth argument is the filename where the results are to be written
// fifth argument is the tmp directory (this is not needed)
// the rest of the arguments are species names for the result
try
{
// Parse the commandline options
COptions::init(argc, argv);
}
catch (copasi::autoexcept &e)
{}
catch (copasi::option_error &e)
{}
if (argc < 5)
{
std::cout << "Usage: stochastic-testsuite SBMLFILENAME ENDTIME STEPNUMBER REPEATS OUTFILENAME SPECIESID1 SPECIESID2 ..." << std::endl;
exit(1);
}
char* pSBMLFilename = argv[1];
char* pEndTime = argv[2];
char* pStepNumber = argv[3];
char* pRepeats = argv[4];
char* pOutputFilename = argv[5];
unsigned int NUMARGS = 6;
/*
std::cout << "Input : " << pSBMLFilename << std::endl;
std::cout << "Endtime : " << pEndTime << std::endl;
std::cout << "Stepnumber: " << pStepNumber << std::endl;
std::cout << "Repeats : " << pRepeats << std::endl;
std::cout << "Output file: " << pOutputFilename << std::endl;
*/
char** pSBMLSpeciesIds = new char * [argc - NUMARGS];
unsigned int i, iMax = argc;
CTrajectoryTask* pTrajectoryTask = NULL;
CScanTask* pScanTask = NULL;
std::string CWD = COptions::getPWD();
double endTime = strtod(pEndTime, &pEndTime);
double stepNumber = strtod(pStepNumber, &pStepNumber);
long int repeats = strtol(pRepeats, &pRepeats , 10);
if (endTime == 0.0)
{
std::cerr << "Invalid endtime " << pEndTime << std::endl;
exit(1);
}
if (stepNumber == 0.0)
{
std::cerr << "Invalid step number " << pStepNumber << std::endl;
exit(1);
}
for (i = NUMARGS; i < iMax;++i)
{
pSBMLSpeciesIds[i - NUMARGS] = argv[i];
//std::cout << "Copying pointer to " << argv[i] << "." << std::endl;
}
try
{
// Create the root container.
CCopasiContainer::init();
// Create the global data model.
CCopasiDataModel::Global = new CCopasiDataModel;
// Import the SBML File
CCopasiDataModel::Global->importSBML(pSBMLFilename);
//CCopasiDataModel::Global->getModel()->forceCompile();
// create a report with the correct filename and all the species against
// time.
CReportDefinitionVector* pReports = CCopasiDataModel::Global->getReportDefinitionList();
CReportDefinition* pReport = pReports->createReportDefinition("Report", "Output for stochastic testsuite run");
pReport->setTaskType(CCopasiTask::timeCourse);
pReport->setIsTable(true);
std::vector<CRegisteredObjectName>* pTable = pReport->getTableAddr();
pTable->push_back(CCopasiObjectName(CCopasiDataModel::Global->getModel()->getCN() + ",Reference=Time"));
iMax = iMax - NUMARGS;
const CCopasiVector<CMetab>& metabolites = CCopasiDataModel::Global->getModel()->getMetabolites();
for (i = 0; i < iMax;++i)
{
unsigned int j, jMax = metabolites.size();
for (j = 0; j < jMax;++j)
{
if (metabolites[j]->getSBMLId() == pSBMLSpeciesIds[i])
{
pTable->push_back(metabolites[j]->getObject(CCopasiObjectName("Reference=ParticleNumber"))->getCN());
//std::cout << "adding metabolite " << metabolites[j]->getObjectName() << " to report." << std::endl;
break;
}
}
if (j == jMax)
{
std::cerr << "Could not find a metabolite for the SBML id \"" << pSBMLSpeciesIds[i] << "\"" << std::endl;
exit(1);
}
}
// create a trajectory task
pTrajectoryTask = new CTrajectoryTask();
pTrajectoryTask->setMethodType(CCopasiMethod::stochastic);
pTrajectoryTask->getProblem()->setModel(CCopasiDataModel::Global->getModel());
pTrajectoryTask->setScheduled(false);
//pTrajectoryTask->getReport().setReportDefinition(pReport);
//pTrajectoryTask->getReport().setTarget(CWD + "/" + pOutputFilename);
//pTrajectoryTask->getReport().setAppend(false);
CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem*>(pTrajectoryTask->getProblem());
pProblem->setStepNumber((const unsigned C_INT32)stepNumber);
pProblem->setDuration((const C_FLOAT64)endTime);
pProblem->setTimeSeriesRequested(true);
//pProblem->setInitialState(CCopasiDataModel::Global->getModel()->getInitialState());
CTrajectoryMethod* pMethod = dynamic_cast<CTrajectoryMethod*>(pTrajectoryTask->getMethod());
pMethod->getParameter("STOCH.UseRandomSeed")->setValue(false);
CCopasiVectorN< CCopasiTask > & TaskList = * CCopasiDataModel::Global->getTaskList();
TaskList.remove("Time-Course");
TaskList.add(pTrajectoryTask, true);
// create a scan task
pScanTask = new CScanTask();
CScanProblem* pScanProblem = dynamic_cast<CScanProblem*>(pScanTask->getProblem());
pScanProblem->setModel(CCopasiDataModel::Global->getModel());
pScanTask->setScheduled(true);
pScanTask->getReport().setReportDefinition(pReport);
pScanTask->getReport().setTarget(CWD + "/" + pOutputFilename);
pScanTask->getReport().setAppend(false);
pScanProblem->setSubtask(CCopasiTask::timeCourse);
pScanProblem->createScanItem(CScanProblem::SCAN_REPEAT, repeats);
pScanProblem->setOutputInSubtask(true);
pScanProblem->setAdjustInitialConditions(false);
TaskList.remove("Scan");
TaskList.add(pScanTask, true);
// save the file for control purposes
std::string saveFilename = pSBMLFilename;
saveFilename = saveFilename.substr(0, saveFilename.length() - 4) + ".cps";
CCopasiDataModel::Global->saveModel(saveFilename, true);
// Run the trajectory task
pScanTask->initialize(CCopasiTask::OUTPUT_COMPLETE, NULL);
pScanTask->process(true);
pScanTask->restore();
// create another report that will write to the directory where the input file came from
// this can be used for debugging
// create a trajectory task
pScanTask->getReport().setTarget(pOutputFilename);
pScanTask->initialize(CCopasiTask::OUTPUT_COMPLETE, NULL);
pScanTask->process(true);
pScanTask->restore();
}
catch (CCopasiException Exception)
{
std::cerr << Exception.getMessage().getText() << std::endl;
}
pdelete(CCopasiDataModel::Global);
pdelete(CCopasiContainer::Root);
return 0;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "ql2capserver.h"
#include "ql2capserver_p.h"
#include "qbluetoothsocket.h"
#include "qbluetoothsocket_p.h"
#include "symbian/utils_symbian_p.h"
#include <QTimer>
#include <QCoreApplication>
#include <QDebug>
QTM_BEGIN_NAMESPACE
QL2capServerPrivate::QL2capServerPrivate()
: socket(0),pending(false),maxPendingConnections(1),securityFlags(QBluetooth::NoSecurity)
{
}
QL2capServerPrivate::~QL2capServerPrivate()
{
delete socket;
}
void QL2capServer::close()
{
Q_D(QL2capServer);
if(!d->socket)
{
// there is no way to propagate the error to user
// so just ignore the problem.
return;
}
d->socket->setSocketState(QBluetoothSocket::ClosingState);
d->socket->close();
// force active object (socket) to run and shutdown socket.
qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
}
bool QL2capServer::listen(const QBluetoothAddress &address, quint16 port)
{
Q_D(QL2capServer);
// listen has already been called before
if(d->socket)
return true;
d->socket = new QBluetoothSocket(QBluetoothSocket::L2capSocket,this);
if(!d->socket)
{
return false;
}
d->ds = d->socket->d_ptr;
if(!d->ds)
{
delete d->socket;
d->socket = 0;
return false;
}
TL2CAPSockAddr addr;
if(!address.isNull())
{
// TBTDevAddr constructor may panic
TRAPD(err,addr.SetBTAddr(TBTDevAddr(address.toUInt64())));
if(err != KErrNone)
{
delete d->socket;
d->socket = 0;
return false;
}
}
if (port == 0)
addr.SetPort(KL2CAPPassiveAutoBind);
else
addr.SetPort(port);
TBTServiceSecurity security;
switch (d->securityFlags) {
case QBluetooth::Authentication:
security.SetAuthentication(EMitmDesired);
break;
case QBluetooth::Authorization:
security.SetAuthorisation(ETrue);
break;
case QBluetooth::Encryption:
// "Secure" is BlueZ specific we just make sure the code remain compatible
case QBluetooth::Secure:
// authentication required
security.SetAuthentication(EMitmDesired);
security.SetEncryption(ETrue);
break;
case QBluetooth::NoSecurity:
default:
break;
}
addr.SetSecurity(security);
if(d->ds->iSocket->Bind(addr) == KErrNone)
{
d->socket->setSocketState(QBluetoothSocket::BoundState);
}
else
{
delete d->socket;
d->socket = 0;
return false;
}
if(d->ds->iSocket->Listen(d->maxPendingConnections) != KErrNone)
{
delete d->socket;
d->socket = 0;
return false;
}
// unknown socket type is used for blank socket
QBluetoothSocket *pendingSocket = new QBluetoothSocket(QBluetoothSocket::UnknownSocketType, this);
if(!pendingSocket)
{
delete d->socket;
d->socket = 0;
return false;
}
QBluetoothSocketPrivate *pd = pendingSocket->d_ptr;
pd->ensureBlankNativeSocket(QBluetoothSocket::L2capSocket);
connect(d->socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
connect(d->socket, SIGNAL(connected()), this, SLOT(connected()));
connect(d->socket, SIGNAL(error(QBluetoothSocket::SocketError)), this, SLOT(socketError(QBluetoothSocket::SocketError)));
if (d->ds->iSocket->Accept(*pd->iSocket) == KErrNone)
{
d->socket->setSocketState(QBluetoothSocket::ListeningState);
d->activeSockets.append(pendingSocket);
return true;
}
else
{
delete d->socket, pendingSocket;
d->socket = 0;
return false;
}
}
void QL2capServer::setMaxPendingConnections(int numConnections)
{
Q_D(QL2capServer);
d->maxPendingConnections = numConnections;
}
bool QL2capServer::hasPendingConnections() const
{
Q_D(const QL2capServer);
return !d->activeSockets.isEmpty();
}
QBluetoothSocket *QL2capServer::nextPendingConnection()
{
Q_D(QL2capServer);
if (d->activeSockets.isEmpty())
return 0;
QBluetoothSocket *next = d->activeSockets.takeFirst();
return next;
}
QBluetoothAddress QL2capServer::serverAddress() const
{
Q_D(const QL2capServer);
if(d->socket)
return d->socket->localAddress();
else
return QBluetoothAddress();
}
quint16 QL2capServer::serverPort() const
{
Q_D(const QL2capServer);
if(d->socket)
return d->socket->localPort();
else
return 0;
}
void QL2capServer::connected()
{
Q_D(QL2capServer);
if(!d->activeSockets.isEmpty())
{
// update state of the pending socket and start receiving
(d->activeSockets.last())->setSocketState(QBluetoothSocket::ConnectedState);
(d->activeSockets.last())->d_ptr->startReceive();
}
else
return;
emit newConnection();
QBluetoothSocket *pendingSocket = new QBluetoothSocket(QBluetoothSocket::UnknownSocketType);
if(!pendingSocket)
{
delete d->socket;
d->socket = 0;
return;
}
QBluetoothSocketPrivate *pd = pendingSocket->d_ptr;
pd->ensureBlankNativeSocket(QBluetoothSocket::L2capSocket);
if (d->ds->iSocket->Accept(*pd->iSocket) == KErrNone)
{
d->socket->setSocketState(QBluetoothSocket::ListeningState);
d->activeSockets.append(pendingSocket);
return;
}
else
{
// we might reach this statement if we have reach
// maxPendingConnections
qDebug() << "QL2capServer::connected accept failed";
delete d->socket, pendingSocket;
d->socket = 0;
return;
}
}
void QL2capServer::disconnected()
{
qDebug() << __PRETTY_FUNCTION__ << aErr;
Q_D(QL2capServer);
delete d->socket;
d->socket = 0;
}
void QL2capServer::socketError(QBluetoothSocket::SocketError err)
{
if (aErr == KErrNone)
Q_D(QL2capServer);
delete d->socket;
d->socket = 0;
}
void QL2capServer::setSecurityFlags(QBluetooth::SecurityFlags security)
{
Q_D(QL2capServer);
d->securityFlags = security;
}
QBluetooth::SecurityFlags QL2capServer::securityFlags() const
{
Q_D(const QL2capServer);
return d->securityFlags;
}
QTM_END_NAMESPACE
<commit_msg>Fix merge error from symbian backend<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "ql2capserver.h"
#include "ql2capserver_p.h"
#include "qbluetoothsocket.h"
#include "qbluetoothsocket_p.h"
#include "symbian/utils_symbian_p.h"
#include <QTimer>
#include <QCoreApplication>
#include <QDebug>
QTM_BEGIN_NAMESPACE
QL2capServerPrivate::QL2capServerPrivate()
: socket(0),pending(false),maxPendingConnections(1),securityFlags(QBluetooth::NoSecurity)
{
}
QL2capServerPrivate::~QL2capServerPrivate()
{
delete socket;
}
void QL2capServer::close()
{
Q_D(QL2capServer);
if(!d->socket)
{
// there is no way to propagate the error to user
// so just ignore the problem.
return;
}
d->socket->setSocketState(QBluetoothSocket::ClosingState);
d->socket->close();
// force active object (socket) to run and shutdown socket.
qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
}
bool QL2capServer::listen(const QBluetoothAddress &address, quint16 port)
{
Q_D(QL2capServer);
// listen has already been called before
if(d->socket)
return true;
d->socket = new QBluetoothSocket(QBluetoothSocket::L2capSocket,this);
if(!d->socket)
{
return false;
}
d->ds = d->socket->d_ptr;
if(!d->ds)
{
delete d->socket;
d->socket = 0;
return false;
}
TL2CAPSockAddr addr;
if(!address.isNull())
{
// TBTDevAddr constructor may panic
TRAPD(err,addr.SetBTAddr(TBTDevAddr(address.toUInt64())));
if(err != KErrNone)
{
delete d->socket;
d->socket = 0;
return false;
}
}
if (port == 0)
addr.SetPort(KL2CAPPassiveAutoBind);
else
addr.SetPort(port);
TBTServiceSecurity security;
switch (d->securityFlags) {
case QBluetooth::Authentication:
security.SetAuthentication(EMitmDesired);
break;
case QBluetooth::Authorization:
security.SetAuthorisation(ETrue);
break;
case QBluetooth::Encryption:
// "Secure" is BlueZ specific we just make sure the code remain compatible
case QBluetooth::Secure:
// authentication required
security.SetAuthentication(EMitmDesired);
security.SetEncryption(ETrue);
break;
case QBluetooth::NoSecurity:
default:
break;
}
addr.SetSecurity(security);
if(d->ds->iSocket->Bind(addr) == KErrNone)
{
d->socket->setSocketState(QBluetoothSocket::BoundState);
}
else
{
delete d->socket;
d->socket = 0;
return false;
}
if(d->ds->iSocket->Listen(d->maxPendingConnections) != KErrNone)
{
delete d->socket;
d->socket = 0;
return false;
}
// unknown socket type is used for blank socket
QBluetoothSocket *pendingSocket = new QBluetoothSocket(QBluetoothSocket::UnknownSocketType, this);
if(!pendingSocket)
{
delete d->socket;
d->socket = 0;
return false;
}
QBluetoothSocketPrivate *pd = pendingSocket->d_ptr;
pd->ensureBlankNativeSocket(QBluetoothSocket::L2capSocket);
connect(d->socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
connect(d->socket, SIGNAL(connected()), this, SLOT(connected()));
connect(d->socket, SIGNAL(error(QBluetoothSocket::SocketError)), this, SLOT(socketError(QBluetoothSocket::SocketError)));
if (d->ds->iSocket->Accept(*pd->iSocket) == KErrNone)
{
d->socket->setSocketState(QBluetoothSocket::ListeningState);
d->activeSockets.append(pendingSocket);
return true;
}
else
{
delete d->socket, pendingSocket;
d->socket = 0;
return false;
}
}
void QL2capServer::setMaxPendingConnections(int numConnections)
{
Q_D(QL2capServer);
d->maxPendingConnections = numConnections;
}
bool QL2capServer::hasPendingConnections() const
{
Q_D(const QL2capServer);
return !d->activeSockets.isEmpty();
}
QBluetoothSocket *QL2capServer::nextPendingConnection()
{
Q_D(QL2capServer);
if (d->activeSockets.isEmpty())
return 0;
QBluetoothSocket *next = d->activeSockets.takeFirst();
return next;
}
QBluetoothAddress QL2capServer::serverAddress() const
{
Q_D(const QL2capServer);
if(d->socket)
return d->socket->localAddress();
else
return QBluetoothAddress();
}
quint16 QL2capServer::serverPort() const
{
Q_D(const QL2capServer);
if(d->socket)
return d->socket->localPort();
else
return 0;
}
void QL2capServer::connected()
{
Q_D(QL2capServer);
if(!d->activeSockets.isEmpty())
{
// update state of the pending socket and start receiving
(d->activeSockets.last())->setSocketState(QBluetoothSocket::ConnectedState);
(d->activeSockets.last())->d_ptr->startReceive();
}
else
return;
emit newConnection();
QBluetoothSocket *pendingSocket = new QBluetoothSocket(QBluetoothSocket::UnknownSocketType);
if(!pendingSocket)
{
delete d->socket;
d->socket = 0;
return;
}
QBluetoothSocketPrivate *pd = pendingSocket->d_ptr;
pd->ensureBlankNativeSocket(QBluetoothSocket::L2capSocket);
if (d->ds->iSocket->Accept(*pd->iSocket) == KErrNone)
{
d->socket->setSocketState(QBluetoothSocket::ListeningState);
d->activeSockets.append(pendingSocket);
return;
}
else
{
// we might reach this statement if we have reach
// maxPendingConnections
qDebug() << "QL2capServer::connected accept failed";
delete d->socket, pendingSocket;
d->socket = 0;
return;
}
}
void QL2capServer::disconnected()
{
Q_D(QL2capServer);
delete d->socket;
d->socket = 0;
}
void QL2capServer::socketError(QBluetoothSocket::SocketError err)
{
Q_D(QL2capServer);
delete d->socket;
d->socket = 0;
}
void QL2capServer::setSecurityFlags(QBluetooth::SecurityFlags security)
{
Q_D(QL2capServer);
d->securityFlags = security;
}
QBluetooth::SecurityFlags QL2capServer::securityFlags() const
{
Q_D(const QL2capServer);
return d->securityFlags;
}
QTM_END_NAMESPACE
<|endoftext|>
|
<commit_before>/* Copyright (c) 2008-2019 the MRtrix3 contributors.
*
* 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/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/
#include "file/config.h"
#include "gui/opengl/gl.h"
#include "gui/mrview/mode/base.h"
namespace MR
{
namespace GUI
{
namespace MRView
{
namespace Mode
{
Base::Base (int flags) :
projection (window().glarea, window().font),
features (flags),
update_overlays (false),
visible (true) { }
Base::~Base ()
{
glarea()->setCursor (Cursor::crosshair);
}
const Projection* Base::get_current_projection () const { return &projection; }
void Base::paintGL ()
{
GL::assert_context_is_current();
GL_CHECK_ERROR;
projection.set_viewport (window(), 0, 0, width(), height());
GL_CHECK_ERROR;
gl::Clear (gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
if (!image()) {
projection.setup_render_text();
projection.render_text (10, 10, "No image loaded");
projection.done_render_text();
goto done_painting;
}
GL_CHECK_ERROR;
if (!std::isfinite (focus().squaredNorm()) || !std::isfinite (target().squaredNorm()))
reset_view();
{
GL_CHECK_ERROR;
// call mode's draw method:
paint (projection);
gl::Disable (gl::MULTISAMPLE);
GL_CHECK_ERROR;
projection.setup_render_text();
if (window().show_voxel_info()) {
Eigen::Vector3f voxel (image()->transform().scanner2voxel.cast<float>() * focus());
ssize_t vox [] = { ssize_t(std::round (voxel[0])), ssize_t(std::round (voxel[1])), ssize_t(std::round (voxel[2])) };
std::string vox_str = printf ("voxel index: [ %d %d %d ", vox[0], vox[1], vox[2]);
for (size_t n = 3; n < image()->header().ndim(); ++n)
vox_str += str(image()->image.index(n)) + " ";
vox_str += "]";
projection.render_text (printf ("position: [ %.4g %.4g %.4g ] mm", focus() [0], focus() [1], focus() [2]), LeftEdge | BottomEdge);
projection.render_text (vox_str, LeftEdge | BottomEdge, 1);
std::string value_str;
cfloat value;
if (image()->interpolate()) {
value_str = "interp value: ";
value = image()->trilinear_value (window().focus());
} else {
value_str = "voxel value: ";
value = image()->nearest_neighbour_value (window().focus());
}
if (std::isfinite (abs (value)))
value_str += str(value);
else
value_str += "?";
projection.render_text (value_str, LeftEdge | BottomEdge, 2);
// Draw additional labels from tools
QList<QAction*> tools = window().tools()->actions();
for (size_t i = 0, line_num = 4, N = tools.size(); i < N; ++i) {
Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(tools[i])->dock;
if (dock)
line_num += dock->tool->draw_tool_labels (LeftEdge | BottomEdge, line_num, projection);
}
}
GL_CHECK_ERROR;
if (window().show_comments()) {
for (size_t line = 0; line != image()->comments().size(); ++line)
projection.render_text (image()->comments()[line], LeftEdge | TopEdge, line);
}
projection.done_render_text();
GL_CHECK_ERROR;
if (window().show_colourbar()) {
auto &colourbar_renderer = window().colourbar_renderer;
colourbar_renderer.begin (&projection, window().colourbar_position, 1);
colourbar_renderer.render (*image(), image()->scale_inverted());
colourbar_renderer.end ();
QList<QAction*> tools = window().tools()->actions();
size_t num_tool_colourbars = 0;
for (size_t i = 0, N = tools.size(); i < N; ++i) {
Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(tools[i])->dock;
if (dock)
num_tool_colourbars += dock->tool->visible_number_colourbars ();
}
colourbar_renderer.begin (&projection, window().tools_colourbar_position, num_tool_colourbars);
for (size_t i = 0, N = tools.size(); i < N; ++i) {
Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(tools[i])->dock;
if (dock)
dock->tool->draw_colourbars ();
}
colourbar_renderer.end ();
}
GL_CHECK_ERROR;
}
done_painting:
update_overlays = false;
GL::assert_context_is_current();
}
void Base::paint (Projection&) { }
void Base::mouse_press_event () { }
void Base::mouse_release_event () { }
void Base::slice_move_event (const ModelViewProjection& proj, float x)
{
const auto &header = image()->header();
float increment = snap_to_image() ?
x * header.spacing (plane()) :
x * std::pow (header.spacing(0) * header.spacing(1) * header.spacing(2), 1/3.f);
move_in_out (increment, proj);
move_target_to_focus_plane (proj);
updateGL();
}
void Base::slice_move_event (float x)
{
const ModelViewProjection* proj = get_current_projection();
if (!proj) return;
slice_move_event (*proj, x);
}
void Base::set_focus_event (const ModelViewProjection& proj)
{
set_focus (proj.screen_to_model (window().mouse_position(), focus()));
updateGL();
}
void Base::set_focus_event ()
{
const ModelViewProjection* proj = get_current_projection();
if (!proj) return;
set_focus_event (*proj);
}
void Base::contrast_event ()
{
image()->adjust_windowing (window().mouse_displacement());
window().on_scaling_changed();
updateGL();
}
void Base::pan_event (const ModelViewProjection& proj)
{
set_target (target() - proj.screen_to_model_direction (window().mouse_displacement(), target()));
// updateGL(); # updateGL() causes pan gestures to remain in state Qt::GestureUpdated, never reaching Qt::GestureFinished on macOS
}
void Base::pan_event ()
{
const ModelViewProjection* proj = get_current_projection();
if (!proj) return;
pan_event (*proj);
}
void Base::panthrough_event (const ModelViewProjection& proj)
{
move_in_out_FOV (window().mouse_displacement().y(), proj);
move_target_to_focus_plane (proj);
updateGL();
}
void Base::panthrough_event ()
{
const ModelViewProjection* proj = get_current_projection();
if (!proj) return;
panthrough_event (*proj);
}
void Base::reset_windowing ()
{
if (image()) {
image()->reset_windowing (plane(), snap_to_image());
emit window().on_scaling_changed();
updateGL();
}
}
void Base::setup_projection (const int axis, ModelViewProjection& with_projection) const
{
const GL::mat4 M = snap_to_image() ? GL::mat4 (image()->transform().image2scanner.matrix()) : GL::mat4 (orientation());
setup_projection (adjust_projection_matrix (GL::transpose (M), axis), with_projection);
}
void Base::setup_projection (const Math::Versorf& V, ModelViewProjection& with_projection) const
{
setup_projection (adjust_projection_matrix (GL::transpose (GL::mat4 (V))), with_projection);
}
void Base::setup_projection (const GL::mat4& M, ModelViewProjection& with_projection) const
{
// info for projection:
const int w = with_projection.width(), h = with_projection.height();
const float fov = FOV() / (float)(w+h);
const float depth = std::sqrt ( Math::pow2 (image()->header().spacing(0) * image()->header().size(0))
+ Math::pow2 (image()->header().spacing(1) * image()->header().size(1))
+ Math::pow2 (image()->header().spacing(2) * image()->header().size(2)));
// set up projection & modelview matrices:
const GL::mat4 P = GL::ortho (-w*fov, w*fov, -h*fov, h*fov, -depth, depth);
const GL::mat4 MV = M * GL::translate (-target());
with_projection.set (MV, P);
}
Math::Versorf Base::get_tilt_rotation (const ModelViewProjection& proj) const
{
QPoint dpos = window().mouse_displacement();
if (dpos.x() == 0 && dpos.y() == 0)
return Math::Versorf();
const Eigen::Vector3f x = proj.screen_to_model_direction (dpos, target());
const Eigen::Vector3f z = proj.screen_normal();
const Eigen::Vector3f v (x.cross (z).normalized());
float angle = -ROTATION_INC * std::sqrt (float (Math::pow2 (dpos.x()) + Math::pow2 (dpos.y())));
if (angle > Math::pi_2)
angle = Math::pi_2;
return Math::Versorf (Eigen::AngleAxisf (angle, v));
}
Math::Versorf Base::get_rotate_rotation (const ModelViewProjection& proj) const
{
QPoint dpos = window().mouse_displacement();
if (dpos.x() == 0 && dpos.y() == 0)
return Math::Versorf();
Eigen::Vector3f x1 (window().mouse_position().x() - proj.x_position() - proj.width()/2,
window().mouse_position().y() - proj.y_position() - proj.height()/2,
0.0);
if (x1.norm() < 16.0f)
return Math::Versorf();
Eigen::Vector3f x0 (dpos.x() - x1[0], dpos.y() - x1[1], 0.0);
x1.normalize();
x0.normalize();
const Eigen::Vector3f n = x1.cross (x0);
const float angle = n[2];
Eigen::Vector3f v = (proj.screen_normal()).normalized();
return Math::Versorf (Eigen::AngleAxisf (angle, v));
}
void Base::tilt_event (const ModelViewProjection& proj)
{
if (snap_to_image())
window().set_snap_to_image (false);
const Math::Versorf rot = get_tilt_rotation (proj);
if (!rot)
return;
Math::Versorf orient = rot * orientation();
set_orientation (orient);
updateGL();
}
void Base::tilt_event ()
{
const ModelViewProjection* proj = get_current_projection();
if (!proj) return;
tilt_event (*proj);
}
void Base::rotate_event (const ModelViewProjection& proj)
{
if (snap_to_image())
window().set_snap_to_image (false);
const Math::Versorf rot = get_rotate_rotation (proj);
if (!rot)
return;
Math::Versorf orient = rot * orientation();
set_orientation (orient);
updateGL();
}
void Base::rotate_event ()
{
const ModelViewProjection* proj = get_current_projection();
if (!proj) return;
rotate_event (*proj);
}
void Base::reset_event ()
{
reset_view();
updateGL();
}
void Base::reset_view ()
{
if (!image()) return;
const ModelViewProjection* proj = get_current_projection();
if (!proj) return;
float dim[] = {
float(image()->header().size (0) * image()->header().spacing (0)),
float(image()->header().size (1) * image()->header().spacing (1)),
float(image()->header().size (2) * image()->header().spacing (2))
};
if (dim[0] < dim[1] && dim[0] < dim[2])
set_plane (0);
else if (dim[1] < dim[0] && dim[1] < dim[2])
set_plane (1);
else
set_plane (2);
Eigen::Vector3f p (
std::floor ((image()->header().size(0)-1)/2.0f),
std::floor ((image()->header().size(1)-1)/2.0f),
std::floor ((image()->header().size(2)-1)/2.0f)
);
set_focus (image()->transform().voxel2scanner.cast<float>() * p);
set_target (focus());
reset_orientation();
int x, y;
image()->get_axes (plane(), x, y);
set_FOV (std::max (dim[x], dim[y]));
updateGL();
}
GL::mat4 Base::adjust_projection_matrix (const GL::mat4& Q, int proj) const
{
GL::mat4 M;
M(3,0) = M(3,1) = M(3,2) = M(0,3) = M(1,3) = M(2,3) = 0.0f;
M(3,3) = 1.0f;
if (proj == 0) { // sagittal
for (size_t n = 0; n < 3; n++) {
M(0,n) = -Q(1,n); // x: -y
M(1,n) = Q(2,n); // y: z
M(2,n) = -Q(0,n); // z: -x
}
}
else if (proj == 1) { // coronal
for (size_t n = 0; n < 3; n++) {
M(0,n) = -Q(0,n); // x: -x
M(1,n) = Q(2,n); // y: z
M(2,n) = Q(1,n); // z: y
}
}
else { // axial
for (size_t n = 0; n < 3; n++) {
M(0,n) = -Q(0,n); // x: -x
M(1,n) = Q(1,n); // y: y
M(2,n) = -Q(2,n); // z: -z
}
}
return M;
}
}
}
}
}
#undef MODE
<commit_msg>mrview: fix cursor jump following pan gesture on macOS<commit_after>/* Copyright (c) 2008-2019 the MRtrix3 contributors.
*
* 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/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/
#include "file/config.h"
#include "gui/opengl/gl.h"
#include "gui/mrview/mode/base.h"
namespace MR
{
namespace GUI
{
namespace MRView
{
namespace Mode
{
Base::Base (int flags) :
projection (window().glarea, window().font),
features (flags),
update_overlays (false),
visible (true) { }
Base::~Base ()
{
glarea()->setCursor (Cursor::crosshair);
}
const Projection* Base::get_current_projection () const { return &projection; }
void Base::paintGL ()
{
GL::assert_context_is_current();
GL_CHECK_ERROR;
projection.set_viewport (window(), 0, 0, width(), height());
GL_CHECK_ERROR;
gl::Clear (gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
if (!image()) {
projection.setup_render_text();
projection.render_text (10, 10, "No image loaded");
projection.done_render_text();
goto done_painting;
}
GL_CHECK_ERROR;
if (!std::isfinite (focus().squaredNorm()) || !std::isfinite (target().squaredNorm()))
reset_view();
{
GL_CHECK_ERROR;
// call mode's draw method:
paint (projection);
gl::Disable (gl::MULTISAMPLE);
GL_CHECK_ERROR;
projection.setup_render_text();
if (window().show_voxel_info()) {
Eigen::Vector3f voxel (image()->transform().scanner2voxel.cast<float>() * focus());
ssize_t vox [] = { ssize_t(std::round (voxel[0])), ssize_t(std::round (voxel[1])), ssize_t(std::round (voxel[2])) };
std::string vox_str = printf ("voxel index: [ %d %d %d ", vox[0], vox[1], vox[2]);
for (size_t n = 3; n < image()->header().ndim(); ++n)
vox_str += str(image()->image.index(n)) + " ";
vox_str += "]";
projection.render_text (printf ("position: [ %.4g %.4g %.4g ] mm", focus() [0], focus() [1], focus() [2]), LeftEdge | BottomEdge);
projection.render_text (vox_str, LeftEdge | BottomEdge, 1);
std::string value_str;
cfloat value;
if (image()->interpolate()) {
value_str = "interp value: ";
value = image()->trilinear_value (window().focus());
} else {
value_str = "voxel value: ";
value = image()->nearest_neighbour_value (window().focus());
}
if (std::isfinite (abs (value)))
value_str += str(value);
else
value_str += "?";
projection.render_text (value_str, LeftEdge | BottomEdge, 2);
// Draw additional labels from tools
QList<QAction*> tools = window().tools()->actions();
for (size_t i = 0, line_num = 4, N = tools.size(); i < N; ++i) {
Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(tools[i])->dock;
if (dock)
line_num += dock->tool->draw_tool_labels (LeftEdge | BottomEdge, line_num, projection);
}
}
GL_CHECK_ERROR;
if (window().show_comments()) {
for (size_t line = 0; line != image()->comments().size(); ++line)
projection.render_text (image()->comments()[line], LeftEdge | TopEdge, line);
}
projection.done_render_text();
GL_CHECK_ERROR;
if (window().show_colourbar()) {
auto &colourbar_renderer = window().colourbar_renderer;
colourbar_renderer.begin (&projection, window().colourbar_position, 1);
colourbar_renderer.render (*image(), image()->scale_inverted());
colourbar_renderer.end ();
QList<QAction*> tools = window().tools()->actions();
size_t num_tool_colourbars = 0;
for (size_t i = 0, N = tools.size(); i < N; ++i) {
Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(tools[i])->dock;
if (dock)
num_tool_colourbars += dock->tool->visible_number_colourbars ();
}
colourbar_renderer.begin (&projection, window().tools_colourbar_position, num_tool_colourbars);
for (size_t i = 0, N = tools.size(); i < N; ++i) {
Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(tools[i])->dock;
if (dock)
dock->tool->draw_colourbars ();
}
colourbar_renderer.end ();
}
GL_CHECK_ERROR;
}
done_painting:
update_overlays = false;
GL::assert_context_is_current();
}
void Base::paint (Projection&) { }
void Base::mouse_press_event () { }
void Base::mouse_release_event () { }
void Base::slice_move_event (const ModelViewProjection& proj, float x)
{
const auto &header = image()->header();
float increment = snap_to_image() ?
x * header.spacing (plane()) :
x * std::pow (header.spacing(0) * header.spacing(1) * header.spacing(2), 1/3.f);
move_in_out (increment, proj);
move_target_to_focus_plane (proj);
updateGL();
}
void Base::slice_move_event (float x)
{
const ModelViewProjection* proj = get_current_projection();
if (!proj) return;
slice_move_event (*proj, x);
}
void Base::set_focus_event (const ModelViewProjection& proj)
{
set_focus (proj.screen_to_model (window().mouse_position(), focus()));
updateGL();
}
void Base::set_focus_event ()
{
const ModelViewProjection* proj = get_current_projection();
if (!proj) return;
set_focus_event (*proj);
}
void Base::contrast_event ()
{
image()->adjust_windowing (window().mouse_displacement());
window().on_scaling_changed();
updateGL();
}
void Base::pan_event (const ModelViewProjection& proj)
{
set_target (target() - proj.screen_to_model_direction (window().mouse_displacement(), target()));
updateGL();
}
void Base::pan_event ()
{
const ModelViewProjection* proj = get_current_projection();
if (!proj) return;
pan_event (*proj);
}
void Base::panthrough_event (const ModelViewProjection& proj)
{
move_in_out_FOV (window().mouse_displacement().y(), proj);
move_target_to_focus_plane (proj);
updateGL();
}
void Base::panthrough_event ()
{
const ModelViewProjection* proj = get_current_projection();
if (!proj) return;
panthrough_event (*proj);
}
void Base::reset_windowing ()
{
if (image()) {
image()->reset_windowing (plane(), snap_to_image());
emit window().on_scaling_changed();
updateGL();
}
}
void Base::setup_projection (const int axis, ModelViewProjection& with_projection) const
{
const GL::mat4 M = snap_to_image() ? GL::mat4 (image()->transform().image2scanner.matrix()) : GL::mat4 (orientation());
setup_projection (adjust_projection_matrix (GL::transpose (M), axis), with_projection);
}
void Base::setup_projection (const Math::Versorf& V, ModelViewProjection& with_projection) const
{
setup_projection (adjust_projection_matrix (GL::transpose (GL::mat4 (V))), with_projection);
}
void Base::setup_projection (const GL::mat4& M, ModelViewProjection& with_projection) const
{
// info for projection:
const int w = with_projection.width(), h = with_projection.height();
const float fov = FOV() / (float)(w+h);
const float depth = std::sqrt ( Math::pow2 (image()->header().spacing(0) * image()->header().size(0))
+ Math::pow2 (image()->header().spacing(1) * image()->header().size(1))
+ Math::pow2 (image()->header().spacing(2) * image()->header().size(2)));
// set up projection & modelview matrices:
const GL::mat4 P = GL::ortho (-w*fov, w*fov, -h*fov, h*fov, -depth, depth);
const GL::mat4 MV = M * GL::translate (-target());
with_projection.set (MV, P);
}
Math::Versorf Base::get_tilt_rotation (const ModelViewProjection& proj) const
{
QPoint dpos = window().mouse_displacement();
if (dpos.x() == 0 && dpos.y() == 0)
return Math::Versorf();
const Eigen::Vector3f x = proj.screen_to_model_direction (dpos, target());
const Eigen::Vector3f z = proj.screen_normal();
const Eigen::Vector3f v (x.cross (z).normalized());
float angle = -ROTATION_INC * std::sqrt (float (Math::pow2 (dpos.x()) + Math::pow2 (dpos.y())));
if (angle > Math::pi_2)
angle = Math::pi_2;
return Math::Versorf (Eigen::AngleAxisf (angle, v));
}
Math::Versorf Base::get_rotate_rotation (const ModelViewProjection& proj) const
{
QPoint dpos = window().mouse_displacement();
if (dpos.x() == 0 && dpos.y() == 0)
return Math::Versorf();
Eigen::Vector3f x1 (window().mouse_position().x() - proj.x_position() - proj.width()/2,
window().mouse_position().y() - proj.y_position() - proj.height()/2,
0.0);
if (x1.norm() < 16.0f)
return Math::Versorf();
Eigen::Vector3f x0 (dpos.x() - x1[0], dpos.y() - x1[1], 0.0);
x1.normalize();
x0.normalize();
const Eigen::Vector3f n = x1.cross (x0);
const float angle = n[2];
Eigen::Vector3f v = (proj.screen_normal()).normalized();
return Math::Versorf (Eigen::AngleAxisf (angle, v));
}
void Base::tilt_event (const ModelViewProjection& proj)
{
if (snap_to_image())
window().set_snap_to_image (false);
const Math::Versorf rot = get_tilt_rotation (proj);
if (!rot)
return;
Math::Versorf orient = rot * orientation();
set_orientation (orient);
updateGL();
}
void Base::tilt_event ()
{
const ModelViewProjection* proj = get_current_projection();
if (!proj) return;
tilt_event (*proj);
}
void Base::rotate_event (const ModelViewProjection& proj)
{
if (snap_to_image())
window().set_snap_to_image (false);
const Math::Versorf rot = get_rotate_rotation (proj);
if (!rot)
return;
Math::Versorf orient = rot * orientation();
set_orientation (orient);
updateGL();
}
void Base::rotate_event ()
{
const ModelViewProjection* proj = get_current_projection();
if (!proj) return;
rotate_event (*proj);
}
void Base::reset_event ()
{
reset_view();
updateGL();
}
void Base::reset_view ()
{
if (!image()) return;
const ModelViewProjection* proj = get_current_projection();
if (!proj) return;
float dim[] = {
float(image()->header().size (0) * image()->header().spacing (0)),
float(image()->header().size (1) * image()->header().spacing (1)),
float(image()->header().size (2) * image()->header().spacing (2))
};
if (dim[0] < dim[1] && dim[0] < dim[2])
set_plane (0);
else if (dim[1] < dim[0] && dim[1] < dim[2])
set_plane (1);
else
set_plane (2);
Eigen::Vector3f p (
std::floor ((image()->header().size(0)-1)/2.0f),
std::floor ((image()->header().size(1)-1)/2.0f),
std::floor ((image()->header().size(2)-1)/2.0f)
);
set_focus (image()->transform().voxel2scanner.cast<float>() * p);
set_target (focus());
reset_orientation();
int x, y;
image()->get_axes (plane(), x, y);
set_FOV (std::max (dim[x], dim[y]));
updateGL();
}
GL::mat4 Base::adjust_projection_matrix (const GL::mat4& Q, int proj) const
{
GL::mat4 M;
M(3,0) = M(3,1) = M(3,2) = M(0,3) = M(1,3) = M(2,3) = 0.0f;
M(3,3) = 1.0f;
if (proj == 0) { // sagittal
for (size_t n = 0; n < 3; n++) {
M(0,n) = -Q(1,n); // x: -y
M(1,n) = Q(2,n); // y: z
M(2,n) = -Q(0,n); // z: -x
}
}
else if (proj == 1) { // coronal
for (size_t n = 0; n < 3; n++) {
M(0,n) = -Q(0,n); // x: -x
M(1,n) = Q(2,n); // y: z
M(2,n) = Q(1,n); // z: y
}
}
else { // axial
for (size_t n = 0; n < 3; n++) {
M(0,n) = -Q(0,n); // x: -x
M(1,n) = Q(1,n); // y: y
M(2,n) = -Q(2,n); // z: -z
}
}
return M;
}
}
}
}
}
#undef MODE
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtGui module of the Qt eXTension library
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of th Common Public License, version 1.0, as published by
** IBM.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL along with this file.
** See the LICENSE file and the cpl1.0.txt file included with the source
** distribution for more information. If you did not receive a copy of the
** license, contact the Qxt Foundation.
**
** <http://libqxt.sourceforge.net> <foundation@libqxt.org>
**
****************************************************************************/
#include "qxtcheckcombobox.h"
#include "qxtcheckcombobox_p.h"
#include <QLineEdit>
#include <QKeyEvent>
QxtCheckComboBoxPrivate::QxtCheckComboBoxPrivate()
{
separator = QLatin1String(",");
}
bool QxtCheckComboBoxPrivate::eventFilter(QObject* receiver, QEvent* event)
{
switch (event->type())
{
case QEvent::KeyPress:
case QEvent::KeyRelease:
{
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
if (receiver == &qxt_p() && (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down))
{
qxt_p().showPopup();
return true;
}
else if (keyEvent->key() == Qt::Key_Escape)
{
// it is important to call QComboBox implementation
qxt_p().QComboBox::hidePopup();
}
return false;
}
default:
return false;
}
}
void QxtCheckComboBoxPrivate::updateCheckedItems()
{
QStringList items = qxt_p().checkedItems();
if (items.isEmpty())
qxt_p().setEditText(defaultText);
else
qxt_p().setEditText(items.join(separator));
// TODO: find a way to recalculate a meaningful size hint
emit qxt_p().checkedItemsChanged(items);
}
void QxtCheckComboBoxPrivate::toggleCheckState(int index)
{
QVariant value = qxt_p().itemData(index, Qt::CheckStateRole);
if (value.isValid())
{
Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
qxt_p().setItemData(index, (state == Qt::Unchecked ? Qt::Checked : Qt::Unchecked), Qt::CheckStateRole);
}
}
QxtCheckComboModel::QxtCheckComboModel(QObject* parent)
: QStandardItemModel(0, 1, parent) // rows,cols
{
}
Qt::ItemFlags QxtCheckComboModel::flags(const QModelIndex& index) const
{
return QStandardItemModel::flags(index) | Qt::ItemIsUserCheckable;
}
QVariant QxtCheckComboModel::data(const QModelIndex& index, int role) const
{
QVariant value = QStandardItemModel::data(index, role);
if (index.isValid() && role == Qt::CheckStateRole && !value.isValid())
value = Qt::Unchecked;
return value;
}
bool QxtCheckComboModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
bool ok = QStandardItemModel::setData(index, value, role);
if (ok && role == Qt::CheckStateRole)
{
emit dataChanged(index, index);
emit checkStateChanged();
}
return ok;
}
/*!
\class QxtCheckComboBox QxtCheckComboBox
\ingroup QxtGui
\brief An extended QComboBox with checkable items.
QxtComboBox is a specialized combo box with checkable items.
Checked items are collected together in the line edit.
\image html qxtcheckcombobox.png "QxtCheckComboBox in Plastique style."
*/
/*!
\enum QxtCheckComboBox::CheckMode
This enum describes the check mode.
\sa QxtCheckComboBox::checkMode
*/
/*!
\var QxtCheckComboBox::CheckMode QxtCheckComboBox::CheckIndicator
The check state changes only via the check indicator (like in item views).
*/
/*!
\var QxtCheckComboBox::CheckMode QxtCheckComboBox::CheckWholeItem
The check state changes via the whole item (like with a combo box).
*/
/*!
\fn QxtCheckComboBox::checkedItemsChanged(const QStringList& items)
This signal is emitted whenever the checked items have been changed.
*/
/*!
Constructs a new QxtCheckComboBox with \a parent.
*/
QxtCheckComboBox::QxtCheckComboBox(QWidget* parent) : QComboBox(parent)
{
QXT_INIT_PRIVATE(QxtCheckComboBox);
setModel(new QxtCheckComboModel(this));
connect(this, SIGNAL(activated(int)), &qxt_d(), SLOT(toggleCheckState(int)));
connect(model(), SIGNAL(checkStateChanged()), &qxt_d(), SLOT(updateCheckedItems()));
// read-only contents
QLineEdit* lineEdit = new QLineEdit(this);
lineEdit->setReadOnly(true);
setLineEdit(lineEdit);
view()->installEventFilter(&qxt_d());
view()->viewport()->installEventFilter(&qxt_d());
this->installEventFilter(&qxt_d());
}
/*!
Destructs the combo box.
*/
QxtCheckComboBox::~QxtCheckComboBox()
{
}
/*!
\reimp
*/
void QxtCheckComboBox::hidePopup()
{
}
/*!
Returns the check state of the item at \a index.
*/
Qt::CheckState QxtCheckComboBox::itemCheckState(int index) const
{
return static_cast<Qt::CheckState>(itemData(index, Qt::CheckStateRole).toInt());
}
/*!
Sets the check state of the item at \a index to \a state.
*/
void QxtCheckComboBox::setItemCheckState(int index, Qt::CheckState state)
{
setItemData(index, state, Qt::CheckStateRole);
}
/*!
\property QxtCheckComboBox::checkedItems
\brief This property holds the checked items.
*/
QStringList QxtCheckComboBox::checkedItems() const
{
QStringList items;
if (model())
{
QModelIndex index = model()->index(0, modelColumn(), rootModelIndex());
QModelIndexList indexes = model()->match(index, Qt::CheckStateRole, Qt::Checked, -1, Qt::MatchExactly);
foreach (const QModelIndex& index, indexes)
items += index.data().toString();
}
return items;
}
void QxtCheckComboBox::setCheckedItems(const QStringList& items)
{
// not the most efficient solution but most likely nobody
// will put too many items into a combo box anyway so...
foreach (const QString& text, items)
{
const int index = findText(text);
setItemCheckState(index, index != -1 ? Qt::Checked : Qt::Unchecked);
}
}
/*!
\property QxtCheckComboBox::defaultText
\brief This property holds the default text.
The default text is shown when there are no checked items.
The default value is an empty string.
*/
QString QxtCheckComboBox::defaultText() const
{
return qxt_d().defaultText;
}
void QxtCheckComboBox::setDefaultText(const QString& text)
{
if (qxt_d().defaultText != text)
{
qxt_d().defaultText = text;
qxt_d().updateCheckedItems();
}
}
/*!
\property QxtCheckComboBox::separator
\brief This property holds the default separator.
The checked items are joined together with the separator string.
The default value is a comma (",").
*/
QString QxtCheckComboBox::separator() const
{
return qxt_d().separator;
}
void QxtCheckComboBox::setSeparator(const QString& separator)
{
if (qxt_d().separator != separator)
{
qxt_d().separator = separator;
qxt_d().updateCheckedItems();
}
}
<commit_msg>Made QxtCheckComboBox to setInsertPolicy(QComboBox::NoInsert). This fixes a bug which caused QxtCheckComboBox to accidentally insert line edit content (eg. currently checked items) when hitting enter.<commit_after>/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtGui module of the Qt eXTension library
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of th Common Public License, version 1.0, as published by
** IBM.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL along with this file.
** See the LICENSE file and the cpl1.0.txt file included with the source
** distribution for more information. If you did not receive a copy of the
** license, contact the Qxt Foundation.
**
** <http://libqxt.sourceforge.net> <foundation@libqxt.org>
**
****************************************************************************/
#include "qxtcheckcombobox.h"
#include "qxtcheckcombobox_p.h"
#include <QLineEdit>
#include <QKeyEvent>
QxtCheckComboBoxPrivate::QxtCheckComboBoxPrivate()
{
separator = QLatin1String(",");
}
bool QxtCheckComboBoxPrivate::eventFilter(QObject* receiver, QEvent* event)
{
switch (event->type())
{
case QEvent::KeyPress:
case QEvent::KeyRelease:
{
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
if (receiver == &qxt_p() && (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down))
{
qxt_p().showPopup();
return true;
}
else if (keyEvent->key() == Qt::Key_Escape)
{
// it is important to call QComboBox implementation
qxt_p().QComboBox::hidePopup();
}
return false;
}
default:
return false;
}
}
void QxtCheckComboBoxPrivate::updateCheckedItems()
{
QStringList items = qxt_p().checkedItems();
if (items.isEmpty())
qxt_p().setEditText(defaultText);
else
qxt_p().setEditText(items.join(separator));
// TODO: find a way to recalculate a meaningful size hint
emit qxt_p().checkedItemsChanged(items);
}
void QxtCheckComboBoxPrivate::toggleCheckState(int index)
{
QVariant value = qxt_p().itemData(index, Qt::CheckStateRole);
if (value.isValid())
{
Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
qxt_p().setItemData(index, (state == Qt::Unchecked ? Qt::Checked : Qt::Unchecked), Qt::CheckStateRole);
}
}
QxtCheckComboModel::QxtCheckComboModel(QObject* parent)
: QStandardItemModel(0, 1, parent) // rows,cols
{
}
Qt::ItemFlags QxtCheckComboModel::flags(const QModelIndex& index) const
{
return QStandardItemModel::flags(index) | Qt::ItemIsUserCheckable;
}
QVariant QxtCheckComboModel::data(const QModelIndex& index, int role) const
{
QVariant value = QStandardItemModel::data(index, role);
if (index.isValid() && role == Qt::CheckStateRole && !value.isValid())
value = Qt::Unchecked;
return value;
}
bool QxtCheckComboModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
bool ok = QStandardItemModel::setData(index, value, role);
if (ok && role == Qt::CheckStateRole)
{
emit dataChanged(index, index);
emit checkStateChanged();
}
return ok;
}
/*!
\class QxtCheckComboBox QxtCheckComboBox
\ingroup QxtGui
\brief An extended QComboBox with checkable items.
QxtComboBox is a specialized combo box with checkable items.
Checked items are collected together in the line edit.
\image html qxtcheckcombobox.png "QxtCheckComboBox in Plastique style."
*/
/*!
\enum QxtCheckComboBox::CheckMode
This enum describes the check mode.
\sa QxtCheckComboBox::checkMode
*/
/*!
\var QxtCheckComboBox::CheckMode QxtCheckComboBox::CheckIndicator
The check state changes only via the check indicator (like in item views).
*/
/*!
\var QxtCheckComboBox::CheckMode QxtCheckComboBox::CheckWholeItem
The check state changes via the whole item (like with a combo box).
*/
/*!
\fn QxtCheckComboBox::checkedItemsChanged(const QStringList& items)
This signal is emitted whenever the checked items have been changed.
*/
/*!
Constructs a new QxtCheckComboBox with \a parent.
*/
QxtCheckComboBox::QxtCheckComboBox(QWidget* parent) : QComboBox(parent)
{
QXT_INIT_PRIVATE(QxtCheckComboBox);
setModel(new QxtCheckComboModel(this));
connect(this, SIGNAL(activated(int)), &qxt_d(), SLOT(toggleCheckState(int)));
connect(model(), SIGNAL(checkStateChanged()), &qxt_d(), SLOT(updateCheckedItems()));
// read-only contents
QLineEdit* lineEdit = new QLineEdit(this);
lineEdit->setReadOnly(true);
setLineEdit(lineEdit);
setInsertPolicy(QComboBox::NoInsert);
view()->installEventFilter(&qxt_d());
view()->viewport()->installEventFilter(&qxt_d());
this->installEventFilter(&qxt_d());
}
/*!
Destructs the combo box.
*/
QxtCheckComboBox::~QxtCheckComboBox()
{
}
/*!
\reimp
*/
void QxtCheckComboBox::hidePopup()
{
}
/*!
Returns the check state of the item at \a index.
*/
Qt::CheckState QxtCheckComboBox::itemCheckState(int index) const
{
return static_cast<Qt::CheckState>(itemData(index, Qt::CheckStateRole).toInt());
}
/*!
Sets the check state of the item at \a index to \a state.
*/
void QxtCheckComboBox::setItemCheckState(int index, Qt::CheckState state)
{
setItemData(index, state, Qt::CheckStateRole);
}
/*!
\property QxtCheckComboBox::checkedItems
\brief This property holds the checked items.
*/
QStringList QxtCheckComboBox::checkedItems() const
{
QStringList items;
if (model())
{
QModelIndex index = model()->index(0, modelColumn(), rootModelIndex());
QModelIndexList indexes = model()->match(index, Qt::CheckStateRole, Qt::Checked, -1, Qt::MatchExactly);
foreach (const QModelIndex& index, indexes)
items += index.data().toString();
}
return items;
}
void QxtCheckComboBox::setCheckedItems(const QStringList& items)
{
// not the most efficient solution but most likely nobody
// will put too many items into a combo box anyway so...
foreach (const QString& text, items)
{
const int index = findText(text);
setItemCheckState(index, index != -1 ? Qt::Checked : Qt::Unchecked);
}
}
/*!
\property QxtCheckComboBox::defaultText
\brief This property holds the default text.
The default text is shown when there are no checked items.
The default value is an empty string.
*/
QString QxtCheckComboBox::defaultText() const
{
return qxt_d().defaultText;
}
void QxtCheckComboBox::setDefaultText(const QString& text)
{
if (qxt_d().defaultText != text)
{
qxt_d().defaultText = text;
qxt_d().updateCheckedItems();
}
}
/*!
\property QxtCheckComboBox::separator
\brief This property holds the default separator.
The checked items are joined together with the separator string.
The default value is a comma (",").
*/
QString QxtCheckComboBox::separator() const
{
return qxt_d().separator;
}
void QxtCheckComboBox::setSeparator(const QString& separator)
{
if (qxt_d().separator != separator)
{
qxt_d().separator = separator;
qxt_d().updateCheckedItems();
}
}
<|endoftext|>
|
<commit_before>#pragma sw require header org.sw.demo.google.protobuf.protoc
#pragma sw require header org.sw.demo.qtproject.qt.base.tools.moc-5
#define QT_VERSION "-5"
/*void configure(Build &s)
{
if (s.isConfigSelected("mt"))
{
auto ss = s.createSettings();
ss.Native.LibrariesType = LibraryType::Static;
ss.Native.MT = true;
s.addSettings(ss);
}
}*/
void build(Solution &s)
{
auto &aspia = s.addProject("aspia", "master");
aspia += Git("https://github.com/dchapyshev/aspia", "", "{v}");
constexpr auto cppstd = cpp17;
auto setup_target = [&aspia](auto &t, const String &name, bool add_tests = false, String dir = {}) -> decltype(auto)
{
if (dir.empty())
dir = name;
t += cppstd;
t.Public += "."_idir;
t.setRootDirectory(dir);
t += IncludeDirectory("."s);
t += ".*"_rr;
//
t.AllowEmptyRegexes = true;
// os specific
t -= ".*_win.*"_rr;
t -= ".*_linux.*"_rr;
t -= ".*/linux/.*"_rr;
t -= ".*_pulse.*"_rr;
t -= ".*_mac.*"_rr;
t -= ".*_posix.*"_rr;
t -= ".*_x11.*"_rr;
if (t.getBuildSettings().TargetOS.Type == OSType::Windows)
t += ".*_win.*"_rr;
else if (t.getBuildSettings().TargetOS.isApple())
t += ".*_mac.*"_rr;
else
{
t += ".*_pulse.*"_rr;
t += ".*_linux.*"_rr;
t += ".*/linux/.*"_rr;
t += ".*_x11.*"_rr;
}
if (t.getBuildSettings().TargetOS.Type != OSType::Windows)
t += ".*_posix.*"_rr;
t -= ".*_unittest.*"_rr;
t -= ".*tests.*"_rr;
//
t.AllowEmptyRegexes = false;
// test
if (add_tests)
{
auto &bt = t.addExecutable("test");
bt += cppstd;
bt += FileRegex(dir, ".*_unittest.*", true);
bt += t;
bt += "org.sw.demo.google.googletest.gmock"_dep;
bt += "org.sw.demo.google.googletest.gtest.main"_dep;
t.addTest(bt);
}
return t;
};
auto add_lib = [&aspia, &setup_target](const String &name, bool add_tests = false, String dir = {}) -> decltype(auto)
{
return setup_target(aspia.addStaticLibrary(name), name, add_tests, dir);
};
auto &protocol = aspia.addStaticLibrary("proto");
protocol += "proto/.*\\.proto"_rr;
for (const auto &[p, _] : protocol[FileRegex(protocol.SourceDir / "proto", ".*\\.proto", false)])
{
ProtobufData d;
d.outdir = protocol.BinaryDir / "proto";
d.public_protobuf = true;
d.addIncludeDirectory(protocol.SourceDir / "proto");
gen_protobuf_cpp("org.sw.demo.google.protobuf"_dep, protocol, p, d);
}
auto &base = aspia.addStaticLibrary("base");
base += "third_party/modp_b64/.*\\.[hc]"_rr;
base += "third_party/x11region/.*\\.[hc]"_rr;
base += "third_party/tbb_c_allocator/.*"_rr;
base -= "build/.*"_rr;
setup_target(base, "base", false);
base.Public += "UNICODE"_def;
base.Public += "WIN32_LEAN_AND_MEAN"_def;
base.Public += "NOMINMAX"_def;
base.Public += protocol;
base.Public += "org.sw.demo.qtproject.qt.base.widgets" QT_VERSION ""_dep;
base.Public += "org.sw.demo.qtproject.qt.base.network" QT_VERSION ""_dep;
base.Public += "org.sw.demo.qtproject.qt.base.xml" QT_VERSION ""_dep;
base.Public += "org.sw.demo.boost.align"_dep;
base.Public += "org.sw.demo.imneme.pcg_cpp-master"_dep;
base.Public += "org.sw.demo.chriskohlhoff.asio"_dep;
base.Public += "org.sw.demo.rapidxml"_dep;
base.Public += "org.sw.demo.miloyip.rapidjson"_dep;
base.Public += "org.sw.demo.google.protobuf.protobuf"_dep; // should be protobuf_lite actually?
base.Public += "org.sw.demo.chromium.libyuv-master"_dep;
base.Public += "org.sw.demo.webmproject.vpx"_dep;
base.Public += "org.sw.demo.webmproject.webm"_dep;
base.Public += "org.sw.demo.xiph.opus"_dep;
if (base.getBuildSettings().TargetOS.Type == OSType::Windows)
{
base -= "x11/.*"_rr;
base.Public += "com.Microsoft.Windows.SDK.winrt"_dep;
base +=
"Dbghelp.lib"_slib,
"Mswsock.lib"_slib,
"Avrt.lib"_slib,
"comsuppw.lib"_slib,
"Winspool.lib"_slib,
"Setupapi.lib"_slib
;
}
automoc("org.sw.demo.qtproject.qt.base.tools.moc" QT_VERSION ""_dep, base);
auto &relay = aspia.addExecutable("relay");
relay += cppstd;
relay += "relay/.*"_rr;
relay += base;
auto &router = aspia.addExecutable("router");
router += cppstd;
router += "router/.*"_rr;
router += base;
router += "org.sw.demo.sqlite3"_dep;
auto qt_progs = [](auto &t, const String &name_override = {}, const path &path_override = {})
{
auto name = name_override.empty() ? t.getPackage().getPath().back() : name_override;
automoc("org.sw.demo.qtproject.qt.base.tools.moc" QT_VERSION ""_dep, t);
rcc("org.sw.demo.qtproject.qt.base.tools.rcc" QT_VERSION ""_dep, t, t.SourceDir / path_override / ("resources/" + name + ".qrc"));
qt_uic("org.sw.demo.qtproject.qt.base.tools.uic" QT_VERSION ""_dep, t);
};
auto qt_progs2 = [](auto &t)
{
automoc("org.sw.demo.qtproject.qt.base.tools.moc" QT_VERSION ""_dep, t);
rcc("org.sw.demo.qtproject.qt.base.tools.rcc" QT_VERSION ""_dep, t, t.SourceDir / "ui/resources.qrc");
qt_uic("org.sw.demo.qtproject.qt.base.tools.uic" QT_VERSION ""_dep, t);
};
auto qt_progs_and_tr = [&qt_progs](auto &t, const String &name_override = {}, const path &path_override = {})
{
auto name = name_override.empty() ? t.getPackage().getPath().back() : name_override;
qt_progs(t, name_override, path_override);
// trs
qt_tr("org.sw.demo.qtproject.qt" QT_VERSION ""_dep, t);
t.configureFile(t.SourceDir / path_override / ("translations/" + name + "_translations.qrc"),
t.BinaryDir / (name + "_translations.qrc"), ConfigureFlags::CopyOnly);
rcc("org.sw.demo.qtproject.qt.base.tools.rcc" QT_VERSION ""_dep, t,
t.BinaryDir / (name + "_translations.qrc"))
->working_directory = t.BinaryDir;
};
auto qt_progs_and_tr2 = [&qt_progs2](auto &t)
{
qt_progs2(t);
// trs
qt_tr("org.sw.demo.qtproject.qt" QT_VERSION ""_dep, t);
t.configureFile(t.SourceDir / "ui/translations.qrc",
t.BinaryDir / "translations.qrc", ConfigureFlags::CopyOnly);
rcc("org.sw.demo.qtproject.qt.base.tools.rcc" QT_VERSION ""_dep, t,
t.BinaryDir / "translations.qrc")->working_directory = t.BinaryDir;
};
auto &common = add_lib("common");
if (common.getBuildSettings().TargetOS.Type == OSType::Windows)
{
common -= "file_enumerator_fs.cc";
common.Public += "Shlwapi.lib"_slib;
}
common.Public += base, protocol;
common.Public += "org.sw.demo.openssl.crypto"_dep;
common.Public += "org.sw.demo.qtproject.qt.base.widgets" QT_VERSION ""_dep;
common.Public += "org.sw.demo.qtproject.qt.winextras" QT_VERSION ""_dep;
qt_progs_and_tr(common);
auto &qt_base = add_lib("qt_base");
qt_base.Public += base;
qt_base.Public += "org.sw.demo.qtproject.qt.base.widgets" QT_VERSION ""_dep;
automoc("org.sw.demo.qtproject.qt.base.tools.moc" QT_VERSION ""_dep, qt_base);
qt_translations_rcc("org.sw.demo.qtproject.qt" QT_VERSION ""_dep, aspia, qt_base, "qt_translations.qrc");
auto setup_exe = [](auto &t) -> decltype(auto)
{
if (auto L = t.getSelectedTool()->as<VisualStudioLinker*>(); L)
L->Subsystem = vs::Subsystem::Windows;
t += "org.sw.demo.qtproject.qt.base.winmain" QT_VERSION ""_dep;
return t;
};
//
auto &client_core = add_lib("client");
client_core.Public += common;
if (client_core.getBuildSettings().TargetOS.Type == OSType::Windows)
client_core.Public += "org.sw.demo.qtproject.qt.base.plugins.printsupport.windows" QT_VERSION ""_dep;
qt_progs_and_tr(client_core);
auto add_exe = [&setup_exe](auto &base, const String &name) -> decltype(auto)
{
return setup_exe(base.addExecutable(name));
};
//
auto &console = add_exe(aspia, "console");
setup_target(console, "console");
console.Public += client_core, qt_base;
if (console.getBuildSettings().TargetOS.Type == OSType::Windows)
{
console.Public += "org.sw.demo.qtproject.qt.base.plugins.platforms.windows" QT_VERSION ""_dep;
console.Public += "org.sw.demo.qtproject.qt.base.plugins.styles.windowsvista" QT_VERSION ""_dep;
}
qt_progs_and_tr(console);
auto &host = aspia.addExecutable("host");
auto &core = host.addSharedLibrary("core");
setup_target(core, "host");
core -= ".*_entry_point.cc"_rr, ".*\\.rc"_rr;
core += "HOST_IMPLEMENTATION"_def;
if (core.getBuildSettings().TargetOS.Type == OSType::Windows)
core.Public += "sas.lib"_slib;
core.Public += common, qt_base;
core.Public += "org.sw.demo.boost.property_tree"_dep;
core.Public += "org.sw.demo.qtproject.qt.base.plugins.platforms.windows" QT_VERSION ""_dep;
core.Public += "org.sw.demo.qtproject.qt.base.plugins.styles.windowsvista" QT_VERSION ""_dep;
qt_progs_and_tr2(core);
setup_exe(host);
host += "host/ui/host_entry_point.cc";
host += "host/ui/host.rc";
host += core;
auto &service = add_exe(host, "service");
service += "host/win/service_entry_point.cc";
service += "host/win/service.rc";
service += core;
auto &desktop_agent = add_exe(aspia, "desktop_agent");
desktop_agent += "host/desktop_agent_entry_point.cc";
desktop_agent += "host/desktop_agent.rc";
desktop_agent += core;
auto &client = add_exe(aspia, "client_exe");
client += "client/client_entry_point.cc";
client += "client/client.rc";
client += client_core, qt_base;
}
<commit_msg>[sw] Fix spec build on linux.<commit_after>#pragma sw require header org.sw.demo.google.protobuf.protoc
#pragma sw require header org.sw.demo.qtproject.qt.base.tools.moc-5
#define QT_VERSION "-5"
/*void configure(Build &s)
{
if (s.isConfigSelected("mt"))
{
auto ss = s.createSettings();
ss.Native.LibrariesType = LibraryType::Static;
ss.Native.MT = true;
s.addSettings(ss);
}
}*/
void build(Solution &s)
{
auto &aspia = s.addProject("aspia", "master");
aspia += Git("https://github.com/dchapyshev/aspia", "", "{v}");
constexpr auto cppstd = cpp17;
auto setup_target = [&aspia](auto &t, const String &name, bool add_tests = false, String dir = {}) -> decltype(auto)
{
if (dir.empty())
dir = name;
t += cppstd;
t.Public += "."_idir;
t.setRootDirectory(dir);
t += IncludeDirectory("."s);
t += ".*"_rr;
//
t.AllowEmptyRegexes = true;
// os specific
t -= ".*_win.*"_rr;
t -= ".*_linux.*"_rr;
t -= ".*/linux/.*"_rr;
t -= ".*_pulse.*"_rr;
t -= ".*_mac.*"_rr;
t -= ".*_posix.*"_rr;
t -= ".*_x11.*"_rr;
if (t.getBuildSettings().TargetOS.Type == OSType::Windows)
t += ".*_win.*"_rr;
else if (t.getBuildSettings().TargetOS.isApple())
t += ".*_mac.*"_rr;
else
{
t += ".*_pulse.*"_rr;
t += ".*_linux.*"_rr;
t += ".*/linux/.*"_rr;
t += ".*_x11.*"_rr;
}
if (t.getBuildSettings().TargetOS.Type != OSType::Windows)
t += ".*_posix.*"_rr;
t -= ".*_unittest.*"_rr;
t -= ".*tests.*"_rr;
//
t.AllowEmptyRegexes = false;
// test
if (add_tests)
{
auto &bt = t.addExecutable("test");
bt += cppstd;
bt += FileRegex(dir, ".*_unittest.*", true);
bt += t;
bt += "org.sw.demo.google.googletest.gmock"_dep;
bt += "org.sw.demo.google.googletest.gtest.main"_dep;
t.addTest(bt);
}
return t;
};
auto add_lib = [&aspia, &setup_target](const String &name, bool add_tests = false, String dir = {}) -> decltype(auto)
{
return setup_target(aspia.addStaticLibrary(name), name, add_tests, dir);
};
auto &protocol = aspia.addStaticLibrary("proto");
protocol += "proto/.*\\.proto"_rr;
for (const auto &[p, _] : protocol[FileRegex(protocol.SourceDir / "proto", ".*\\.proto", false)])
{
ProtobufData d;
d.outdir = protocol.BinaryDir / "proto";
d.public_protobuf = true;
d.addIncludeDirectory(protocol.SourceDir / "proto");
gen_protobuf_cpp("org.sw.demo.google.protobuf"_dep, protocol, p, d);
}
auto &base = aspia.addStaticLibrary("base");
base += "third_party/modp_b64/.*\\.[hc]"_rr;
base += "third_party/x11region/.*\\.[hc]"_rr;
base += "third_party/tbb_c_allocator/.*"_rr;
base -= "build/.*"_rr;
setup_target(base, "base", false);
base.Public += "UNICODE"_def;
base.Public += "WIN32_LEAN_AND_MEAN"_def;
base.Public += "NOMINMAX"_def;
base.Public += protocol;
base.Public += "org.sw.demo.qtproject.qt.base.widgets" QT_VERSION ""_dep;
base.Public += "org.sw.demo.qtproject.qt.base.network" QT_VERSION ""_dep;
base.Public += "org.sw.demo.qtproject.qt.base.xml" QT_VERSION ""_dep;
base.Public += "org.sw.demo.boost.align"_dep;
base.Public += "org.sw.demo.imneme.pcg_cpp-master"_dep;
base.Public += "org.sw.demo.chriskohlhoff.asio"_dep;
base.Public += "org.sw.demo.rapidxml"_dep;
base.Public += "org.sw.demo.miloyip.rapidjson"_dep;
base.Public += "org.sw.demo.google.protobuf.protobuf"_dep; // should be protobuf_lite actually?
base.Public += "org.sw.demo.chromium.libyuv-master"_dep;
base.Public += "org.sw.demo.webmproject.vpx"_dep;
base.Public += "org.sw.demo.webmproject.webm"_dep;
base.Public += "org.sw.demo.xiph.opus"_dep;
if (base.getBuildSettings().TargetOS.Type == OSType::Windows)
{
base -= "x11/.*"_rr;
base.Public += "com.Microsoft.Windows.SDK.winrt"_dep;
base +=
"Dbghelp.lib"_slib,
"Mswsock.lib"_slib,
"Avrt.lib"_slib,
"comsuppw.lib"_slib,
"Winspool.lib"_slib,
"Setupapi.lib"_slib
;
}
automoc("org.sw.demo.qtproject.qt.base.tools.moc" QT_VERSION ""_dep, base);
auto &relay = aspia.addExecutable("relay");
relay += cppstd;
relay += "relay/.*"_rr;
relay += base;
auto &router = aspia.addExecutable("router");
router += cppstd;
router += "router/.*"_rr;
router += base;
router += "org.sw.demo.sqlite3"_dep;
auto qt_progs = [](auto &t, const String &name_override = {}, const path &path_override = {})
{
auto name = name_override.empty() ? t.getPackage().getPath().back() : name_override;
automoc("org.sw.demo.qtproject.qt.base.tools.moc" QT_VERSION ""_dep, t);
rcc("org.sw.demo.qtproject.qt.base.tools.rcc" QT_VERSION ""_dep, t, t.SourceDir / path_override / ("resources/" + name + ".qrc"));
qt_uic("org.sw.demo.qtproject.qt.base.tools.uic" QT_VERSION ""_dep, t);
};
auto qt_progs2 = [](auto &t)
{
automoc("org.sw.demo.qtproject.qt.base.tools.moc" QT_VERSION ""_dep, t);
rcc("org.sw.demo.qtproject.qt.base.tools.rcc" QT_VERSION ""_dep, t, t.SourceDir / "ui/resources.qrc");
qt_uic("org.sw.demo.qtproject.qt.base.tools.uic" QT_VERSION ""_dep, t);
};
auto qt_progs_and_tr = [&qt_progs](auto &t, const String &name_override = {}, const path &path_override = {})
{
auto name = name_override.empty() ? t.getPackage().getPath().back() : name_override;
qt_progs(t, name_override, path_override);
// trs
qt_tr("org.sw.demo.qtproject.qt" QT_VERSION ""_dep, t);
t.configureFile(t.SourceDir / path_override / ("translations/" + name + "_translations.qrc"),
t.BinaryDir / (name + "_translations.qrc"), ConfigureFlags::CopyOnly);
rcc("org.sw.demo.qtproject.qt.base.tools.rcc" QT_VERSION ""_dep, t,
t.BinaryDir / (name + "_translations.qrc"))
->working_directory = t.BinaryDir;
};
auto qt_progs_and_tr2 = [&qt_progs2](auto &t)
{
qt_progs2(t);
// trs
qt_tr("org.sw.demo.qtproject.qt" QT_VERSION ""_dep, t);
t.configureFile(t.SourceDir / "ui/translations.qrc",
t.BinaryDir / "translations.qrc", ConfigureFlags::CopyOnly);
rcc("org.sw.demo.qtproject.qt.base.tools.rcc" QT_VERSION ""_dep, t,
t.BinaryDir / "translations.qrc")->working_directory = t.BinaryDir;
};
auto &common = add_lib("common");
if (common.getBuildSettings().TargetOS.Type == OSType::Windows)
{
common -= "file_enumerator_fs.cc";
common.Public += "Shlwapi.lib"_slib;
}
common.Public += base, protocol;
common.Public += "org.sw.demo.openssl.crypto"_dep;
common.Public += "org.sw.demo.qtproject.qt.base.widgets" QT_VERSION ""_dep;
common.Public += "org.sw.demo.qtproject.qt.winextras" QT_VERSION ""_dep;
qt_progs_and_tr(common);
auto &qt_base = add_lib("qt_base");
qt_base.Public += base;
qt_base.Public += "org.sw.demo.qtproject.qt.base.widgets" QT_VERSION ""_dep;
automoc("org.sw.demo.qtproject.qt.base.tools.moc" QT_VERSION ""_dep, qt_base);
qt_translations_rcc("org.sw.demo.qtproject.qt" QT_VERSION ""_dep, aspia, qt_base, "qt_translations.qrc");
auto setup_exe = [](auto &t) -> decltype(auto)
{
if (auto L = t.getSelectedTool()->template as<VisualStudioLinker*>(); L)
L->Subsystem = vs::Subsystem::Windows;
t += "org.sw.demo.qtproject.qt.base.winmain" QT_VERSION ""_dep;
return t;
};
//
auto &client_core = add_lib("client");
client_core.Public += common;
if (client_core.getBuildSettings().TargetOS.Type == OSType::Windows)
client_core.Public += "org.sw.demo.qtproject.qt.base.plugins.printsupport.windows" QT_VERSION ""_dep;
qt_progs_and_tr(client_core);
auto add_exe = [&setup_exe](auto &base, const String &name) -> decltype(auto)
{
return setup_exe(base.addExecutable(name));
};
//
auto &console = add_exe(aspia, "console");
setup_target(console, "console");
console.Public += client_core, qt_base;
if (console.getBuildSettings().TargetOS.Type == OSType::Windows)
{
console.Public += "org.sw.demo.qtproject.qt.base.plugins.platforms.windows" QT_VERSION ""_dep;
console.Public += "org.sw.demo.qtproject.qt.base.plugins.styles.windowsvista" QT_VERSION ""_dep;
}
qt_progs_and_tr(console);
auto &host = aspia.addExecutable("host");
auto &core = host.addSharedLibrary("core");
setup_target(core, "host");
core -= ".*_entry_point.cc"_rr, ".*\\.rc"_rr;
core += "HOST_IMPLEMENTATION"_def;
if (core.getBuildSettings().TargetOS.Type == OSType::Windows)
core.Public += "sas.lib"_slib;
core.Public += common, qt_base;
core.Public += "org.sw.demo.boost.property_tree"_dep;
core.Public += "org.sw.demo.qtproject.qt.base.plugins.platforms.windows" QT_VERSION ""_dep;
core.Public += "org.sw.demo.qtproject.qt.base.plugins.styles.windowsvista" QT_VERSION ""_dep;
qt_progs_and_tr2(core);
setup_exe(host);
host += "host/ui/host_entry_point.cc";
host += "host/ui/host.rc";
host += core;
auto &service = add_exe(host, "service");
service += "host/win/service_entry_point.cc";
service += "host/win/service.rc";
service += core;
auto &desktop_agent = add_exe(aspia, "desktop_agent");
desktop_agent += "host/desktop_agent_entry_point.cc";
desktop_agent += "host/desktop_agent.rc";
desktop_agent += core;
auto &client = add_exe(aspia, "client_exe");
client += "client/client_entry_point.cc";
client += "client/client.rc";
client += client_core, qt_base;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2008-2013 Communi authors
*
* 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.
*/
#include "textbrowser.h"
#include <QApplication>
#include <QScrollBar>
#include <QPainter>
#include <QTextBlock>
#include <QAbstractTextDocumentLayout>
TextBrowser::TextBrowser(QWidget* parent) : QTextBrowser(parent), ub(-1), bud(0)
{
}
QWidget* TextBrowser::buddy() const
{
return bud;
}
void TextBrowser::setBuddy(QWidget* buddy)
{
bud = buddy;
}
int TextBrowser::unseenBlock() const
{
return ub;
}
void TextBrowser::setUnseenBlock(int block)
{
ub = block;
}
void TextBrowser::keyPressEvent(QKeyEvent* event)
{
// for example:
// - Ctrl+C goes to the browser
// - Ctrl+V goes to the buddy
// - Shift+7 ("/") goes to the buddy
switch (event->key()) {
case Qt::Key_Shift:
case Qt::Key_Control:
case Qt::Key_Meta:
case Qt::Key_Alt:
case Qt::Key_AltGr:
break;
default:
if (!event->matches(QKeySequence::Copy)) {
QApplication::sendEvent(bud, event);
bud->setFocus();
return;
}
break;
}
QTextBrowser::keyPressEvent(event);
}
void TextBrowser::resizeEvent(QResizeEvent* event)
{
QTextBrowser::resizeEvent(event);
// http://www.qtsoftware.com/developer/task-tracker/index_html?method=entry&id=240940
QMetaObject::invokeMethod(this, "scrollToBottom", Qt::QueuedConnection);
}
void TextBrowser::scrollToTop()
{
verticalScrollBar()->triggerAction(QScrollBar::SliderToMinimum);
}
void TextBrowser::scrollToBottom()
{
verticalScrollBar()->triggerAction(QScrollBar::SliderToMaximum);
}
void TextBrowser::scrollToNextPage()
{
verticalScrollBar()->triggerAction(QScrollBar::SliderPageStepAdd);
}
void TextBrowser::scrollToPreviousPage()
{
verticalScrollBar()->triggerAction(QScrollBar::SliderPageStepSub);
}
void TextBrowser::paintEvent(QPaintEvent* event)
{
QTextBrowser::paintEvent(event);
QPainter painter(viewport());
QTextBlock block;
if (ub > 0)
block = document()->findBlockByNumber(ub);
if (block.isValid()) {
painter.save();
painter.setPen(Qt::DashLine);
painter.translate(-horizontalScrollBar()->value(), -verticalScrollBar()->value());
QRectF br = document()->documentLayout()->blockBoundingRect(block);
painter.drawLine(br.topLeft(), br.topRight());
painter.restore();
}
QLinearGradient gradient(0, 0, 0, 3);
gradient.setColorAt(0.0, palette().color(QPalette::Dark));
gradient.setColorAt(1.0, Qt::transparent);
painter.fillRect(0, 0, width(), 3, gradient);
}
void TextBrowser::wheelEvent(QWheelEvent* event)
{
#ifdef Q_WS_MACX
// disable cmd+wheel zooming on mac
QAbstractScrollArea::wheelEvent(event);
#else
QTextBrowser::wheelEvent(event);
#endif // Q_WS_MACX
}
<commit_msg>TextBrowser: allow the "select all" key sequence<commit_after>/*
* Copyright (C) 2008-2013 Communi authors
*
* 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.
*/
#include "textbrowser.h"
#include <QApplication>
#include <QScrollBar>
#include <QPainter>
#include <QTextBlock>
#include <QAbstractTextDocumentLayout>
TextBrowser::TextBrowser(QWidget* parent) : QTextBrowser(parent), ub(-1), bud(0)
{
}
QWidget* TextBrowser::buddy() const
{
return bud;
}
void TextBrowser::setBuddy(QWidget* buddy)
{
bud = buddy;
}
int TextBrowser::unseenBlock() const
{
return ub;
}
void TextBrowser::setUnseenBlock(int block)
{
ub = block;
}
void TextBrowser::keyPressEvent(QKeyEvent* event)
{
// for example:
// - Ctrl+C goes to the browser
// - Ctrl+V goes to the buddy
// - Shift+7 ("/") goes to the buddy
switch (event->key()) {
case Qt::Key_Shift:
case Qt::Key_Control:
case Qt::Key_Meta:
case Qt::Key_Alt:
case Qt::Key_AltGr:
break;
default:
if (!event->matches(QKeySequence::Copy) && !event->matches(QKeySequence::SelectAll)) {
QApplication::sendEvent(bud, event);
bud->setFocus();
return;
}
break;
}
QTextBrowser::keyPressEvent(event);
}
void TextBrowser::resizeEvent(QResizeEvent* event)
{
QTextBrowser::resizeEvent(event);
// http://www.qtsoftware.com/developer/task-tracker/index_html?method=entry&id=240940
QMetaObject::invokeMethod(this, "scrollToBottom", Qt::QueuedConnection);
}
void TextBrowser::scrollToTop()
{
verticalScrollBar()->triggerAction(QScrollBar::SliderToMinimum);
}
void TextBrowser::scrollToBottom()
{
verticalScrollBar()->triggerAction(QScrollBar::SliderToMaximum);
}
void TextBrowser::scrollToNextPage()
{
verticalScrollBar()->triggerAction(QScrollBar::SliderPageStepAdd);
}
void TextBrowser::scrollToPreviousPage()
{
verticalScrollBar()->triggerAction(QScrollBar::SliderPageStepSub);
}
void TextBrowser::paintEvent(QPaintEvent* event)
{
QTextBrowser::paintEvent(event);
QPainter painter(viewport());
QTextBlock block;
if (ub > 0)
block = document()->findBlockByNumber(ub);
if (block.isValid()) {
painter.save();
painter.setPen(Qt::DashLine);
painter.translate(-horizontalScrollBar()->value(), -verticalScrollBar()->value());
QRectF br = document()->documentLayout()->blockBoundingRect(block);
painter.drawLine(br.topLeft(), br.topRight());
painter.restore();
}
QLinearGradient gradient(0, 0, 0, 3);
gradient.setColorAt(0.0, palette().color(QPalette::Dark));
gradient.setColorAt(1.0, Qt::transparent);
painter.fillRect(0, 0, width(), 3, gradient);
}
void TextBrowser::wheelEvent(QWheelEvent* event)
{
#ifdef Q_WS_MACX
// disable cmd+wheel zooming on mac
QAbstractScrollArea::wheelEvent(event);
#else
QTextBrowser::wheelEvent(event);
#endif // Q_WS_MACX
}
<|endoftext|>
|
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
*
* This 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. See file COPYING.
*
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <iostream>
#include <string>
using namespace std;
#include "config.h"
#include "mon/MonMap.h"
#include "mon/Monitor.h"
#include "mon/MonitorStore.h"
#include "msg/SimpleMessenger.h"
#include "include/nstring.h"
#include "common/Timer.h"
#include "common/common_init.h"
void usage()
{
cerr << "usage: cmon -i monid [--mon-data=pathtodata] [flags]" << std::endl;
cerr << " --debug_mon n\n";
cerr << " debug monitor level (e.g. 10)\n";
generic_server_usage();
}
int main(int argc, const char **argv)
{
int err;
vector<const char*> args;
argv_to_vec(argc, argv, args);
env_to_vec(args);
configure_daemon_mode();
common_init(args, "mon");
// whoami
char *end;
int whoami = strtol(g_conf.id, &end, 10);
if (*end || end == g_conf.id || whoami < 0) {
cerr << "must specify '-i #' where # is the osd number" << std::endl;
usage();
}
if (!g_conf.mon_data) {
cerr << "must specify '--mon-data=foo' data path" << std::endl;
usage();
}
if (g_conf.clock_tare) g_clock.tare();
MonitorStore store(g_conf.mon_data);
err = store.mount();
if (err < 0) {
cerr << "problem opening monitor store in " << g_conf.mon_data << ": " << strerror(-err) << std::endl;
exit(1);
}
// whoami?
if (!store.exists_bl_ss("whoami")) {
cerr << "mon fs missing 'whoami'" << std::endl;
exit(1);
}
int w = store.get_int("whoami");
if (w != whoami) {
cerr << "monitor data is for mon" << w << ", but you said i was mon" << whoami << std::endl;
exit(1);
}
bufferlist magicbl;
store.get_bl_ss(magicbl, "magic", 0);
nstring magic(magicbl.length()-1, magicbl.c_str()); // ignore trailing \n
if (strcmp(magic.c_str(), CEPH_MON_ONDISK_MAGIC)) {
cerr << "mon fs magic '" << magic << "' != current '" << CEPH_MON_ONDISK_MAGIC << "'" << std::endl;
exit(1);
}
// monmap?
bufferlist mapbl;
store.get_bl_ss(mapbl, "monmap/latest", 0);
if (mapbl.length() == 0) {
cerr << "mon fs missing 'monmap'" << std::endl;
exit(1);
}
MonMap monmap;
monmap.decode(mapbl);
if ((unsigned)whoami >= monmap.size() || whoami < 0) {
cerr << "mon" << whoami << " does not exist in monmap" << std::endl;
exit(1);
}
// bind
cout << "starting mon" << whoami
<< " at " << monmap.get_inst(whoami).addr
<< " from " << g_conf.mon_data << std::endl;
g_my_addr = monmap.get_inst(whoami).addr;
err = rank.bind();
if (err < 0)
return 1;
_dout_create_courtesy_output_symlink("mon", whoami);
// start monitor
Messenger *m = rank.register_entity(entity_name_t::MON(whoami));
m->set_default_send_priority(CEPH_MSG_PRIO_HIGH);
Monitor *mon = new Monitor(whoami, &store, m, &monmap);
rank.start(); // may daemonize
rank.set_policy(entity_name_t::TYPE_MON, Rank::Policy::lossless());
rank.set_policy(entity_name_t::TYPE_MDS, Rank::Policy::lossy_fast_fail());
rank.set_policy(entity_name_t::TYPE_CLIENT, Rank::Policy::lossy_fast_fail());
rank.set_policy(entity_name_t::TYPE_OSD, Rank::Policy::lossy_fast_fail());
rank.set_policy(entity_name_t::TYPE_ADMIN, Rank::Policy::lossy_fast_fail());
mon->init();
rank.wait();
store.umount();
delete mon;
// cd on exit, so that gmon.out (if any) goes into a separate directory for each node.
char s[20];
sprintf(s, "gmon/%d", getpid());
if (mkdir(s, 0755) == 0)
chdir(s);
return 0;
}
<commit_msg>cmon: typo<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
*
* This 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. See file COPYING.
*
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <iostream>
#include <string>
using namespace std;
#include "config.h"
#include "mon/MonMap.h"
#include "mon/Monitor.h"
#include "mon/MonitorStore.h"
#include "msg/SimpleMessenger.h"
#include "include/nstring.h"
#include "common/Timer.h"
#include "common/common_init.h"
void usage()
{
cerr << "usage: cmon -i monid [--mon-data=pathtodata] [flags]" << std::endl;
cerr << " --debug_mon n\n";
cerr << " debug monitor level (e.g. 10)\n";
generic_server_usage();
}
int main(int argc, const char **argv)
{
int err;
vector<const char*> args;
argv_to_vec(argc, argv, args);
env_to_vec(args);
configure_daemon_mode();
common_init(args, "mon");
// whoami
char *end;
int whoami = strtol(g_conf.id, &end, 10);
if (*end || end == g_conf.id || whoami < 0) {
cerr << "must specify '-i #' where # is the mon number" << std::endl;
usage();
}
if (!g_conf.mon_data) {
cerr << "must specify '--mon-data=foo' data path" << std::endl;
usage();
}
if (g_conf.clock_tare) g_clock.tare();
MonitorStore store(g_conf.mon_data);
err = store.mount();
if (err < 0) {
cerr << "problem opening monitor store in " << g_conf.mon_data << ": " << strerror(-err) << std::endl;
exit(1);
}
// whoami?
if (!store.exists_bl_ss("whoami")) {
cerr << "mon fs missing 'whoami'" << std::endl;
exit(1);
}
int w = store.get_int("whoami");
if (w != whoami) {
cerr << "monitor data is for mon" << w << ", but you said i was mon" << whoami << std::endl;
exit(1);
}
bufferlist magicbl;
store.get_bl_ss(magicbl, "magic", 0);
nstring magic(magicbl.length()-1, magicbl.c_str()); // ignore trailing \n
if (strcmp(magic.c_str(), CEPH_MON_ONDISK_MAGIC)) {
cerr << "mon fs magic '" << magic << "' != current '" << CEPH_MON_ONDISK_MAGIC << "'" << std::endl;
exit(1);
}
// monmap?
bufferlist mapbl;
store.get_bl_ss(mapbl, "monmap/latest", 0);
if (mapbl.length() == 0) {
cerr << "mon fs missing 'monmap'" << std::endl;
exit(1);
}
MonMap monmap;
monmap.decode(mapbl);
if ((unsigned)whoami >= monmap.size() || whoami < 0) {
cerr << "mon" << whoami << " does not exist in monmap" << std::endl;
exit(1);
}
// bind
cout << "starting mon" << whoami
<< " at " << monmap.get_inst(whoami).addr
<< " from " << g_conf.mon_data << std::endl;
g_my_addr = monmap.get_inst(whoami).addr;
err = rank.bind();
if (err < 0)
return 1;
_dout_create_courtesy_output_symlink("mon", whoami);
// start monitor
Messenger *m = rank.register_entity(entity_name_t::MON(whoami));
m->set_default_send_priority(CEPH_MSG_PRIO_HIGH);
Monitor *mon = new Monitor(whoami, &store, m, &monmap);
rank.start(); // may daemonize
rank.set_policy(entity_name_t::TYPE_MON, Rank::Policy::lossless());
rank.set_policy(entity_name_t::TYPE_MDS, Rank::Policy::lossy_fast_fail());
rank.set_policy(entity_name_t::TYPE_CLIENT, Rank::Policy::lossy_fast_fail());
rank.set_policy(entity_name_t::TYPE_OSD, Rank::Policy::lossy_fast_fail());
rank.set_policy(entity_name_t::TYPE_ADMIN, Rank::Policy::lossy_fast_fail());
mon->init();
rank.wait();
store.umount();
delete mon;
// cd on exit, so that gmon.out (if any) goes into a separate directory for each node.
char s[20];
sprintf(s, "gmon/%d", getpid());
if (mkdir(s, 0755) == 0)
chdir(s);
return 0;
}
<|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
// This class
#include "grins/error_estimation_factory.h"
// libMesh
#include "libmesh/adjoint_residual_error_estimator.h"
#include "libmesh/getpot.h"
#include "libmesh/patch_recovery_error_estimator.h"
#include "libmesh/qoi_set.h"
namespace GRINS
{
ErrorEstimatorFactory::ErrorEstimatorFactory()
{
return;
}
ErrorEstimatorFactory::~ErrorEstimatorFactory()
{
return;
}
std::tr1::shared_ptr<libMesh::ErrorEstimator> ErrorEstimatorFactory::build( const GetPot& input,
const libMesh::QoISet& qoi_set )
{
std::string estimator_type = input("MeshAdaptivity/estimator_type", "none");
ErrorEstimatorEnum estimator_enum = this->string_to_enum( estimator_type );
std::tr1::shared_ptr<libMesh::ErrorEstimator> error_estimator;
switch( estimator_enum )
{
case(ADJOINT_RESIDUAL):
{
error_estimator.reset( new libMesh::AdjointResidualErrorEstimator );
libMesh::AdjointResidualErrorEstimator* adjoint_error_estimator = libmesh_cast_ptr<libMesh::AdjointResidualErrorEstimator*>( error_estimator.get() );
adjoint_error_estimator->qoi_set() = qoi_set;
libMesh::PatchRecoveryErrorEstimator *p1 = new libMesh::PatchRecoveryErrorEstimator;
adjoint_error_estimator->primal_error_estimator().reset( p1 );
libMesh::PatchRecoveryErrorEstimator *p2 = new libMesh::PatchRecoveryErrorEstimator;
adjoint_error_estimator->dual_error_estimator().reset( p2 );
bool patch_reuse = input( "MeshAdaptivity/patch_reuse", false );
adjoint_error_estimator->primal_error_estimator()->error_norm.set_type( 0, H1_SEMINORM );
p1->set_patch_reuse( patch_reuse );
adjoint_error_estimator->dual_error_estimator()->error_norm.set_type( 0, H1_SEMINORM );
p2->set_patch_reuse( patch_reuse );
}
break;
case(ADJOINT_REFINEMENT):
case(KELLY):
case(PATCH_RECOVERY):
case(WEIGHTED_PATCH_RECOVERY):
case(UNIFORM_REFINEMENT):
{
libmesh_not_implemented();
}
break;
// wat?!
default:
{
libmesh_error();
}
} // switch( estimator_enum )
return error_estimator;
}
ErrorEstimatorFactory::ErrorEstimatorEnum ErrorEstimatorFactory::string_to_enum( const std::string& estimator_type ) const
{
ErrorEstimatorEnum value;
if( estimator_type == std::string("adjoint_residual") )
{
value = ADJOINT_RESIDUAL;
}
else if( estimator_type == std::string("adjoint_refinement") )
{
value = ADJOINT_REFINEMENT;
}
else if( estimator_type == std::string("kelly") )
{
value = KELLY;
}
else if( estimator_type == std::string("patch_recovery") )
{
value = PATCH_RECOVERY;
}
else if( estimator_type == std::string("weighted_patch_recovery") )
{
value = WEIGHTED_PATCH_RECOVERY;
}
else if( estimator_type == std::string("uniform_refinement") )
{
value = UNIFORM_REFINEMENT;
}
else
{
std::cerr << "Error: Invalid error estimator type " << estimator_type << std::endl
<< "Valid error estimator types are: adjoint_residual" << std::endl
<< " adjoint_refinement" << std::endl
<< " kelly" << std::endl
<< " patch_recovery" << std::endl
<< " weighted_patch_recovery" << std::endl
<< " uniform_refinement" << std::endl;
libmesh_error();
}
return value;
}
} // namespace GRINS
<commit_msg>Add Kelly and PatchRecover error estimators.<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
// This class
#include "grins/error_estimation_factory.h"
// libMesh
#include "libmesh/adjoint_residual_error_estimator.h"
#include "libmesh/getpot.h"
#include "libmesh/patch_recovery_error_estimator.h"
#include "libmesh/qoi_set.h"
#include "libmesh/kelly_error_estimator.h"
namespace GRINS
{
ErrorEstimatorFactory::ErrorEstimatorFactory()
{
return;
}
ErrorEstimatorFactory::~ErrorEstimatorFactory()
{
return;
}
std::tr1::shared_ptr<libMesh::ErrorEstimator> ErrorEstimatorFactory::build( const GetPot& input,
const libMesh::QoISet& qoi_set )
{
std::string estimator_type = input("MeshAdaptivity/estimator_type", "none");
ErrorEstimatorEnum estimator_enum = this->string_to_enum( estimator_type );
std::tr1::shared_ptr<libMesh::ErrorEstimator> error_estimator;
switch( estimator_enum )
{
case(ADJOINT_RESIDUAL):
{
error_estimator.reset( new libMesh::AdjointResidualErrorEstimator );
libMesh::AdjointResidualErrorEstimator* adjoint_error_estimator = libmesh_cast_ptr<libMesh::AdjointResidualErrorEstimator*>( error_estimator.get() );
adjoint_error_estimator->qoi_set() = qoi_set;
libMesh::PatchRecoveryErrorEstimator *p1 = new libMesh::PatchRecoveryErrorEstimator;
adjoint_error_estimator->primal_error_estimator().reset( p1 );
libMesh::PatchRecoveryErrorEstimator *p2 = new libMesh::PatchRecoveryErrorEstimator;
adjoint_error_estimator->dual_error_estimator().reset( p2 );
bool patch_reuse = input( "MeshAdaptivity/patch_reuse", false );
adjoint_error_estimator->primal_error_estimator()->error_norm.set_type( 0, H1_SEMINORM );
p1->set_patch_reuse( patch_reuse );
adjoint_error_estimator->dual_error_estimator()->error_norm.set_type( 0, H1_SEMINORM );
p2->set_patch_reuse( patch_reuse );
}
break;
case(KELLY):
{
error_estimator.reset( new libMesh::KellyErrorEstimator );
}
break;
case(PATCH_RECOVERY):
{
error_estimator.reset( new libMesh::PatchRecoveryErrorEstimator );
}
break;
case(ADJOINT_REFINEMENT):
case(WEIGHTED_PATCH_RECOVERY):
case(UNIFORM_REFINEMENT):
{
libmesh_not_implemented();
}
break;
// wat?!
default:
{
libmesh_error();
}
} // switch( estimator_enum )
return error_estimator;
}
ErrorEstimatorFactory::ErrorEstimatorEnum ErrorEstimatorFactory::string_to_enum( const std::string& estimator_type ) const
{
ErrorEstimatorEnum value;
if( estimator_type == std::string("adjoint_residual") )
{
value = ADJOINT_RESIDUAL;
}
else if( estimator_type == std::string("adjoint_refinement") )
{
value = ADJOINT_REFINEMENT;
}
else if( estimator_type == std::string("kelly") )
{
value = KELLY;
}
else if( estimator_type == std::string("patch_recovery") )
{
value = PATCH_RECOVERY;
}
else if( estimator_type == std::string("weighted_patch_recovery") )
{
value = WEIGHTED_PATCH_RECOVERY;
}
else if( estimator_type == std::string("uniform_refinement") )
{
value = UNIFORM_REFINEMENT;
}
else
{
std::cerr << "Error: Invalid error estimator type " << estimator_type << std::endl
<< "Valid error estimator types are: adjoint_residual" << std::endl
<< " adjoint_refinement" << std::endl
<< " kelly" << std::endl
<< " patch_recovery" << std::endl
<< " weighted_patch_recovery" << std::endl
<< " uniform_refinement" << std::endl;
libmesh_error();
}
return value;
}
} // namespace GRINS
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include <string>
#include "webrtc/system_wrappers/interface/sleep.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/voice_engine/test/auto_test/fixtures/after_initialization_fixture.h"
namespace webrtc {
namespace {
const int16_t kLimiterHeadroom = 29204; // == -1 dbFS
const int16_t kInt16Max = 0x7fff;
const int kSampleRateHz = 16000;
const int kTestDurationMs = 3000;
} // namespace
class MixingTest : public AfterInitializationFixture {
protected:
MixingTest()
: output_filename_(test::OutputPath() + "mixing_test_output.pcm") {
}
void SetUp() {
transport_ = new LoopBackTransport(voe_network_);
}
void TearDown() {
delete transport_;
}
// Creates and mixes |num_remote_streams| which play a file "as microphone"
// with |num_local_streams| which play a file "locally", using a constant
// amplitude of |input_value|. The local streams manifest as "anonymous"
// mixing participants, meaning they will be mixed regardless of the number
// of participants. (A stream is a VoiceEngine "channel").
//
// The mixed output is verified to always fall between |max_output_value| and
// |min_output_value|, after a startup phase.
//
// |num_remote_streams_using_mono| of the remote streams use mono, with the
// remainder using stereo.
void RunMixingTest(int num_remote_streams,
int num_local_streams,
int num_remote_streams_using_mono,
bool real_audio,
int16_t input_value,
int16_t max_output_value,
int16_t min_output_value) {
ASSERT_LE(num_remote_streams_using_mono, num_remote_streams);
if (real_audio) {
input_filename_ = test::ResourcePath("voice_engine/audio_long16", "pcm");
} else {
input_filename_ = test::OutputPath() + "mixing_test_input.pcm";
GenerateInputFile(input_value);
}
std::vector<int> local_streams(num_local_streams);
for (size_t i = 0; i < local_streams.size(); ++i) {
local_streams[i] = voe_base_->CreateChannel();
EXPECT_NE(-1, local_streams[i]);
}
StartLocalStreams(local_streams);
TEST_LOG("Playing %d local streams.\n", num_local_streams);
std::vector<int> remote_streams(num_remote_streams);
for (size_t i = 0; i < remote_streams.size(); ++i) {
remote_streams[i] = voe_base_->CreateChannel();
EXPECT_NE(-1, remote_streams[i]);
}
StartRemoteStreams(remote_streams, num_remote_streams_using_mono);
TEST_LOG("Playing %d remote streams.\n", num_remote_streams);
// Give it plenty of time to get started.
SleepMs(1000);
// Start recording the mixed output and wait.
EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1 /* record meeting */,
output_filename_.c_str()));
SleepMs(kTestDurationMs);
EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1));
StopLocalStreams(local_streams);
StopRemoteStreams(remote_streams);
if (!real_audio) {
VerifyMixedOutput(max_output_value, min_output_value);
}
}
private:
// Generate input file with constant values equal to |input_value|. The file
// will be twice the duration of the test.
void GenerateInputFile(int16_t input_value) {
FILE* input_file = fopen(input_filename_.c_str(), "wb");
ASSERT_TRUE(input_file != NULL);
for (int i = 0; i < kSampleRateHz / 1000 * (kTestDurationMs * 2); i++) {
ASSERT_EQ(1u, fwrite(&input_value, sizeof(input_value), 1, input_file));
}
ASSERT_EQ(0, fclose(input_file));
}
void VerifyMixedOutput(int16_t max_output_value, int16_t min_output_value) {
// Verify the mixed output.
FILE* output_file = fopen(output_filename_.c_str(), "rb");
ASSERT_TRUE(output_file != NULL);
int16_t output_value = 0;
int samples_read = 0;
while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) {
samples_read++;
std::ostringstream trace_stream;
trace_stream << samples_read << " samples read";
SCOPED_TRACE(trace_stream.str());
EXPECT_LE(output_value, max_output_value);
EXPECT_GE(output_value, min_output_value);
}
// Ensure we've at least recorded half as much file as the duration of the
// test. We have to use a relaxed tolerance here due to filesystem flakiness
// on the bots.
ASSERT_GE((samples_read * 1000.0) / kSampleRateHz, 0.5 * kTestDurationMs);
// Ensure we read the entire file.
ASSERT_NE(0, feof(output_file));
ASSERT_EQ(0, fclose(output_file));
}
// Start up local streams ("anonymous" participants).
void StartLocalStreams(const std::vector<int>& streams) {
for (size_t i = 0; i < streams.size(); ++i) {
EXPECT_EQ(0, voe_base_->StartPlayout(streams[i]));
EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(streams[i],
input_filename_.c_str(), true));
}
}
void StopLocalStreams(const std::vector<int>& streams) {
for (size_t i = 0; i < streams.size(); ++i) {
EXPECT_EQ(0, voe_base_->StopPlayout(streams[i]));
EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i]));
}
}
// Start up remote streams ("normal" participants).
void StartRemoteStreams(const std::vector<int>& streams,
int num_remote_streams_using_mono) {
// Use L16 at 16kHz to minimize distortion (file recording is 16kHz and
// resampling will cause distortion).
CodecInst codec_inst;
strcpy(codec_inst.plname, "L16");
codec_inst.channels = 1;
codec_inst.plfreq = kSampleRateHz;
codec_inst.pltype = 105;
codec_inst.pacsize = codec_inst.plfreq / 100;
codec_inst.rate = codec_inst.plfreq * sizeof(int16_t) * 8; // 8 bits/byte.
for (int i = 0; i < num_remote_streams_using_mono; ++i) {
// Add some delay between starting up the channels in order to give them
// different energies in the "real audio" test and hopefully exercise
// more code paths.
SleepMs(50);
StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i);
}
// The remainder of the streams will use stereo.
codec_inst.channels = 2;
codec_inst.pltype++;
for (size_t i = num_remote_streams_using_mono; i < streams.size(); ++i) {
StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i);
}
}
// Start up a single remote stream.
void StartRemoteStream(int stream, const CodecInst& codec_inst, int port) {
EXPECT_EQ(0, voe_codec_->SetRecPayloadType(stream, codec_inst));
EXPECT_EQ(0, voe_network_->RegisterExternalTransport(stream, *transport_));
EXPECT_EQ(0, voe_base_->StartReceive(stream));
EXPECT_EQ(0, voe_base_->StartPlayout(stream));
EXPECT_EQ(0, voe_codec_->SetSendCodec(stream, codec_inst));
EXPECT_EQ(0, voe_base_->StartSend(stream));
EXPECT_EQ(0, voe_file_->StartPlayingFileAsMicrophone(stream,
input_filename_.c_str(), true));
}
void StopRemoteStreams(const std::vector<int>& streams) {
for (size_t i = 0; i < streams.size(); ++i) {
EXPECT_EQ(0, voe_base_->StopSend(streams[i]));
EXPECT_EQ(0, voe_base_->StopPlayout(streams[i]));
EXPECT_EQ(0, voe_base_->StopReceive(streams[i]));
EXPECT_EQ(0, voe_network_->DeRegisterExternalTransport(streams[i]));
EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i]));
}
}
std::string input_filename_;
const std::string output_filename_;
LoopBackTransport* transport_;
};
// This test has no verification, but exercises additional code paths in a
// somewhat more realistic scenario using real audio. It can at least hunt for
// asserts and crashes.
TEST_F(MixingTest, MixManyChannelsForStress) {
RunMixingTest(10, 0, 10, true, 0, 0, 0);
}
// These tests assume a maximum of three mixed participants. We typically allow
// a +/- 10% range around the expected output level to account for distortion
// from coding and processing in the loopback chain.
TEST_F(MixingTest, FourChannelsWithOnlyThreeMixed) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 3;
RunMixingTest(4, 0, 4, false, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
// Ensure the mixing saturation protection is working. We can do this because
// the mixing limiter is given some headroom, so the expected output is less
// than full scale.
TEST_F(MixingTest, VerifySaturationProtection) {
const int16_t kInputValue = 20000;
const int16_t kExpectedOutput = kLimiterHeadroom;
// If this isn't satisfied, we're not testing anything.
ASSERT_GT(kInputValue * 3, kInt16Max);
ASSERT_LT(1.1 * kExpectedOutput, kInt16Max);
RunMixingTest(3, 0, 3, false, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
TEST_F(MixingTest, SaturationProtectionHasNoEffectOnOneChannel) {
const int16_t kInputValue = kInt16Max;
const int16_t kExpectedOutput = kInt16Max;
// If this isn't satisfied, we're not testing anything.
ASSERT_GT(0.95 * kExpectedOutput, kLimiterHeadroom);
// Tighter constraints are required here to properly test this.
RunMixingTest(1, 0, 1, false, kInputValue, kExpectedOutput,
0.95 * kExpectedOutput);
}
TEST_F(MixingTest, VerifyAnonymousAndNormalParticipantMixing) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 2;
RunMixingTest(1, 1, 1, false, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
TEST_F(MixingTest, AnonymousParticipantsAreAlwaysMixed) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 4;
RunMixingTest(3, 1, 3, false, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
TEST_F(MixingTest, VerifyStereoAndMonoMixing) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 2;
RunMixingTest(2, 0, 1, false, kInputValue, 1.1 * kExpectedOutput,
// Lower than 0.9 due to observed flakiness on bots.
0.8 * kExpectedOutput);
}
} // namespace webrtc
<commit_msg>Reduce flakiness of voe_auto_test MixingTest by checking dumped audio size<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include <string>
#include "webrtc/system_wrappers/interface/sleep.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/voice_engine/test/auto_test/fixtures/after_initialization_fixture.h"
namespace webrtc {
namespace {
const int16_t kLimiterHeadroom = 29204; // == -1 dbFS
const int16_t kInt16Max = 0x7fff;
const int kSampleRateHz = 16000;
const int kTestDurationMs = 3000;
} // namespace
class MixingTest : public AfterInitializationFixture {
protected:
MixingTest()
: output_filename_(test::OutputPath() + "mixing_test_output.pcm") {
}
void SetUp() {
transport_ = new LoopBackTransport(voe_network_);
}
void TearDown() {
delete transport_;
}
// Creates and mixes |num_remote_streams| which play a file "as microphone"
// with |num_local_streams| which play a file "locally", using a constant
// amplitude of |input_value|. The local streams manifest as "anonymous"
// mixing participants, meaning they will be mixed regardless of the number
// of participants. (A stream is a VoiceEngine "channel").
//
// The mixed output is verified to always fall between |max_output_value| and
// |min_output_value|, after a startup phase.
//
// |num_remote_streams_using_mono| of the remote streams use mono, with the
// remainder using stereo.
void RunMixingTest(int num_remote_streams,
int num_local_streams,
int num_remote_streams_using_mono,
bool real_audio,
int16_t input_value,
int16_t max_output_value,
int16_t min_output_value) {
ASSERT_LE(num_remote_streams_using_mono, num_remote_streams);
if (real_audio) {
input_filename_ = test::ResourcePath("voice_engine/audio_long16", "pcm");
} else {
input_filename_ = test::OutputPath() + "mixing_test_input.pcm";
GenerateInputFile(input_value);
}
std::vector<int> local_streams(num_local_streams);
for (size_t i = 0; i < local_streams.size(); ++i) {
local_streams[i] = voe_base_->CreateChannel();
EXPECT_NE(-1, local_streams[i]);
}
StartLocalStreams(local_streams);
TEST_LOG("Playing %d local streams.\n", num_local_streams);
std::vector<int> remote_streams(num_remote_streams);
for (size_t i = 0; i < remote_streams.size(); ++i) {
remote_streams[i] = voe_base_->CreateChannel();
EXPECT_NE(-1, remote_streams[i]);
}
StartRemoteStreams(remote_streams, num_remote_streams_using_mono);
TEST_LOG("Playing %d remote streams.\n", num_remote_streams);
// Give it plenty of time to get started.
SleepMs(1000);
// Start recording the mixed output and wait.
EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1 /* record meeting */,
output_filename_.c_str()));
SleepMs(kTestDurationMs);
while (GetFileDurationMs(output_filename_.c_str()) < kTestDurationMs) {
SleepMs(200);
}
EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1));
StopLocalStreams(local_streams);
StopRemoteStreams(remote_streams);
if (!real_audio) {
VerifyMixedOutput(max_output_value, min_output_value);
}
}
private:
// Generate input file with constant values equal to |input_value|. The file
// will be twice the duration of the test.
void GenerateInputFile(int16_t input_value) {
FILE* input_file = fopen(input_filename_.c_str(), "wb");
ASSERT_TRUE(input_file != NULL);
for (int i = 0; i < kSampleRateHz / 1000 * (kTestDurationMs * 2); i++) {
ASSERT_EQ(1u, fwrite(&input_value, sizeof(input_value), 1, input_file));
}
ASSERT_EQ(0, fclose(input_file));
}
void VerifyMixedOutput(int16_t max_output_value, int16_t min_output_value) {
// Verify the mixed output.
FILE* output_file = fopen(output_filename_.c_str(), "rb");
ASSERT_TRUE(output_file != NULL);
int16_t output_value = 0;
int samples_read = 0;
while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) {
samples_read++;
std::ostringstream trace_stream;
trace_stream << samples_read << " samples read";
SCOPED_TRACE(trace_stream.str());
EXPECT_LE(output_value, max_output_value);
EXPECT_GE(output_value, min_output_value);
}
// Ensure we've at least recorded half as much file as the duration of the
// test. We have to use a relaxed tolerance here due to filesystem flakiness
// on the bots.
ASSERT_GE((samples_read * 1000.0) / kSampleRateHz, kTestDurationMs);
// Ensure we read the entire file.
ASSERT_NE(0, feof(output_file));
ASSERT_EQ(0, fclose(output_file));
}
// Start up local streams ("anonymous" participants).
void StartLocalStreams(const std::vector<int>& streams) {
for (size_t i = 0; i < streams.size(); ++i) {
EXPECT_EQ(0, voe_base_->StartPlayout(streams[i]));
EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(streams[i],
input_filename_.c_str(), true));
}
}
void StopLocalStreams(const std::vector<int>& streams) {
for (size_t i = 0; i < streams.size(); ++i) {
EXPECT_EQ(0, voe_base_->StopPlayout(streams[i]));
EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i]));
}
}
// Start up remote streams ("normal" participants).
void StartRemoteStreams(const std::vector<int>& streams,
int num_remote_streams_using_mono) {
// Use L16 at 16kHz to minimize distortion (file recording is 16kHz and
// resampling will cause distortion).
CodecInst codec_inst;
strcpy(codec_inst.plname, "L16");
codec_inst.channels = 1;
codec_inst.plfreq = kSampleRateHz;
codec_inst.pltype = 105;
codec_inst.pacsize = codec_inst.plfreq / 100;
codec_inst.rate = codec_inst.plfreq * sizeof(int16_t) * 8; // 8 bits/byte.
for (int i = 0; i < num_remote_streams_using_mono; ++i) {
// Add some delay between starting up the channels in order to give them
// different energies in the "real audio" test and hopefully exercise
// more code paths.
SleepMs(50);
StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i);
}
// The remainder of the streams will use stereo.
codec_inst.channels = 2;
codec_inst.pltype++;
for (size_t i = num_remote_streams_using_mono; i < streams.size(); ++i) {
StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i);
}
}
// Start up a single remote stream.
void StartRemoteStream(int stream, const CodecInst& codec_inst, int port) {
EXPECT_EQ(0, voe_codec_->SetRecPayloadType(stream, codec_inst));
EXPECT_EQ(0, voe_network_->RegisterExternalTransport(stream, *transport_));
EXPECT_EQ(0, voe_base_->StartReceive(stream));
EXPECT_EQ(0, voe_base_->StartPlayout(stream));
EXPECT_EQ(0, voe_codec_->SetSendCodec(stream, codec_inst));
EXPECT_EQ(0, voe_base_->StartSend(stream));
EXPECT_EQ(0, voe_file_->StartPlayingFileAsMicrophone(stream,
input_filename_.c_str(), true));
}
void StopRemoteStreams(const std::vector<int>& streams) {
for (size_t i = 0; i < streams.size(); ++i) {
EXPECT_EQ(0, voe_base_->StopSend(streams[i]));
EXPECT_EQ(0, voe_base_->StopPlayout(streams[i]));
EXPECT_EQ(0, voe_base_->StopReceive(streams[i]));
EXPECT_EQ(0, voe_network_->DeRegisterExternalTransport(streams[i]));
EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i]));
}
}
int GetFileDurationMs(const char* file_name) {
FILE* fid = fopen(file_name, "rb");
EXPECT_FALSE(fid == NULL);
fseek(fid, 0, SEEK_END);
int size = ftell(fid);
EXPECT_NE(-1, size);
fclose(fid);
// Divided by 2 due to 2 bytes/sample.
return size * 1000 / kSampleRateHz / 2;
}
std::string input_filename_;
const std::string output_filename_;
LoopBackTransport* transport_;
};
// This test has no verification, but exercises additional code paths in a
// somewhat more realistic scenario using real audio. It can at least hunt for
// asserts and crashes.
TEST_F(MixingTest, MixManyChannelsForStress) {
RunMixingTest(10, 0, 10, true, 0, 0, 0);
}
// These tests assume a maximum of three mixed participants. We typically allow
// a +/- 10% range around the expected output level to account for distortion
// from coding and processing in the loopback chain.
TEST_F(MixingTest, FourChannelsWithOnlyThreeMixed) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 3;
RunMixingTest(4, 0, 4, false, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
// Ensure the mixing saturation protection is working. We can do this because
// the mixing limiter is given some headroom, so the expected output is less
// than full scale.
TEST_F(MixingTest, VerifySaturationProtection) {
const int16_t kInputValue = 20000;
const int16_t kExpectedOutput = kLimiterHeadroom;
// If this isn't satisfied, we're not testing anything.
ASSERT_GT(kInputValue * 3, kInt16Max);
ASSERT_LT(1.1 * kExpectedOutput, kInt16Max);
RunMixingTest(3, 0, 3, false, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
TEST_F(MixingTest, SaturationProtectionHasNoEffectOnOneChannel) {
const int16_t kInputValue = kInt16Max;
const int16_t kExpectedOutput = kInt16Max;
// If this isn't satisfied, we're not testing anything.
ASSERT_GT(0.95 * kExpectedOutput, kLimiterHeadroom);
// Tighter constraints are required here to properly test this.
RunMixingTest(1, 0, 1, false, kInputValue, kExpectedOutput,
0.95 * kExpectedOutput);
}
TEST_F(MixingTest, VerifyAnonymousAndNormalParticipantMixing) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 2;
RunMixingTest(1, 1, 1, false, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
TEST_F(MixingTest, AnonymousParticipantsAreAlwaysMixed) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 4;
RunMixingTest(3, 1, 3, false, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
TEST_F(MixingTest, VerifyStereoAndMonoMixing) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 2;
RunMixingTest(2, 0, 1, false, kInputValue, 1.1 * kExpectedOutput,
// Lower than 0.9 due to observed flakiness on bots.
0.8 * kExpectedOutput);
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>#pragma once
// prints matrix to stdout in row-major order
template <typename T, size_t N, size_t M>
void print(const tmat<T, N, M>& m);
<commit_msg>why would I want this<commit_after>#pragma once
// prints matrix to stdout in column-major order
template <typename T, size_t N, size_t M>
void print(const tmat<T, N, M>& m);
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Luke San Antonio
* All rights reserved.
*/
#pragma once
#include <utility> // for std::move
namespace survive
{
template <class T>
struct Maybe_Owned
{
template <class... Args>
Maybe_Owned(Args&&... args) noexcept;
Maybe_Owned(T&& t) noexcept;
Maybe_Owned(T* t = nullptr) noexcept;
template <class R>
Maybe_Owned(Maybe_Owned<R>&&) noexcept;
Maybe_Owned(Maybe_Owned const&) noexcept = delete;
template <class R>
Maybe_Owned& operator=(Maybe_Owned<R>&&) noexcept;
Maybe_Owned& operator=(Maybe_Owned const&&) noexcept = delete;
~Maybe_Owned() noexcept;
void set_owned(T&& t) noexcept;
void set_pointer(T* t) noexcept;
T const* get() const noexcept;
T* get() noexcept;
T&& unwrap() noexcept;
T const* operator->() const noexcept;
T* operator->() noexcept;
T const& operator*() const noexcept;
T& operator*() noexcept;
operator bool() const noexcept;
bool is_owned() const noexcept;
bool is_pointer() const noexcept;
private:
bool owned_ = false;
T* ptr_ = nullptr;
};
template <class T>
template <class... Args>
Maybe_Owned<T>::Maybe_Owned(Args&&... args) noexcept
: owned_(true), ptr_(new T{std::forward<Args>(args)...}) {}
template <class T>
Maybe_Owned<T>::Maybe_Owned(T&& t) noexcept
: owned_(true), ptr_(new T(std::move(t))) {}
template <class T>
Maybe_Owned<T>::Maybe_Owned(T* t) noexcept : owned_(false), ptr_(t) {}
template <class T>
Maybe_Owned<T>::~Maybe_Owned() noexcept
{
if(owned_) delete ptr_;
}
template <class T>
template <class R>
Maybe_Owned<T>::Maybe_Owned(Maybe_Owned<R>&& mo1) noexcept
: owned_(mo1.owned_), ptr_(mo1.ptr_)
{
mo1.owned_ = false;
// We don't need to null the pointer since setting the owned value to false
// should suffice in preventing this other maybe-owned from deleting its
// pointer. Nonetheless:
mo1.ptr_ = nullptr;
}
template <class T>
template <class R>
Maybe_Owned<T>& Maybe_Owned<T>::operator=(Maybe_Owned<R>&& mo1) noexcept
{
owned_ = mo1.owned_;
ptr_ = mo1.ptr_;
mo1.owned_ = false;
mo1.ptr_ = nullptr;
}
template <class T>
void Maybe_Owned<T>::set_owned(T&& t) noexcept
{
owned_ = true;
ptr_ = new T(std::move(t));
}
template <class T>
void Maybe_Owned<T>::set_pointer(T* t) noexcept
{
owned_ = false;
ptr_ = t;
}
template <class T>
T const* Maybe_Owned<T>::get() const noexcept
{
return ptr_;
}
template <class T>
T* Maybe_Owned<T>::get() noexcept
{
return ptr_;
}
template <class T>
T&& Maybe_Owned<T>::unwrap() noexcept
{
owned_ = false;
T&& old_t = std::move(*ptr_);
ptr_ = nullptr;
return old_t;
}
template <class T>
T const* Maybe_Owned<T>::operator->() const noexcept
{
return ptr_;
}
template <class T>
T* Maybe_Owned<T>::operator->() noexcept
{
return ptr_;
}
template <class T>
T const& Maybe_Owned<T>::operator*() const noexcept
{
return *ptr_;
}
template <class T>
T& Maybe_Owned<T>::operator*() noexcept
{
return *ptr_;
}
template <class T>
bool Maybe_Owned<T>::is_owned() const noexcept
{
return owned_;
}
template <class T>
bool Maybe_Owned<T>::is_pointer() const noexcept
{
return !owned_;
}
template <class T>
Maybe_Owned<T>::operator bool() const noexcept
{
return get();
}
}
<commit_msg>Fixed an compile error not caught cause template instantiation.<commit_after>/*
* Copyright (C) 2014 Luke San Antonio
* All rights reserved.
*/
#pragma once
#include <utility> // for std::move
namespace survive
{
template <class T>
struct Maybe_Owned
{
template <class... Args>
Maybe_Owned(Args&&... args) noexcept;
Maybe_Owned(T&& t) noexcept;
Maybe_Owned(T* t = nullptr) noexcept;
template <class R>
Maybe_Owned(Maybe_Owned<R>&&) noexcept;
Maybe_Owned(Maybe_Owned const&) noexcept = delete;
template <class R>
Maybe_Owned& operator=(Maybe_Owned<R>&&) noexcept;
Maybe_Owned& operator=(Maybe_Owned const&&) noexcept = delete;
~Maybe_Owned() noexcept;
void set_owned(T&& t) noexcept;
void set_pointer(T* t) noexcept;
T const* get() const noexcept;
T* get() noexcept;
T&& unwrap() noexcept;
T const* operator->() const noexcept;
T* operator->() noexcept;
T const& operator*() const noexcept;
T& operator*() noexcept;
operator bool() const noexcept;
bool is_owned() const noexcept;
bool is_pointer() const noexcept;
private:
bool owned_ = false;
T* ptr_ = nullptr;
};
template <class T>
template <class... Args>
Maybe_Owned<T>::Maybe_Owned(Args&&... args) noexcept
: owned_(true), ptr_(new T{std::forward<Args>(args)...}) {}
template <class T>
Maybe_Owned<T>::Maybe_Owned(T&& t) noexcept
: owned_(true), ptr_(new T(std::move(t))) {}
template <class T>
Maybe_Owned<T>::Maybe_Owned(T* t) noexcept : owned_(false), ptr_(t) {}
template <class T>
Maybe_Owned<T>::~Maybe_Owned() noexcept
{
if(owned_) delete ptr_;
}
template <class T>
template <class R>
Maybe_Owned<T>::Maybe_Owned(Maybe_Owned<R>&& mo1) noexcept
: owned_(mo1.owned_), ptr_(mo1.ptr_)
{
mo1.owned_ = false;
// We don't need to null the pointer since setting the owned value to false
// should suffice in preventing this other maybe-owned from deleting its
// pointer. Nonetheless:
mo1.ptr_ = nullptr;
}
template <class T>
template <class R>
Maybe_Owned<T>& Maybe_Owned<T>::operator=(Maybe_Owned<R>&& mo1) noexcept
{
owned_ = mo1.owned_;
ptr_ = mo1.ptr_;
mo1.owned_ = false;
mo1.ptr_ = nullptr;
}
template <class T>
void Maybe_Owned<T>::set_owned(T&& t) noexcept
{
owned_ = true;
ptr_ = new T(std::move(t));
}
template <class T>
void Maybe_Owned<T>::set_pointer(T* t) noexcept
{
owned_ = false;
ptr_ = t;
}
template <class T>
T const* Maybe_Owned<T>::get() const noexcept
{
return ptr_;
}
template <class T>
T* Maybe_Owned<T>::get() noexcept
{
return ptr_;
}
template <class T>
T&& Maybe_Owned<T>::unwrap() noexcept
{
owned_ = false;
T&& old_t = std::move(*ptr_);
ptr_ = nullptr;
return std::move(old_t);
}
template <class T>
T const* Maybe_Owned<T>::operator->() const noexcept
{
return ptr_;
}
template <class T>
T* Maybe_Owned<T>::operator->() noexcept
{
return ptr_;
}
template <class T>
T const& Maybe_Owned<T>::operator*() const noexcept
{
return *ptr_;
}
template <class T>
T& Maybe_Owned<T>::operator*() noexcept
{
return *ptr_;
}
template <class T>
bool Maybe_Owned<T>::is_owned() const noexcept
{
return owned_;
}
template <class T>
bool Maybe_Owned<T>::is_pointer() const noexcept
{
return !owned_;
}
template <class T>
Maybe_Owned<T>::operator bool() const noexcept
{
return get();
}
}
<|endoftext|>
|
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "INSFVMomentumDiffusion.h"
#include "INSFVRhieChowInterpolator.h"
#include "NS.h"
#include "SystemBase.h"
registerMooseObject("NavierStokesApp", INSFVMomentumDiffusion);
InputParameters
INSFVMomentumDiffusion::validParams()
{
auto params = INSFVFluxKernel::validParams();
params.addRequiredParam<MooseFunctorName>(NS::mu, "The viscosity");
params.addClassDescription(
"Implements the Laplace form of the viscous stress in the Navier-Stokes equation.");
params.set<unsigned short>("ghost_layers") = 2;
return params;
}
INSFVMomentumDiffusion::INSFVMomentumDiffusion(const InputParameters & params)
: INSFVFluxKernel(params), _mu(getFunctor<ADReal>(NS::mu))
{
}
ADReal
INSFVMomentumDiffusion::computeStrongResidual()
{
const auto face = Moose::FV::makeCDFace(*_face_info, faceArgSubdomains());
const auto dudn = gradUDotNormal();
const auto face_mu = _mu(face);
if (_face_type == FaceInfo::VarFaceNeighbors::ELEM ||
_face_type == FaceInfo::VarFaceNeighbors::BOTH)
{
const auto dof_number = _face_info->elem().dof_number(_sys.number(), _var.number(), 0);
// A gradient is a linear combination of degrees of freedom so it's safe to straight-up index
// into the derivatives vector at the dof we care about
_ae = dudn.derivatives()[dof_number];
_ae *= -face_mu;
}
if (_face_type == FaceInfo::VarFaceNeighbors::NEIGHBOR ||
_face_type == FaceInfo::VarFaceNeighbors::BOTH)
{
const auto dof_number = _face_info->neighbor().dof_number(_sys.number(), _var.number(), 0);
_an = dudn.derivatives()[dof_number];
_an *= face_mu;
}
return -face_mu * dudn;
}
void
INSFVMomentumDiffusion::gatherRCData(const FaceInfo & fi)
{
if (skipForBoundary(fi))
return;
_face_info = &fi;
_normal = fi.normal();
_face_type = fi.faceType(_var.name());
processResidual(computeStrongResidual() * (fi.faceArea() * fi.faceCoord()));
if (_face_type == FaceInfo::VarFaceNeighbors::ELEM ||
_face_type == FaceInfo::VarFaceNeighbors::BOTH)
_rc_uo.addToA(&fi.elem(), _index, _ae * (fi.faceArea() * fi.faceCoord()));
if (_face_type == FaceInfo::VarFaceNeighbors::NEIGHBOR ||
_face_type == FaceInfo::VarFaceNeighbors::BOTH)
_rc_uo.addToA(fi.neighborPtr(), _index, _an * (fi.faceArea() * fi.faceCoord()));
}
<commit_msg>Have three ghosting layers from INSFVMomentumDiffusion for skew<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "INSFVMomentumDiffusion.h"
#include "INSFVRhieChowInterpolator.h"
#include "NS.h"
#include "SystemBase.h"
#include "RelationshipManager.h"
#include "Factory.h"
registerMooseObject("NavierStokesApp", INSFVMomentumDiffusion);
InputParameters
INSFVMomentumDiffusion::validParams()
{
auto params = INSFVFluxKernel::validParams();
params.addRequiredParam<MooseFunctorName>(NS::mu, "The viscosity");
params.addClassDescription(
"Implements the Laplace form of the viscous stress in the Navier-Stokes equation.");
params.set<unsigned short>("ghost_layers") = 2;
return params;
}
INSFVMomentumDiffusion::INSFVMomentumDiffusion(const InputParameters & params)
: INSFVFluxKernel(params), _mu(getFunctor<ADReal>(NS::mu))
{
if ((_var.faceInterpolationMethod() == Moose::FV::InterpMethod::SkewCorrectedAverage) &&
(_tid == 0))
{
auto & factory = _app.getFactory();
auto rm_params = factory.getValidParams("ElementSideNeighborLayers");
rm_params.set<std::string>("for_whom") = name();
rm_params.set<MooseMesh *>("mesh") = &const_cast<MooseMesh &>(_mesh);
rm_params.set<Moose::RelationshipManagerType>("rm_type") =
Moose::RelationshipManagerType::GEOMETRIC | Moose::RelationshipManagerType::ALGEBRAIC |
Moose::RelationshipManagerType::COUPLING;
FVKernel::setRMParams(
_pars, rm_params, std::max((unsigned short)(3), _pars.get<unsigned short>("ghost_layers")));
mooseAssert(rm_params.areAllRequiredParamsValid(),
"All relationship manager parameters should be valid.");
auto rm_obj = factory.create<RelationshipManager>(
"ElementSideNeighborLayers", name() + "_skew_correction", rm_params);
// Delete the resources created on behalf of the RM if it ends up not being added to the
// App.
if (!_app.addRelationshipManager(rm_obj))
factory.releaseSharedObjects(*rm_obj);
}
}
ADReal
INSFVMomentumDiffusion::computeStrongResidual()
{
const auto face = Moose::FV::makeCDFace(*_face_info, faceArgSubdomains());
const auto dudn = gradUDotNormal();
const auto face_mu = _mu(face);
if (_face_type == FaceInfo::VarFaceNeighbors::ELEM ||
_face_type == FaceInfo::VarFaceNeighbors::BOTH)
{
const auto dof_number = _face_info->elem().dof_number(_sys.number(), _var.number(), 0);
// A gradient is a linear combination of degrees of freedom so it's safe to straight-up index
// into the derivatives vector at the dof we care about
_ae = dudn.derivatives()[dof_number];
_ae *= -face_mu;
}
if (_face_type == FaceInfo::VarFaceNeighbors::NEIGHBOR ||
_face_type == FaceInfo::VarFaceNeighbors::BOTH)
{
const auto dof_number = _face_info->neighbor().dof_number(_sys.number(), _var.number(), 0);
_an = dudn.derivatives()[dof_number];
_an *= face_mu;
}
return -face_mu * dudn;
}
void
INSFVMomentumDiffusion::gatherRCData(const FaceInfo & fi)
{
if (skipForBoundary(fi))
return;
_face_info = &fi;
_normal = fi.normal();
_face_type = fi.faceType(_var.name());
processResidual(computeStrongResidual() * (fi.faceArea() * fi.faceCoord()));
if (_face_type == FaceInfo::VarFaceNeighbors::ELEM ||
_face_type == FaceInfo::VarFaceNeighbors::BOTH)
_rc_uo.addToA(&fi.elem(), _index, _ae * (fi.faceArea() * fi.faceCoord()));
if (_face_type == FaceInfo::VarFaceNeighbors::NEIGHBOR ||
_face_type == FaceInfo::VarFaceNeighbors::BOTH)
_rc_uo.addToA(fi.neighborPtr(), _index, _an * (fi.faceArea() * fi.faceCoord()));
}
<|endoftext|>
|
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "skia/ext/lazy_pixel_ref_utils.h"
#include "skia/ext/lazy_pixel_ref.h"
#include "third_party/skia/include/core/SkBitmapDevice.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkData.h"
#include "third_party/skia/include/core/SkDraw.h"
#include "third_party/skia/include/core/SkPixelRef.h"
#include "third_party/skia/include/core/SkRRect.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/include/core/SkShader.h"
#include "third_party/skia/src/core/SkRasterClip.h"
namespace skia {
namespace {
// URI label for a lazily decoded SkPixelRef.
const char kLabelLazyDecoded[] = "lazy";
class LazyPixelRefSet {
public:
LazyPixelRefSet(
std::vector<LazyPixelRefUtils::PositionLazyPixelRef>* pixel_refs)
: pixel_refs_(pixel_refs) {}
void Add(SkPixelRef* pixel_ref, const SkRect& rect) {
// Only save lazy pixel refs.
if (pixel_ref->getURI() &&
!strcmp(pixel_ref->getURI(), kLabelLazyDecoded)) {
LazyPixelRefUtils::PositionLazyPixelRef position_pixel_ref;
position_pixel_ref.lazy_pixel_ref =
static_cast<skia::LazyPixelRef*>(pixel_ref);
position_pixel_ref.pixel_ref_rect = rect;
pixel_refs_->push_back(position_pixel_ref);
}
}
private:
std::vector<LazyPixelRefUtils::PositionLazyPixelRef>* pixel_refs_;
};
class GatherPixelRefDevice : public SkBitmapDevice {
public:
GatherPixelRefDevice(const SkBitmap& bm, LazyPixelRefSet* lazy_pixel_ref_set)
: SkBitmapDevice(bm), lazy_pixel_ref_set_(lazy_pixel_ref_set) {}
virtual void clear(SkColor color) SK_OVERRIDE {}
virtual void writePixels(const SkBitmap& bitmap,
int x,
int y,
SkCanvas::Config8888 config8888) SK_OVERRIDE {}
virtual void drawPaint(const SkDraw& draw, const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (GetBitmapFromPaint(paint, &bitmap)) {
SkRect clip_rect = SkRect::Make(draw.fRC->getBounds());
SkRect canvas_rect = SkRect::MakeWH(width(), height());
SkRect paint_rect = SkRect::MakeEmpty();
paint_rect.intersect(canvas_rect, clip_rect);
AddBitmap(bitmap, paint_rect);
}
}
virtual void drawPoints(const SkDraw& draw,
SkCanvas::PointMode mode,
size_t count,
const SkPoint points[],
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
if (count == 0)
return;
SkPoint min_point = points[0];
SkPoint max_point = points[0];
for (size_t i = 1; i < count; ++i) {
const SkPoint& point = points[i];
min_point.set(std::min(min_point.x(), point.x()),
std::min(min_point.y(), point.y()));
max_point.set(std::max(max_point.x(), point.x()),
std::max(max_point.y(), point.y()));
}
SkRect bounds = SkRect::MakeLTRB(
min_point.x(), min_point.y(), max_point.x(), max_point.y());
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawRect(const SkDraw& draw,
const SkRect& rect,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (GetBitmapFromPaint(paint, &bitmap)) {
SkRect mapped_rect;
draw.fMatrix->mapRect(&mapped_rect, rect);
mapped_rect.intersect(SkRect::Make(draw.fRC->getBounds()));
AddBitmap(bitmap, mapped_rect);
}
}
virtual void drawOval(const SkDraw& draw,
const SkRect& rect,
const SkPaint& paint) SK_OVERRIDE {
GatherPixelRefDevice::drawRect(draw, rect, paint);
}
virtual void drawRRect(const SkDraw& draw,
const SkRRect& rect,
const SkPaint& paint) SK_OVERRIDE {
GatherPixelRefDevice::drawRect(draw, rect.rect(), paint);
}
virtual void drawPath(const SkDraw& draw,
const SkPath& path,
const SkPaint& paint,
const SkMatrix* pre_path_matrix,
bool path_is_mutable) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
SkRect path_bounds = path.getBounds();
SkRect final_rect;
if (pre_path_matrix != NULL)
pre_path_matrix->mapRect(&final_rect, path_bounds);
else
final_rect = path_bounds;
GatherPixelRefDevice::drawRect(draw, final_rect, paint);
}
virtual void drawBitmap(const SkDraw& draw,
const SkBitmap& bitmap,
const SkMatrix& matrix,
const SkPaint& paint) SK_OVERRIDE {
SkMatrix total_matrix;
total_matrix.setConcat(*draw.fMatrix, matrix);
SkRect bitmap_rect = SkRect::MakeWH(bitmap.width(), bitmap.height());
SkRect mapped_rect;
total_matrix.mapRect(&mapped_rect, bitmap_rect);
AddBitmap(bitmap, mapped_rect);
SkBitmap paint_bitmap;
if (GetBitmapFromPaint(paint, &paint_bitmap))
AddBitmap(paint_bitmap, mapped_rect);
}
virtual void drawBitmapRect(const SkDraw& draw,
const SkBitmap& bitmap,
const SkRect* src_or_null,
const SkRect& dst,
const SkPaint& paint,
SkCanvas::DrawBitmapRectFlags flags) SK_OVERRIDE {
SkRect bitmap_rect = SkRect::MakeWH(bitmap.width(), bitmap.height());
SkMatrix matrix;
matrix.setRectToRect(bitmap_rect, dst, SkMatrix::kFill_ScaleToFit);
GatherPixelRefDevice::drawBitmap(draw, bitmap, matrix, paint);
}
virtual void drawSprite(const SkDraw& draw,
const SkBitmap& bitmap,
int x,
int y,
const SkPaint& paint) SK_OVERRIDE {
// Sprites aren't affected by current matrix, so we can't reuse drawRect.
SkMatrix matrix;
matrix.setTranslate(x, y);
SkRect bitmap_rect = SkRect::MakeWH(bitmap.width(), bitmap.height());
SkRect mapped_rect;
matrix.mapRect(&mapped_rect, bitmap_rect);
AddBitmap(bitmap, mapped_rect);
SkBitmap paint_bitmap;
if (GetBitmapFromPaint(paint, &paint_bitmap))
AddBitmap(paint_bitmap, mapped_rect);
}
virtual void drawText(const SkDraw& draw,
const void* text,
size_t len,
SkScalar x,
SkScalar y,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
// Math is borrowed from SkBBoxRecord
SkRect bounds;
paint.measureText(text, len, &bounds);
SkPaint::FontMetrics metrics;
paint.getFontMetrics(&metrics);
if (paint.isVerticalText()) {
SkScalar h = bounds.fBottom - bounds.fTop;
if (paint.getTextAlign() == SkPaint::kCenter_Align) {
bounds.fTop -= h / 2;
bounds.fBottom -= h / 2;
}
bounds.fBottom += metrics.fBottom;
bounds.fTop += metrics.fTop;
} else {
SkScalar w = bounds.fRight - bounds.fLeft;
if (paint.getTextAlign() == SkPaint::kCenter_Align) {
bounds.fLeft -= w / 2;
bounds.fRight -= w / 2;
} else if (paint.getTextAlign() == SkPaint::kRight_Align) {
bounds.fLeft -= w;
bounds.fRight -= w;
}
bounds.fTop = metrics.fTop;
bounds.fBottom = metrics.fBottom;
}
SkScalar pad = (metrics.fBottom - metrics.fTop) / 2;
bounds.fLeft -= pad;
bounds.fRight += pad;
bounds.fLeft += x;
bounds.fRight += x;
bounds.fTop += y;
bounds.fBottom += y;
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawPosText(const SkDraw& draw,
const void* text,
size_t len,
const SkScalar pos[],
SkScalar const_y,
int scalars_per_pos,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
if (len == 0)
return;
// Similar to SkDraw asserts.
SkASSERT(scalars_per_pos == 1 || scalars_per_pos == 2);
SkPoint min_point;
SkPoint max_point;
if (scalars_per_pos == 1) {
min_point.set(pos[0], const_y);
max_point.set(pos[0], const_y);
} else if (scalars_per_pos == 2) {
min_point.set(pos[0], const_y + pos[1]);
max_point.set(pos[0], const_y + pos[1]);
}
for (size_t i = 0; i < len; ++i) {
SkScalar x = pos[i * scalars_per_pos];
SkScalar y = const_y;
if (scalars_per_pos == 2)
y += pos[i * scalars_per_pos + 1];
min_point.set(std::min(x, min_point.x()), std::min(y, min_point.y()));
max_point.set(std::max(x, max_point.x()), std::max(y, max_point.y()));
}
SkRect bounds = SkRect::MakeLTRB(
min_point.x(), min_point.y(), max_point.x(), max_point.y());
// Math is borrowed from SkBBoxRecord
SkPaint::FontMetrics metrics;
paint.getFontMetrics(&metrics);
bounds.fTop += metrics.fTop;
bounds.fBottom += metrics.fBottom;
SkScalar pad = (metrics.fTop - metrics.fBottom) / 2;
bounds.fLeft += pad;
bounds.fRight -= pad;
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawTextOnPath(const SkDraw& draw,
const void* text,
size_t len,
const SkPath& path,
const SkMatrix* matrix,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
// Math is borrowed from SkBBoxRecord
SkRect bounds = path.getBounds();
SkPaint::FontMetrics metrics;
paint.getFontMetrics(&metrics);
SkScalar pad = metrics.fTop;
bounds.fLeft += pad;
bounds.fRight -= pad;
bounds.fTop += pad;
bounds.fBottom -= pad;
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawVertices(const SkDraw& draw,
SkCanvas::VertexMode,
int vertex_count,
const SkPoint verts[],
const SkPoint texs[],
const SkColor colors[],
SkXfermode* xmode,
const uint16_t indices[],
int index_count,
const SkPaint& paint) SK_OVERRIDE {
GatherPixelRefDevice::drawPoints(
draw, SkCanvas::kPolygon_PointMode, vertex_count, verts, paint);
}
virtual void drawDevice(const SkDraw&,
SkBaseDevice*,
int x,
int y,
const SkPaint&) SK_OVERRIDE {}
protected:
virtual bool onReadPixels(const SkBitmap& bitmap,
int x,
int y,
SkCanvas::Config8888 config8888) SK_OVERRIDE {
return false;
}
private:
LazyPixelRefSet* lazy_pixel_ref_set_;
void AddBitmap(const SkBitmap& bm, const SkRect& rect) {
lazy_pixel_ref_set_->Add(bm.pixelRef(), rect);
}
bool GetBitmapFromPaint(const SkPaint& paint, SkBitmap* bm) {
SkShader* shader = paint.getShader();
if (shader) {
// Check whether the shader is a gradient in order to prevent generation
// of bitmaps from gradient shaders, which implement asABitmap.
if (SkShader::kNone_GradientType == shader->asAGradient(NULL))
return shader->asABitmap(bm, NULL, NULL);
}
return false;
}
};
class NoSaveLayerCanvas : public SkCanvas {
public:
NoSaveLayerCanvas(SkBaseDevice* device) : INHERITED(device) {}
// Turn saveLayer() into save() for speed, should not affect correctness.
virtual int saveLayer(const SkRect* bounds,
const SkPaint* paint,
SaveFlags flags) SK_OVERRIDE {
// Like SkPictureRecord, we don't want to create layers, but we do need
// to respect the save and (possibly) its rect-clip.
int count = this->INHERITED::save(flags);
if (bounds) {
this->INHERITED::clipRectBounds(bounds, flags, NULL);
}
return count;
}
// Disable aa for speed.
virtual bool clipRect(const SkRect& rect, SkRegion::Op op, bool doAA)
SK_OVERRIDE {
return this->INHERITED::clipRect(rect, op, false);
}
virtual bool clipPath(const SkPath& path, SkRegion::Op op, bool doAA)
SK_OVERRIDE {
return this->updateClipConservativelyUsingBounds(
path.getBounds(), op, path.isInverseFillType());
}
virtual bool clipRRect(const SkRRect& rrect, SkRegion::Op op, bool doAA)
SK_OVERRIDE {
return this->updateClipConservativelyUsingBounds(
rrect.getBounds(), op, false);
}
private:
typedef SkCanvas INHERITED;
};
} // namespace
void LazyPixelRefUtils::GatherPixelRefs(
SkPicture* picture,
std::vector<PositionLazyPixelRef>* lazy_pixel_refs) {
lazy_pixel_refs->clear();
LazyPixelRefSet pixel_ref_set(lazy_pixel_refs);
SkBitmap empty_bitmap;
empty_bitmap.setConfig(
SkBitmap::kNo_Config, picture->width(), picture->height());
GatherPixelRefDevice device(empty_bitmap, &pixel_ref_set);
NoSaveLayerCanvas canvas(&device);
canvas.clipRect(SkRect::MakeWH(picture->width(), picture->height()),
SkRegion::kIntersect_Op,
false);
canvas.drawPicture(*picture);
}
} // namespace skia
<commit_msg>add missing #include of <algorithm>, needed on VS2013 for std::min/max<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "skia/ext/lazy_pixel_ref_utils.h"
#include <algorithm>
#include "skia/ext/lazy_pixel_ref.h"
#include "third_party/skia/include/core/SkBitmapDevice.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkData.h"
#include "third_party/skia/include/core/SkDraw.h"
#include "third_party/skia/include/core/SkPixelRef.h"
#include "third_party/skia/include/core/SkRRect.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/include/core/SkShader.h"
#include "third_party/skia/src/core/SkRasterClip.h"
namespace skia {
namespace {
// URI label for a lazily decoded SkPixelRef.
const char kLabelLazyDecoded[] = "lazy";
class LazyPixelRefSet {
public:
LazyPixelRefSet(
std::vector<LazyPixelRefUtils::PositionLazyPixelRef>* pixel_refs)
: pixel_refs_(pixel_refs) {}
void Add(SkPixelRef* pixel_ref, const SkRect& rect) {
// Only save lazy pixel refs.
if (pixel_ref->getURI() &&
!strcmp(pixel_ref->getURI(), kLabelLazyDecoded)) {
LazyPixelRefUtils::PositionLazyPixelRef position_pixel_ref;
position_pixel_ref.lazy_pixel_ref =
static_cast<skia::LazyPixelRef*>(pixel_ref);
position_pixel_ref.pixel_ref_rect = rect;
pixel_refs_->push_back(position_pixel_ref);
}
}
private:
std::vector<LazyPixelRefUtils::PositionLazyPixelRef>* pixel_refs_;
};
class GatherPixelRefDevice : public SkBitmapDevice {
public:
GatherPixelRefDevice(const SkBitmap& bm, LazyPixelRefSet* lazy_pixel_ref_set)
: SkBitmapDevice(bm), lazy_pixel_ref_set_(lazy_pixel_ref_set) {}
virtual void clear(SkColor color) SK_OVERRIDE {}
virtual void writePixels(const SkBitmap& bitmap,
int x,
int y,
SkCanvas::Config8888 config8888) SK_OVERRIDE {}
virtual void drawPaint(const SkDraw& draw, const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (GetBitmapFromPaint(paint, &bitmap)) {
SkRect clip_rect = SkRect::Make(draw.fRC->getBounds());
SkRect canvas_rect = SkRect::MakeWH(width(), height());
SkRect paint_rect = SkRect::MakeEmpty();
paint_rect.intersect(canvas_rect, clip_rect);
AddBitmap(bitmap, paint_rect);
}
}
virtual void drawPoints(const SkDraw& draw,
SkCanvas::PointMode mode,
size_t count,
const SkPoint points[],
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
if (count == 0)
return;
SkPoint min_point = points[0];
SkPoint max_point = points[0];
for (size_t i = 1; i < count; ++i) {
const SkPoint& point = points[i];
min_point.set(std::min(min_point.x(), point.x()),
std::min(min_point.y(), point.y()));
max_point.set(std::max(max_point.x(), point.x()),
std::max(max_point.y(), point.y()));
}
SkRect bounds = SkRect::MakeLTRB(
min_point.x(), min_point.y(), max_point.x(), max_point.y());
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawRect(const SkDraw& draw,
const SkRect& rect,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (GetBitmapFromPaint(paint, &bitmap)) {
SkRect mapped_rect;
draw.fMatrix->mapRect(&mapped_rect, rect);
mapped_rect.intersect(SkRect::Make(draw.fRC->getBounds()));
AddBitmap(bitmap, mapped_rect);
}
}
virtual void drawOval(const SkDraw& draw,
const SkRect& rect,
const SkPaint& paint) SK_OVERRIDE {
GatherPixelRefDevice::drawRect(draw, rect, paint);
}
virtual void drawRRect(const SkDraw& draw,
const SkRRect& rect,
const SkPaint& paint) SK_OVERRIDE {
GatherPixelRefDevice::drawRect(draw, rect.rect(), paint);
}
virtual void drawPath(const SkDraw& draw,
const SkPath& path,
const SkPaint& paint,
const SkMatrix* pre_path_matrix,
bool path_is_mutable) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
SkRect path_bounds = path.getBounds();
SkRect final_rect;
if (pre_path_matrix != NULL)
pre_path_matrix->mapRect(&final_rect, path_bounds);
else
final_rect = path_bounds;
GatherPixelRefDevice::drawRect(draw, final_rect, paint);
}
virtual void drawBitmap(const SkDraw& draw,
const SkBitmap& bitmap,
const SkMatrix& matrix,
const SkPaint& paint) SK_OVERRIDE {
SkMatrix total_matrix;
total_matrix.setConcat(*draw.fMatrix, matrix);
SkRect bitmap_rect = SkRect::MakeWH(bitmap.width(), bitmap.height());
SkRect mapped_rect;
total_matrix.mapRect(&mapped_rect, bitmap_rect);
AddBitmap(bitmap, mapped_rect);
SkBitmap paint_bitmap;
if (GetBitmapFromPaint(paint, &paint_bitmap))
AddBitmap(paint_bitmap, mapped_rect);
}
virtual void drawBitmapRect(const SkDraw& draw,
const SkBitmap& bitmap,
const SkRect* src_or_null,
const SkRect& dst,
const SkPaint& paint,
SkCanvas::DrawBitmapRectFlags flags) SK_OVERRIDE {
SkRect bitmap_rect = SkRect::MakeWH(bitmap.width(), bitmap.height());
SkMatrix matrix;
matrix.setRectToRect(bitmap_rect, dst, SkMatrix::kFill_ScaleToFit);
GatherPixelRefDevice::drawBitmap(draw, bitmap, matrix, paint);
}
virtual void drawSprite(const SkDraw& draw,
const SkBitmap& bitmap,
int x,
int y,
const SkPaint& paint) SK_OVERRIDE {
// Sprites aren't affected by current matrix, so we can't reuse drawRect.
SkMatrix matrix;
matrix.setTranslate(x, y);
SkRect bitmap_rect = SkRect::MakeWH(bitmap.width(), bitmap.height());
SkRect mapped_rect;
matrix.mapRect(&mapped_rect, bitmap_rect);
AddBitmap(bitmap, mapped_rect);
SkBitmap paint_bitmap;
if (GetBitmapFromPaint(paint, &paint_bitmap))
AddBitmap(paint_bitmap, mapped_rect);
}
virtual void drawText(const SkDraw& draw,
const void* text,
size_t len,
SkScalar x,
SkScalar y,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
// Math is borrowed from SkBBoxRecord
SkRect bounds;
paint.measureText(text, len, &bounds);
SkPaint::FontMetrics metrics;
paint.getFontMetrics(&metrics);
if (paint.isVerticalText()) {
SkScalar h = bounds.fBottom - bounds.fTop;
if (paint.getTextAlign() == SkPaint::kCenter_Align) {
bounds.fTop -= h / 2;
bounds.fBottom -= h / 2;
}
bounds.fBottom += metrics.fBottom;
bounds.fTop += metrics.fTop;
} else {
SkScalar w = bounds.fRight - bounds.fLeft;
if (paint.getTextAlign() == SkPaint::kCenter_Align) {
bounds.fLeft -= w / 2;
bounds.fRight -= w / 2;
} else if (paint.getTextAlign() == SkPaint::kRight_Align) {
bounds.fLeft -= w;
bounds.fRight -= w;
}
bounds.fTop = metrics.fTop;
bounds.fBottom = metrics.fBottom;
}
SkScalar pad = (metrics.fBottom - metrics.fTop) / 2;
bounds.fLeft -= pad;
bounds.fRight += pad;
bounds.fLeft += x;
bounds.fRight += x;
bounds.fTop += y;
bounds.fBottom += y;
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawPosText(const SkDraw& draw,
const void* text,
size_t len,
const SkScalar pos[],
SkScalar const_y,
int scalars_per_pos,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
if (len == 0)
return;
// Similar to SkDraw asserts.
SkASSERT(scalars_per_pos == 1 || scalars_per_pos == 2);
SkPoint min_point;
SkPoint max_point;
if (scalars_per_pos == 1) {
min_point.set(pos[0], const_y);
max_point.set(pos[0], const_y);
} else if (scalars_per_pos == 2) {
min_point.set(pos[0], const_y + pos[1]);
max_point.set(pos[0], const_y + pos[1]);
}
for (size_t i = 0; i < len; ++i) {
SkScalar x = pos[i * scalars_per_pos];
SkScalar y = const_y;
if (scalars_per_pos == 2)
y += pos[i * scalars_per_pos + 1];
min_point.set(std::min(x, min_point.x()), std::min(y, min_point.y()));
max_point.set(std::max(x, max_point.x()), std::max(y, max_point.y()));
}
SkRect bounds = SkRect::MakeLTRB(
min_point.x(), min_point.y(), max_point.x(), max_point.y());
// Math is borrowed from SkBBoxRecord
SkPaint::FontMetrics metrics;
paint.getFontMetrics(&metrics);
bounds.fTop += metrics.fTop;
bounds.fBottom += metrics.fBottom;
SkScalar pad = (metrics.fTop - metrics.fBottom) / 2;
bounds.fLeft += pad;
bounds.fRight -= pad;
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawTextOnPath(const SkDraw& draw,
const void* text,
size_t len,
const SkPath& path,
const SkMatrix* matrix,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
// Math is borrowed from SkBBoxRecord
SkRect bounds = path.getBounds();
SkPaint::FontMetrics metrics;
paint.getFontMetrics(&metrics);
SkScalar pad = metrics.fTop;
bounds.fLeft += pad;
bounds.fRight -= pad;
bounds.fTop += pad;
bounds.fBottom -= pad;
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawVertices(const SkDraw& draw,
SkCanvas::VertexMode,
int vertex_count,
const SkPoint verts[],
const SkPoint texs[],
const SkColor colors[],
SkXfermode* xmode,
const uint16_t indices[],
int index_count,
const SkPaint& paint) SK_OVERRIDE {
GatherPixelRefDevice::drawPoints(
draw, SkCanvas::kPolygon_PointMode, vertex_count, verts, paint);
}
virtual void drawDevice(const SkDraw&,
SkBaseDevice*,
int x,
int y,
const SkPaint&) SK_OVERRIDE {}
protected:
virtual bool onReadPixels(const SkBitmap& bitmap,
int x,
int y,
SkCanvas::Config8888 config8888) SK_OVERRIDE {
return false;
}
private:
LazyPixelRefSet* lazy_pixel_ref_set_;
void AddBitmap(const SkBitmap& bm, const SkRect& rect) {
lazy_pixel_ref_set_->Add(bm.pixelRef(), rect);
}
bool GetBitmapFromPaint(const SkPaint& paint, SkBitmap* bm) {
SkShader* shader = paint.getShader();
if (shader) {
// Check whether the shader is a gradient in order to prevent generation
// of bitmaps from gradient shaders, which implement asABitmap.
if (SkShader::kNone_GradientType == shader->asAGradient(NULL))
return shader->asABitmap(bm, NULL, NULL);
}
return false;
}
};
class NoSaveLayerCanvas : public SkCanvas {
public:
NoSaveLayerCanvas(SkBaseDevice* device) : INHERITED(device) {}
// Turn saveLayer() into save() for speed, should not affect correctness.
virtual int saveLayer(const SkRect* bounds,
const SkPaint* paint,
SaveFlags flags) SK_OVERRIDE {
// Like SkPictureRecord, we don't want to create layers, but we do need
// to respect the save and (possibly) its rect-clip.
int count = this->INHERITED::save(flags);
if (bounds) {
this->INHERITED::clipRectBounds(bounds, flags, NULL);
}
return count;
}
// Disable aa for speed.
virtual bool clipRect(const SkRect& rect, SkRegion::Op op, bool doAA)
SK_OVERRIDE {
return this->INHERITED::clipRect(rect, op, false);
}
virtual bool clipPath(const SkPath& path, SkRegion::Op op, bool doAA)
SK_OVERRIDE {
return this->updateClipConservativelyUsingBounds(
path.getBounds(), op, path.isInverseFillType());
}
virtual bool clipRRect(const SkRRect& rrect, SkRegion::Op op, bool doAA)
SK_OVERRIDE {
return this->updateClipConservativelyUsingBounds(
rrect.getBounds(), op, false);
}
private:
typedef SkCanvas INHERITED;
};
} // namespace
void LazyPixelRefUtils::GatherPixelRefs(
SkPicture* picture,
std::vector<PositionLazyPixelRef>* lazy_pixel_refs) {
lazy_pixel_refs->clear();
LazyPixelRefSet pixel_ref_set(lazy_pixel_refs);
SkBitmap empty_bitmap;
empty_bitmap.setConfig(
SkBitmap::kNo_Config, picture->width(), picture->height());
GatherPixelRefDevice device(empty_bitmap, &pixel_ref_set);
NoSaveLayerCanvas canvas(&device);
canvas.clipRect(SkRect::MakeWH(picture->width(), picture->height()),
SkRegion::kIntersect_Op,
false);
canvas.drawPicture(*picture);
}
} // namespace skia
<|endoftext|>
|
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/component/topology/PointSetTopologyModifier.h>
#include <sofa/simulation/common/StateChangeVisitor.h>
#include <sofa/simulation/common/Simulation.h>
#include <sofa/simulation/common/TopologyChangeVisitor.h>
#include <sofa/component/topology/PointSetTopologyChange.h>
#include <sofa/component/topology/PointSetTopologyContainer.h>
#include <sofa/core/ObjectFactory.h>
namespace sofa
{
namespace component
{
namespace topology
{
SOFA_DECL_CLASS(PointSetTopologyModifier)
int PointSetTopologyModifierClass = core::RegisterObject("Point set topology modifier")
.add< PointSetTopologyModifier >();
using namespace std;
using namespace sofa::defaulttype;
using namespace sofa::core::behavior;
void PointSetTopologyModifier::init()
{
core::topology::TopologyModifier::init();
this->getContext()->get(m_container);
}
void PointSetTopologyModifier::swapPoints(const int i1, const int i2)
{
PointsIndicesSwap *e2 = new PointsIndicesSwap( i1, i2 );
addStateChange(e2);
propagateStateChanges();
PointsIndicesSwap *e = new PointsIndicesSwap( i1, i2 );
this->addTopologyChange(e);
}
void PointSetTopologyModifier::addPointsProcess(const unsigned int nPoints)
{
m_container->addPoints(nPoints);
}
void PointSetTopologyModifier::addPointsWarning(const unsigned int nPoints, const bool addDOF)
{
if(addDOF)
{
PointsAdded *e2 = new PointsAdded(nPoints);
addStateChange(e2);
propagateStateChanges();
}
// Warning that vertices just got created
PointsAdded *e = new PointsAdded(nPoints);
this->addTopologyChange(e);
}
void PointSetTopologyModifier::addPointsWarning(const unsigned int nPoints,
const sofa::helper::vector< sofa::helper::vector< unsigned int > > &ancestors,
const sofa::helper::vector< sofa::helper::vector< double > >& coefs,
const bool addDOF)
{
if(addDOF)
{
PointsAdded *e2 = new PointsAdded(nPoints, ancestors, coefs);
addStateChange(e2);
propagateStateChanges();
}
// Warning that vertices just got created
PointsAdded *e = new PointsAdded(nPoints, ancestors, coefs);
this->addTopologyChange(e);
}
void PointSetTopologyModifier::movePointsProcess (const sofa::helper::vector <unsigned int>& id,
const sofa::helper::vector< sofa::helper::vector< unsigned int > >& ancestors,
const sofa::helper::vector< sofa::helper::vector< double > >& coefs,
const bool moveDOF)
{
if(moveDOF)
{
PointsMoved *ev = new PointsMoved(id, ancestors, coefs);
addStateChange(ev);
propagateStateChanges();
}
// Warning that vertices just been moved
PointsMoved *ev2 = new PointsMoved(id, ancestors, coefs);
this->addTopologyChange(ev2);
}
void PointSetTopologyModifier::removePointsWarning(sofa::helper::vector<unsigned int> &indices,
const bool removeDOF)
{
// sort points so that they are removed in a descending order
std::sort( indices.begin(), indices.end(), std::greater<unsigned int>() );
// Warning that these vertices will be deleted
PointsRemoved *e = new PointsRemoved(indices);
this->addTopologyChange(e);
if(removeDOF)
{
PointsRemoved *e2 = new PointsRemoved(indices);
addStateChange(e2);
}
}
void PointSetTopologyModifier::removePointsProcess(const sofa::helper::vector<unsigned int> & indices,
const bool removeDOF)
{
if(removeDOF)
{
propagateStateChanges();
}
m_container->removePoints(indices.size());
}
void PointSetTopologyModifier::renumberPointsWarning( const sofa::helper::vector<unsigned int> &index,
const sofa::helper::vector<unsigned int> &inv_index,
const bool renumberDOF)
{
// Warning that these vertices will be deleted
PointsRenumbering *e = new PointsRenumbering(index, inv_index);
this->addTopologyChange(e);
if(renumberDOF)
{
PointsRenumbering *e2 = new PointsRenumbering(index, inv_index);
addStateChange(e2);
}
}
void PointSetTopologyModifier::renumberPointsProcess( const sofa::helper::vector<unsigned int> &/*index*/,
const sofa::helper::vector<unsigned int> &/*inv_index*/,
const bool renumberDOF)
{
if(renumberDOF)
{
propagateStateChanges();
}
}
void PointSetTopologyModifier::propagateTopologicalChanges()
{
if (m_container->beginChange() == m_container->endChange()) return; // nothing to do if no event is stored
sofa::simulation::TopologyChangeVisitor a(m_container);
// std::cout << getName() << " propagation du truc: " << getContext()->getName() << std::endl;
// for( std::list<const core::topology::TopologyChange *>::const_iterator it = m_container->beginChange(); it != m_container->endChange(); it++)
// std:: cout << (*it)->getChangeType() << std::endl;
getContext()->executeVisitor(&a);
//TODO: temporary code to test topology engine pipeline. Commented by default for the moment
//this->propagateTopologicalEngineChanges();
// remove the changes we just propagated, so that we don't send them again next time
m_container->resetTopologyChangeList();
}
void PointSetTopologyModifier::propagateTopologicalEngineChanges()
{
std::cout << "PointSetTopologyModifier::propagateTopologicalEngineChanges()" << std::endl;
if (m_container->beginChange() == m_container->endChange()) return; // nothing to do if no event is stored
sofa::helper::list<const sofa::core::topology::TopologyEngine*>::const_iterator engineIt;
for (engineIt = m_container->beginTopologyEngine(); engineIt != m_container->endTopologyEngine(); ++engineIt)
{
// (*engineIt)->update();
}
std::cout << "PointSetTopologyModifier::propagateTopologicalEngineChanges() end" << std::endl;
}
void PointSetTopologyModifier::propagateStateChanges()
{
if (m_container->beginStateChange() == m_container->endStateChange()) return; // nothing to do if no event is stored
sofa::simulation::StateChangeVisitor a(m_container);
getContext()->executeVisitor(&a);
// remove the changes we just propagated, so that we don't send then again next time
m_container->resetStateChangeList();
}
void PointSetTopologyModifier::notifyEndingEvent()
{
sofa::core::topology::EndingEvent *e=new sofa::core::topology::EndingEvent();
m_container->addTopologyChange(e);
}
} // namespace topology
} // namespace component
} // namespace sofa
<commit_msg>r8081/sofa-dev : FIX: compilation.<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/component/topology/PointSetTopologyModifier.h>
#include <sofa/simulation/common/StateChangeVisitor.h>
#include <sofa/simulation/common/Simulation.h>
#include <sofa/simulation/common/TopologyChangeVisitor.h>
#include <sofa/component/topology/PointSetTopologyChange.h>
#include <sofa/component/topology/PointSetTopologyContainer.h>
#include <sofa/core/ObjectFactory.h>
namespace sofa
{
namespace component
{
namespace topology
{
SOFA_DECL_CLASS(PointSetTopologyModifier)
int PointSetTopologyModifierClass = core::RegisterObject("Point set topology modifier")
.add< PointSetTopologyModifier >();
using namespace std;
using namespace sofa::defaulttype;
using namespace sofa::core::behavior;
void PointSetTopologyModifier::init()
{
core::topology::TopologyModifier::init();
this->getContext()->get(m_container);
}
void PointSetTopologyModifier::swapPoints(const int i1, const int i2)
{
PointsIndicesSwap *e2 = new PointsIndicesSwap( i1, i2 );
addStateChange(e2);
propagateStateChanges();
PointsIndicesSwap *e = new PointsIndicesSwap( i1, i2 );
this->addTopologyChange(e);
}
void PointSetTopologyModifier::addPointsProcess(const unsigned int nPoints)
{
m_container->addPoints(nPoints);
}
void PointSetTopologyModifier::addPointsWarning(const unsigned int nPoints, const bool addDOF)
{
if(addDOF)
{
PointsAdded *e2 = new PointsAdded(nPoints);
addStateChange(e2);
propagateStateChanges();
}
// Warning that vertices just got created
PointsAdded *e = new PointsAdded(nPoints);
this->addTopologyChange(e);
}
void PointSetTopologyModifier::addPointsWarning(const unsigned int nPoints,
const sofa::helper::vector< sofa::helper::vector< unsigned int > > &ancestors,
const sofa::helper::vector< sofa::helper::vector< double > >& coefs,
const bool addDOF)
{
if(addDOF)
{
PointsAdded *e2 = new PointsAdded(nPoints, ancestors, coefs);
addStateChange(e2);
propagateStateChanges();
}
// Warning that vertices just got created
PointsAdded *e = new PointsAdded(nPoints, ancestors, coefs);
this->addTopologyChange(e);
}
void PointSetTopologyModifier::movePointsProcess (const sofa::helper::vector <unsigned int>& id,
const sofa::helper::vector< sofa::helper::vector< unsigned int > >& ancestors,
const sofa::helper::vector< sofa::helper::vector< double > >& coefs,
const bool moveDOF)
{
if(moveDOF)
{
PointsMoved *ev = new PointsMoved(id, ancestors, coefs);
addStateChange(ev);
propagateStateChanges();
}
// Warning that vertices just been moved
PointsMoved *ev2 = new PointsMoved(id, ancestors, coefs);
this->addTopologyChange(ev2);
}
void PointSetTopologyModifier::removePointsWarning(sofa::helper::vector<unsigned int> &indices,
const bool removeDOF)
{
// sort points so that they are removed in a descending order
std::sort( indices.begin(), indices.end(), std::greater<unsigned int>() );
// Warning that these vertices will be deleted
PointsRemoved *e = new PointsRemoved(indices);
this->addTopologyChange(e);
if(removeDOF)
{
PointsRemoved *e2 = new PointsRemoved(indices);
addStateChange(e2);
}
}
void PointSetTopologyModifier::removePointsProcess(const sofa::helper::vector<unsigned int> & indices,
const bool removeDOF)
{
if(removeDOF)
{
propagateStateChanges();
}
m_container->removePoints(indices.size());
}
void PointSetTopologyModifier::renumberPointsWarning( const sofa::helper::vector<unsigned int> &index,
const sofa::helper::vector<unsigned int> &inv_index,
const bool renumberDOF)
{
// Warning that these vertices will be deleted
PointsRenumbering *e = new PointsRenumbering(index, inv_index);
this->addTopologyChange(e);
if(renumberDOF)
{
PointsRenumbering *e2 = new PointsRenumbering(index, inv_index);
addStateChange(e2);
}
}
void PointSetTopologyModifier::renumberPointsProcess( const sofa::helper::vector<unsigned int> &/*index*/,
const sofa::helper::vector<unsigned int> &/*inv_index*/,
const bool renumberDOF)
{
if(renumberDOF)
{
propagateStateChanges();
}
}
void PointSetTopologyModifier::propagateTopologicalChanges()
{
if (m_container->beginChange() == m_container->endChange()) return; // nothing to do if no event is stored
sofa::simulation::TopologyChangeVisitor a(m_container);
// std::cout << getName() << " propagation du truc: " << getContext()->getName() << std::endl;
// for( std::list<const core::topology::TopologyChange *>::const_iterator it = m_container->beginChange(); it != m_container->endChange(); it++)
// std:: cout << (*it)->getChangeType() << std::endl;
getContext()->executeVisitor(&a);
//TODO: temporary code to test topology engine pipeline. Commented by default for the moment
//this->propagateTopologicalEngineChanges();
// remove the changes we just propagated, so that we don't send them again next time
m_container->resetTopologyChangeList();
}
void PointSetTopologyModifier::propagateTopologicalEngineChanges()
{
std::cout << "PointSetTopologyModifier::propagateTopologicalEngineChanges()" << std::endl;
if (m_container->beginChange() == m_container->endChange()) return; // nothing to do if no event is stored
sofa::helper::list<sofa::core::topology::TopologyEngine*>::const_iterator engineIt;
for (engineIt = m_container->beginTopologyEngine(); engineIt != m_container->endTopologyEngine(); ++engineIt)
{
(*engineIt)->update();
}
std::cout << "PointSetTopologyModifier::propagateTopologicalEngineChanges() end" << std::endl;
}
void PointSetTopologyModifier::propagateStateChanges()
{
if (m_container->beginStateChange() == m_container->endStateChange()) return; // nothing to do if no event is stored
sofa::simulation::StateChangeVisitor a(m_container);
getContext()->executeVisitor(&a);
// remove the changes we just propagated, so that we don't send then again next time
m_container->resetStateChangeList();
}
void PointSetTopologyModifier::notifyEndingEvent()
{
sofa::core::topology::EndingEvent *e=new sofa::core::topology::EndingEvent();
m_container->addTopologyChange(e);
}
} // namespace topology
} // namespace component
} // namespace sofa
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "multipitch.h"
#include "essentiamath.h"
using namespace std;
using namespace essentia;
using namespace standard;
namespace essentia {
namespace standard {
const char* MultiPitch::name = "MultiPitch";
const char* MultiPitch::version = "1.0";
const char* MultiPitch::description = DOC("This algorithm performas a joint estimation of the fundamental frequencies in each frame corresponding to the pitch of the sources of polyphonic recording. Similar to [2], the estimation is based on harmonic summation. The implementation is based on the system described in [1] with a slight modifications: The caclculation of the pitch salience function is taken from [2].
"\n"
"The output is a vector for each frame containing the estimated melody pitch values .\n"
"\n"
"References:\n"
" [1] A. Klapuri, \"Multiple Fundamental Frequency Estimation by Summing Harmonic\n"
" Amplitudes \", International Society for Music Information Retrieval Conference\n
" (2006).\n"
" [2] J. Salamon and E. Gómez, \"Melody extraction from polyphonic music\n"
" signals using pitch contour characteristics,\" IEEE Transactions on Audio,\n"
" Speech, and Language Processing, vol. 20, no. 6, pp. 1759–1770, 2012.\n\n"
);
void MultiPitch::configure() {
sampleRate = parameter("sampleRate").toReal();
frameSize = parameter("frameSize").toInt();
hopSize = parameter("hopSize").toInt();
string windowType = "hann";
zeroPaddingFactor = 4;
int maxSpectralPeaks = 100;
int numberBins=frequencyToCentBin(sampleRate/2);
centSpectrum.resize(numberBins);
referenceFrequency = parameter("referenceFrequency").toReal();
binResolution = parameter("binResolution").toReal();
Real magnitudeThreshold = parameter("magnitudeThreshold").toReal();
Real magnitudeCompression = parameter("magnitudeCompression").toReal();
numberHarmonics = parameter("numberHarmonics").toInt();
Real harmonicWeight = parameter("harmonicWeight").toReal();
Real minFrequency = parameter("minFrequency").toReal();
Real maxFrequency = parameter("maxFrequency").toReal();
numberHarmonicsMax=floor(sampleRate/maxFrequency);
numberHarmonicsMax=min(numberHarmonics,numberHarmonicsMax);
binsInSemitone = floor(100.0 / binResolution);
centToHertzBase = pow(2, binResolution / 1200.0);
binsInOctave = 1200.0 / binResolution;
referenceTerm = 0.5 - binsInOctave * log2(referenceFrequency);
// Pre-processing
_frameCutter->configure("frameSize", frameSize,
"hopSize", hopSize,
"startFromZero", false);
_windowing->configure("size", frameSize,
"zeroPadding", (zeroPaddingFactor-1) * frameSize,
"type", windowType);
// Spectral peaks
_spectrum->configure("size", frameSize * zeroPaddingFactor);
_spectralPeaks->configure(
"minFrequency", 1, // to avoid zero frequencies
"maxFrequency", 20000,
"maxPeaks", maxSpectralPeaks,
"sampleRate", sampleRate,
"magnitudeThreshold", 0,
"orderBy", "magnitude");
// Spectral whitening
_spectralWhitening->configure("sampleRate", sampleRate);
// Pitch salience contours
_pitchSalienceFunction->configure("binResolution", binResolution,
"referenceFrequency", referenceFrequency,
"magnitudeThreshold", magnitudeThreshold,
"magnitudeCompression", magnitudeCompression,
"numberHarmonics", numberHarmonics,
"harmonicWeight", harmonicWeight);
// pitch salience function peaks are considered F0 cadidates -> limit to considered frequency range
_pitchSalienceFunctionPeaks->configure("binResolution", binResolution,
"referenceFrequency", referenceFrequency,
"minFrequency", minFrequency,
"maxFrequency", maxFrequency);
}
void MultiPitch::compute() {
const vector<Real>& signal = _signal.get();
vector<vector<Real> >& pitch = _pitch.get();
if (signal.empty()) {
pitch.clear();
return;
}
// Pre-processing
vector<Real> frame;
_frameCutter->input("signal").set(signal);
_frameCutter->output("frame").set(frame);
vector<Real> frameWindowed;
_windowing->input("frame").set(frame);
_windowing->output("frame").set(frameWindowed);
// Spectral peaks
vector<Real> frameSpectrum;
_spectrum->input("frame").set(frameWindowed);
_spectrum->output("spectrum").set(frameSpectrum);
vector<Real> frameFrequencies;
vector<Real> frameMagnitudes;
_spectralPeaks->input("spectrum").set(frameSpectrum);
_spectralPeaks->output("frequencies").set(frameFrequencies);
_spectralPeaks->output("magnitudes").set(frameMagnitudes);
// Spectral whitening
vector<Real> frameWhiteMagnitudes;
_spectralWhitening->input("spectrum").set(frameSpectrum);
_spectralWhitening->input("frequencies").set(frameFrequencies);
_spectralWhitening->input("magnitudes").set(frameMagnitudes);
_spectralWhitening->output("magnitudes").set(frameWhiteMagnitudes);
// Pitch salience contours
vector<Real> frameSalience;
_pitchSalienceFunction->input("frequencies").set(frameFrequencies);
_pitchSalienceFunction->input("magnitudes").set(frameMagnitudes);
_pitchSalienceFunction->output("salienceFunction").set(frameSalience);
vector<Real> frameSalienceBins;
vector<Real> frameSalienceValues;
_pitchSalienceFunctionPeaks->input("salienceFunction").set(frameSalience);
_pitchSalienceFunctionPeaks->output("salienceBins").set(frameSalienceBins);
_pitchSalienceFunctionPeaks->output("salienceValues").set(frameSalienceValues);
vector<vector<Real> > peakBins;
vector<vector<Real> > peakSaliences;
vector<Real> nearestBinWeights;
nearestBinWeights.resize(binsInSemitone + 1);
for (int b=0; b <= binsInSemitone; b++) {
nearestBinWeights[b] = pow(cos((Real(b)/binsInSemitone)* M_PI/2), 2);
}
vector<Real> harmonicWeights;
harmonicWeights.clear();
harmonicWeights.reserve(numberHarmonicsMax);
for (int h=0; h<numberHarmonicsMax; h++) {
harmonicWeights.push_back(pow(0.8, h));
}
while (true) {
// get a frame
_frameCutter->compute();
if (!frame.size()) {
break;
}
_windowing->compute();
// calculate spectrum
_spectrum->compute();
// calculate spectral peaks
_spectralPeaks->compute();
// whiten the spectrum
_spectralWhitening->compute();
// calculate salience function
_pitchSalienceFunction->compute();
// calculate peaks of salience function
_pitchSalienceFunctionPeaks->compute();
// no peaks in this frame
if (!frameSalienceBins.size()){
continue;
}
///////////////////////////////////////////////////////////////////////
// Joint F0 estimation (pitch salience function peaks as candidates) //
///////////////////////////////////////////////////////////////////////
// compute the cent-scaled spectrum
fill(centSpectrum.begin(), centSpectrum.end(), (Real) 0.0);
for (int i=0; i<frameSpectrum.size(); i++){
float f=(float(i)/float(frameSpectrum.size()))*(sampleRate/2);
int k=frequencyToCentBin(f);
if (k>0 && k<numberBins){
centSpectrum[k]=centSpectrum[k]+frameSpectrum[i];
}
}
// get indices corresponding to harmonics of each found peak
vector<vector<int> > kPeaks;
for (int i=0; i<frameSalienceBins.size(); i++){
vector<int> k;
float f=referenceFrequency * pow(centToHertzBase, frameSalienceBins[i]);
for (int m=0; m<numberHarmonicsMax; m++){
// find the exact peak for each harmonic
int kBin=frequencyToCentBin(f*(m+1));
int kBinMin=max(0, int(kBin-binsInSemitone));
int kBinMax=min(numberBins,int(kBin+binsInSemitone));
vector<float> specSegment;
for (int ii=kBinMin; ii<=kBinMax; ii++){
specSegment.push_back(centSpectrum[ii]);
}
kBin=kBinMin+argmax(specSegment)-1;
k.push_back(kBin);
}
kPeaks.push_back(k);
}
// candidate Spectra
vector<vector<Real> > Z;
for (int i=0; i<frameSalienceBins.size(); i++){
vector<Real> z;
z.resize(centSpectrum.size());
fill(z.begin(), z.end(), (Real) 0.0);
for (int h=0; h<numberHarmonicsMax; h++) {
int h_bin = kPeaks[i][h];
for(int b=max(0, h_bin-binsInSemitone); b <= min(numberBins-1, h_bin+binsInSemitone); b++) {
//z[b] += nearestBinWeights[abs(b-h_bin)] * harmonicWeights[h] * 0.25; // 0.25 is cancellation parameter
z[b] += nearestBinWeights[abs(b-h_bin)] * getWeight(h_bin,h) * 0.25; // 0.25 is cancellation parameter
}
}
Z.push_back(z);
}
// inhibition function
int numCandidates=frameSalienceBins.size();
float inh[numCandidates][numCandidates];
for (int i=0; i<numCandidates; i++){
for (int j=0; j<numCandidates; j++){
inh[i][j]=0;
for (int m=0; m<numberHarmonicsMax; m++){
inh[i][j]+=getWeight(kPeaks[i][m],m)*centSpectrum[kPeaks[i][m]]*Z[j][kPeaks[i][m]];
}
}
}
// goodess function init
float G_init[numCandidates];
for (int i=0; i<numCandidates; i++){
G_init[i]=frameSalienceValues[i];
}
vector<int> finalSelection;
// polyphony estimation init
int p=1;
float gamma=0.73;
float S=frameSalienceValues[argmax(frameSalienceValues)]/(pow(p,gamma));
finalSelection.push_back(argmax(frameSalienceValues));
// goodess function
vector<vector<float> > G;
for (int i=0; i<numCandidates; i++){
vector<float> g;
for (int j=0; j<numCandidates; j++){
if(i==j){
g.push_back(0.0);
}else{
float g_val=G_init[i]+frameSalienceValues[j]-(inh[i][j]+inh[j][i]);
g.push_back(g_val);
}
}
G.push_back(g);
}
vector<vector<int> > selCandInd;
vector<float> selCandVal;
vector<float> localF0;
while (true){
// find numCandidates largest values
float maxVal=-1;
int maxInd_i=0;
int maxInd_j=0;
for (int I=0; I<numCandidates; I++){
vector<int> localInd;
for (int i=0; i<numCandidates; i++){
for (int j=0; j<numCandidates; j++){
if (G[i][j]>maxVal){
maxVal=G[i][j];
maxInd_i=i;
maxInd_j=j;
}
}
}
localInd.push_back(maxInd_i);
localInd.push_back(maxInd_j);
selCandInd.push_back(localInd);
selCandVal.push_back(G[maxInd_i][maxInd_j]);
G[maxInd_i][maxInd_j]=-1;
maxVal=-1;
maxInd_i=0;
maxInd_j=0;
}
// re-estimate polyphony
p++;
float Snew=selCandVal[argmax(selCandVal)]/(pow(p,gamma));
cout << S << " " << Snew << endl;
if (Snew>S){
finalSelection.clear();
for (int i=0; i<selCandInd[0].size(); i++){
finalSelection.push_back(selCandInd[0][i]);
}
// re-calculate goddess function
for (int i=0; i<numCandidates; i++){
for (int j=0; j<numCandidates; j++){
G[i][j]+=frameSalienceValues[j];
for (int ii=0; ii<selCandInd[i].size(); ii++){
G[i][j]-=(inh[selCandInd[i][ii]][j]+inh[j][selCandInd[i][ii]]);
}
}
}
S=Snew;
}else{
// add estimated f0 to frame
for (int i=0; i<finalSelection.size(); i++){
float freq=referenceFrequency * pow(centToHertzBase, frameSalienceBins[finalSelection[i]]);
localF0.push_back(freq);
}
break;
}
}
pitch.push_back(localF0);
}
}
int MultiPitch::frequencyToCentBin(Real frequency) {
// +0.5 term is used instead of +1 (as in [1]) to center 0th bin to 55Hz
// formula: floor(1200 * log2(frequency / _referenceFrequency) / _binResolution + 0.5)
// --> 1200 * (log2(frequency) - log2(_referenceFrequency)) / _binResolution + 0.5
// --> 1200 * log2(frequency) / _binResolution + (0.5 - 1200 * log2(_referenceFrequency) / _binResolution)
return floor(binsInOctave * log2(frequency) + referenceTerm);
}
float MultiPitch::getWeight(int centBin, int harmonicNumber){
float f=referenceFrequency * pow(centToHertzBase, centBin);
float alpha=27.0;
float beta=320.0;
float w=(f+alpha)/(harmonicNumber*f+beta);
return w;
}
MultiPitch::~MultiPitch() {
// Pre-processing
delete _frameCutter;
delete _windowing;
// Spectral peaks
delete _spectrum;
delete _spectralPeaks;
// Spectral whitening
delete _spectralWhitening;
// Pitch salience contours
delete _pitchSalienceFunction;
delete _pitchSalienceFunctionPeaks;
}
} // namespace standard
} // namespace essentia
<commit_msg>ad 406<commit_after>/*
* Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "multipitch.h"
#include "essentiamath.h"
using namespace std;
using namespace essentia;
using namespace standard;
namespace essentia {
namespace standard {
const char* MultiPitch::name = "MultiPitch";
const char* MultiPitch::version = "1.0";
const char* MultiPitch::description = DOC("This algorithm performas a joint estimation of the fundamental frequencies in each frame corresponding to the pitch of the sources of polyphonic recording. Similar to [2], the estimation is based on harmonic summation. The implementation is based on the system described in [1] with a slight modifications: The caclculation of the pitch salience function is taken from [2].
"\n"
"The output is a vector for each frame containing the estimated melody pitch values .\n"
"\n"
"References:\n"
" [1] A. Klapuri, \"Multiple Fundamental Frequency Estimation by Summing Harmonic\n"
" Amplitudes \", International Society for Music Information Retrieval Conference\n
" (2006).\n"
" [2] J. Salamon and E. Gómez, \"Melody extraction from polyphonic music\n"
" signals using pitch contour characteristics,\" IEEE Transactions on Audio,\n"
" Speech, and Language Processing, vol. 20, no. 6, pp. 1759–1770, 2012.\n\n"
);
void MultiPitch::configure() {
sampleRate = parameter("sampleRate").toReal();
frameSize = parameter("frameSize").toInt();
hopSize = parameter("hopSize").toInt();
string windowType = "hann";
zeroPaddingFactor = 4;
int maxSpectralPeaks = 100;
int numberBins=frequencyToCentBin(sampleRate/2);
centSpectrum.resize(numberBins);
referenceFrequency = parameter("referenceFrequency").toReal();
binResolution = parameter("binResolution").toReal();
Real magnitudeThreshold = parameter("magnitudeThreshold").toReal();
Real magnitudeCompression = parameter("magnitudeCompression").toReal();
numberHarmonics = parameter("numberHarmonics").toInt();
Real harmonicWeight = parameter("harmonicWeight").toReal();
Real minFrequency = parameter("minFrequency").toReal();
Real maxFrequency = parameter("maxFrequency").toReal();
numberHarmonicsMax=floor(sampleRate/maxFrequency);
numberHarmonicsMax=min(numberHarmonics,numberHarmonicsMax);
binsInSemitone = floor(100.0 / binResolution);
centToHertzBase = pow(2, binResolution / 1200.0);
binsInOctave = 1200.0 / binResolution;
referenceTerm = 0.5 - binsInOctave * log2(referenceFrequency);
// Pre-processing
_frameCutter->configure("frameSize", frameSize,
"hopSize", hopSize,
"startFromZero", false);
_windowing->configure("size", frameSize,
"zeroPadding", (zeroPaddingFactor-1) * frameSize,
"type", windowType);
// Spectral peaks
_spectrum->configure("size", frameSize * zeroPaddingFactor);
_spectralPeaks->configure(
"minFrequency", 1, // to avoid zero frequencies
"maxFrequency", 20000,
"maxPeaks", maxSpectralPeaks,
"sampleRate", sampleRate,
"magnitudeThreshold", 0,
"orderBy", "magnitude");
// Spectral whitening
_spectralWhitening->configure("sampleRate", sampleRate);
// Pitch salience contours
_pitchSalienceFunction->configure("binResolution", binResolution,
"referenceFrequency", referenceFrequency,
"magnitudeThreshold", magnitudeThreshold,
"magnitudeCompression", magnitudeCompression,
"numberHarmonics", numberHarmonics,
"harmonicWeight", harmonicWeight);
// pitch salience function peaks are considered F0 cadidates -> limit to considered frequency range
_pitchSalienceFunctionPeaks->configure("binResolution", binResolution,
"referenceFrequency", referenceFrequency,
"minFrequency", minFrequency,
"maxFrequency", maxFrequency);
}
void MultiPitch::compute() {
const vector<Real>& signal = _signal.get();
vector<vector<Real> >& pitch = _pitch.get();
if (signal.empty()) {
pitch.clear();
return;
}
// Pre-processing
vector<Real> frame;
_frameCutter->input("signal").set(signal);
_frameCutter->output("frame").set(frame);
vector<Real> frameWindowed;
_windowing->input("frame").set(frame);
_windowing->output("frame").set(frameWindowed);
// Spectral peaks
vector<Real> frameSpectrum;
_spectrum->input("frame").set(frameWindowed);
_spectrum->output("spectrum").set(frameSpectrum);
vector<Real> frameFrequencies;
vector<Real> frameMagnitudes;
_spectralPeaks->input("spectrum").set(frameSpectrum);
_spectralPeaks->output("frequencies").set(frameFrequencies);
_spectralPeaks->output("magnitudes").set(frameMagnitudes);
// Spectral whitening
vector<Real> frameWhiteMagnitudes;
_spectralWhitening->input("spectrum").set(frameSpectrum);
_spectralWhitening->input("frequencies").set(frameFrequencies);
_spectralWhitening->input("magnitudes").set(frameMagnitudes);
_spectralWhitening->output("magnitudes").set(frameWhiteMagnitudes);
// Pitch salience contours
vector<Real> frameSalience;
_pitchSalienceFunction->input("frequencies").set(frameFrequencies);
_pitchSalienceFunction->input("magnitudes").set(frameMagnitudes);
_pitchSalienceFunction->output("salienceFunction").set(frameSalience);
vector<Real> frameSalienceBins;
vector<Real> frameSalienceValues;
_pitchSalienceFunctionPeaks->input("salienceFunction").set(frameSalience);
_pitchSalienceFunctionPeaks->output("salienceBins").set(frameSalienceBins);
_pitchSalienceFunctionPeaks->output("salienceValues").set(frameSalienceValues);
vector<vector<Real> > peakBins;
vector<vector<Real> > peakSaliences;
vector<Real> nearestBinWeights;
nearestBinWeights.resize(binsInSemitone + 1);
for (int b=0; b <= binsInSemitone; b++) {
nearestBinWeights[b] = pow(cos((Real(b)/binsInSemitone)* M_PI/2), 2);
}
vector<Real> harmonicWeights;
harmonicWeights.clear();
harmonicWeights.reserve(numberHarmonicsMax);
for (int h=0; h<numberHarmonicsMax; h++) {
harmonicWeights.push_back(pow(0.8, h));
}
while (true) {
// get a frame
_frameCutter->compute();
if (!frame.size()) {
break;
}
_windowing->compute();
// calculate spectrum
_spectrum->compute();
// calculate spectral peaks
_spectralPeaks->compute();
// whiten the spectrum
_spectralWhitening->compute();
// calculate salience function
_pitchSalienceFunction->compute();
// calculate peaks of salience function
_pitchSalienceFunctionPeaks->compute();
// no peaks in this frame
if (!frameSalienceBins.size()){
continue;
}
///////////////////////////////////////////////////////////////////////
// Joint F0 estimation (pitch salience function peaks as candidates) //
///////////////////////////////////////////////////////////////////////
// compute the cent-scaled spectrum
fill(centSpectrum.begin(), centSpectrum.end(), (Real) 0.0);
for (int i=0; i<frameSpectrum.size(); i++){
float f=(float(i)/float(frameSpectrum.size()))*(sampleRate/2);
int k=frequencyToCentBin(f);
if (k>0 && k<numberBins){
centSpectrum[k]=centSpectrum[k]+frameSpectrum[i];
}
}
// get indices corresponding to harmonics of each found peak
vector<vector<int> > kPeaks;
for (int i=0; i<frameSalienceBins.size(); i++){
vector<int> k;
float f=referenceFrequency * pow(centToHertzBase, frameSalienceBins[i]);
for (int m=0; m<numberHarmonicsMax; m++){
// find the exact peak for each harmonic
int kBin=frequencyToCentBin(f*(m+1));
int kBinMin=max(0, int(kBin-binsInSemitone));
int kBinMax=min(numberBins,int(kBin+binsInSemitone));
vector<float> specSegment;
for (int ii=kBinMin; ii<=kBinMax; ii++){
specSegment.push_back(centSpectrum[ii]);
}
kBin=kBinMin+argmax(specSegment)-1;
k.push_back(kBin);
}
kPeaks.push_back(k);
}
// candidate Spectra
vector<vector<Real> > Z;
for (int i=0; i<frameSalienceBins.size(); i++){
vector<Real> z;
z.resize(centSpectrum.size());
fill(z.begin(), z.end(), (Real) 0.0);
for (int h=0; h<numberHarmonicsMax; h++) {
int hBin = kPeaks[i][h];
for(int b=max(0, hBin-binsInSemitone); b <= min(numberBins-1, hBin+binsInSemitone); b++) {
z[b] += nearestBinWeights[abs(b-hBin)] * getWeight(hBin,h) * 0.25; // 0.25 is cancellation parameter
}
}
Z.push_back(z);
}
// inhibition function
int numCandidates=frameSalienceBins.size();
float inh[numCandidates][numCandidates];
for (int i=0; i<numCandidates; i++){
for (int j=0; j<numCandidates; j++){
inh[i][j]=0;
for (int m=0; m<numberHarmonicsMax; m++){
inh[i][j]+=getWeight(kPeaks[i][m],m)*centSpectrum[kPeaks[i][m]]*Z[j][kPeaks[i][m]];
}
}
}
// goodess function init
float G_init[numCandidates];
for (int i=0; i<numCandidates; i++){
G_init[i]=frameSalienceValues[i];
}
vector<int> finalSelection;
// polyphony estimation init
int p=1;
float gamma=0.73;
float S=frameSalienceValues[argmax(frameSalienceValues)]/(pow(p,gamma));
finalSelection.push_back(argmax(frameSalienceValues));
// goodess function
vector<vector<float> > G;
for (int i=0; i<numCandidates; i++){
vector<float> g;
for (int j=0; j<numCandidates; j++){
if(i==j){
g.push_back(0.0);
}else{
float g_val=G_init[i]+frameSalienceValues[j]-(inh[i][j]+inh[j][i]);
g.push_back(g_val);
}
}
G.push_back(g);
}
vector<vector<int> > selCandInd;
vector<float> selCandVal;
vector<float> localF0;
while (true){
// find numCandidates largest values
float maxVal=-1;
int maxInd_i=0;
int maxInd_j=0;
for (int I=0; I<numCandidates; I++){
vector<int> localInd;
for (int i=0; i<numCandidates; i++){
for (int j=0; j<numCandidates; j++){
if (G[i][j]>maxVal){
maxVal=G[i][j];
maxInd_i=i;
maxInd_j=j;
}
}
}
localInd.push_back(maxInd_i);
localInd.push_back(maxInd_j);
selCandInd.push_back(localInd);
selCandVal.push_back(G[maxInd_i][maxInd_j]);
G[maxInd_i][maxInd_j]=-1;
maxVal=-1;
maxInd_i=0;
maxInd_j=0;
}
// re-estimate polyphony
p++;
float Snew=selCandVal[argmax(selCandVal)]/(pow(p,gamma));
cout << S << " " << Snew << endl;
if (Snew>S){
finalSelection.clear();
for (int i=0; i<selCandInd[0].size(); i++){
finalSelection.push_back(selCandInd[0][i]);
}
// re-calculate goddess function
for (int i=0; i<numCandidates; i++){
for (int j=0; j<numCandidates; j++){
G[i][j]+=frameSalienceValues[j];
for (int ii=0; ii<selCandInd[i].size(); ii++){
G[i][j]-=(inh[selCandInd[i][ii]][j]+inh[j][selCandInd[i][ii]]);
}
}
}
S=Snew;
}else{
// add estimated f0 to frame
for (int i=0; i<finalSelection.size(); i++){
float freq=referenceFrequency * pow(centToHertzBase, frameSalienceBins[finalSelection[i]]);
localF0.push_back(freq);
}
break;
}
}
pitch.push_back(localF0);
}
}
int MultiPitch::frequencyToCentBin(Real frequency) {
// +0.5 term is used instead of +1 (as in [1]) to center 0th bin to 55Hz
// formula: floor(1200 * log2(frequency / _referenceFrequency) / _binResolution + 0.5)
// --> 1200 * (log2(frequency) - log2(_referenceFrequency)) / _binResolution + 0.5
// --> 1200 * log2(frequency) / _binResolution + (0.5 - 1200 * log2(_referenceFrequency) / _binResolution)
return floor(binsInOctave * log2(frequency) + referenceTerm);
}
float MultiPitch::getWeight(int centBin, int harmonicNumber){
float f=referenceFrequency * pow(centToHertzBase, centBin);
float alpha=27.0;
float beta=320.0;
float w=(f+alpha)/(harmonicNumber*f+beta);
return w;
}
MultiPitch::~MultiPitch() {
// Pre-processing
delete _frameCutter;
delete _windowing;
// Spectral peaks
delete _spectrum;
delete _spectralPeaks;
// Spectral whitening
delete _spectralWhitening;
// Pitch salience contours
delete _pitchSalienceFunction;
delete _pitchSalienceFunctionPeaks;
}
} // namespace standard
} // namespace essentia
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: genericunodialog.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: kz $ $Date: 2008-03-05 18:23:00 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#ifndef _SVT_GENERICUNODIALOG_HXX_
#include "genericunodialog.hxx"
#endif
#ifndef _TOOLKIT_AWT_VCLXWINDOW_HXX_
#include <toolkit/awt/vclxwindow.hxx>
#endif
#ifndef _CPPUHELPER_EXTRACT_HXX_
#include <cppuhelper/extract.hxx>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef TOOLS_DIAGNOSE_EX_H
#include <tools/diagnose_ex.h>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
// --- needed because of the solar mutex
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
// ---
#define THISREF() static_cast< XServiceInfo* >(this)
using namespace ::comphelper;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
//.........................................................................
namespace svt
{
//.........................................................................
//=========================================================================
//-------------------------------------------------------------------------
OGenericUnoDialog::OGenericUnoDialog(const Reference< XMultiServiceFactory >& _rxORB)
:OPropertyContainer(GetBroadcastHelper())
,m_pDialog(NULL)
,m_bExecuting(sal_False)
,m_bCanceled(sal_False)
,m_bTitleAmbiguous(sal_True)
,m_xORB(_rxORB)
{
registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_TITLE), UNODIALOG_PROPERTY_ID_TITLE, PropertyAttribute::TRANSIENT,
&m_sTitle, getCppuType(&m_sTitle));
registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_PARENT), UNODIALOG_PROPERTY_ID_PARENT, PropertyAttribute::TRANSIENT,
&m_xParent, getCppuType(&m_xParent));
}
//-------------------------------------------------------------------------
OGenericUnoDialog::OGenericUnoDialog(const Reference< XComponentContext >& _rxContext)
:OPropertyContainer(GetBroadcastHelper())
,m_pDialog(NULL)
,m_bExecuting(sal_False)
,m_bCanceled(sal_False)
,m_bTitleAmbiguous(sal_True)
,m_xORB( _rxContext->getServiceManager(), UNO_QUERY_THROW )
,m_xContext(_rxContext)
{
registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_TITLE), UNODIALOG_PROPERTY_ID_TITLE, PropertyAttribute::TRANSIENT,
&m_sTitle, getCppuType(&m_sTitle));
registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_PARENT), UNODIALOG_PROPERTY_ID_PARENT, PropertyAttribute::TRANSIENT,
&m_xParent, getCppuType(&m_xParent));
}
//-------------------------------------------------------------------------
OGenericUnoDialog::~OGenericUnoDialog()
{
if (m_pDialog)
{
::osl::MutexGuard aGuard(m_aMutex);
if (m_pDialog)
destroyDialog();
}
}
//-------------------------------------------------------------------------
Any SAL_CALL OGenericUnoDialog::queryInterface(const Type& _rType) throw (RuntimeException)
{
Any aReturn = OGenericUnoDialogBase::queryInterface(_rType);
if (!aReturn.hasValue())
aReturn = ::cppu::queryInterface(_rType
,static_cast<XPropertySet*>(this)
,static_cast<XMultiPropertySet*>(this)
,static_cast<XFastPropertySet*>(this)
);
return aReturn;
}
//-------------------------------------------------------------------------
Sequence<Type> SAL_CALL OGenericUnoDialog::getTypes( ) throw(RuntimeException)
{
Sequence<Type> aTypes = OGenericUnoDialogBase::getTypes();
sal_Int32 nLen = aTypes.getLength();
aTypes.realloc(nLen + 3);
aTypes.getArray()[nLen++] = ::getCppuType(static_cast<Reference<XPropertySet>*>(NULL));
aTypes.getArray()[nLen++] = ::getCppuType(static_cast<Reference<XFastPropertySet>*>(NULL));
aTypes.getArray()[nLen++] = ::getCppuType(static_cast<Reference<XMultiPropertySet>*>(NULL));
return aTypes;
}
//-------------------------------------------------------------------------
Sequence<sal_Int8> SAL_CALL OGenericUnoDialog::getImplementationId( ) throw(RuntimeException)
{
static ::cppu::OImplementationId aId;
return aId.getImplementationId();
}
//-------------------------------------------------------------------------
sal_Bool SAL_CALL OGenericUnoDialog::supportsService(const ::rtl::OUString& ServiceName) throw(RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
const ::rtl::OUString* pArray = aSupported.getConstArray();
for (sal_Int32 i = 0; i < aSupported.getLength(); ++i, ++pArray)
if (pArray->equals(ServiceName))
return sal_True;
return sal_False;
}
//-------------------------------------------------------------------------
void OGenericUnoDialog::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const Any& rValue ) throw(Exception)
{
// TODO : need some handling if we're currently executing ...
OPropertyContainer::setFastPropertyValue_NoBroadcast(nHandle, rValue);
if (UNODIALOG_PROPERTY_ID_TITLE == nHandle)
{
// from now on m_sTitle is valid
m_bTitleAmbiguous = sal_False;
if (m_pDialog)
m_pDialog->SetText(String(m_sTitle));
}
// TODO : need to be a dispose listener on the interface ...
}
//-------------------------------------------------------------------------
sal_Bool OGenericUnoDialog::convertFastPropertyValue( Any& rConvertedValue, Any& rOldValue, sal_Int32 nHandle, const Any& rValue) throw(IllegalArgumentException)
{
switch (nHandle)
{
case UNODIALOG_PROPERTY_ID_PARENT:
{
Reference<starawt::XWindow> xNew;
::cppu::extractInterface(xNew, rValue);
if (xNew != m_xParent)
{
rConvertedValue <<= xNew;
rOldValue <<= m_xParent;
return sal_True;
}
return sal_False;
}
}
return OPropertyContainer::convertFastPropertyValue(rConvertedValue, rOldValue, nHandle, rValue);
}
//-------------------------------------------------------------------------
void SAL_CALL OGenericUnoDialog::setTitle( const ::rtl::OUString& _rTitle ) throw(RuntimeException)
{
try
{
setPropertyValue(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_TITLE), makeAny(_rTitle));
}
catch(RuntimeException&)
{
// allowed to pass
throw;
}
catch(Exception&)
{
// not allowed to pass
}
}
//-------------------------------------------------------------------------
bool OGenericUnoDialog::impl_ensureDialog_lck()
{
if ( m_pDialog )
return true;
// get the parameters for the dialog from the current settings
// the parent window
Window* pParent = NULL;
VCLXWindow* pImplementation = VCLXWindow::GetImplementation(m_xParent);
if (pImplementation)
pParent = pImplementation->GetWindow();
// the title
String sTitle = m_sTitle;
Dialog* pDialog = createDialog( pParent );
OSL_ENSURE( pDialog, "OGenericUnoDialog::impl_ensureDialog_lck: createDialog returned nonsense!" );
if ( !pDialog )
return false;
// do some initialisations
if ( !m_bTitleAmbiguous )
pDialog->SetText( sTitle );
// be notified when the dialog is killed by somebody else
// #i65958# / 2006-07-07 / frank.schoenheit@sun.com
pDialog->AddEventListener( LINK( this, OGenericUnoDialog, OnDialogDying ) );
m_pDialog = pDialog;
return true;
}
//-------------------------------------------------------------------------
sal_Int16 SAL_CALL OGenericUnoDialog::execute( ) throw(RuntimeException)
{
// both creation and execution of the dialog must be guarded with the SolarMutex, so be generous here
::vos::OGuard aSolarGuard( Application::GetSolarMutex() );
Dialog* pDialogToExecute = NULL;
// create the dialog, if neccessary
{
::osl::MutexGuard aGuard(m_aMutex);
if (m_bExecuting)
throw RuntimeException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("already executing the dialog (recursive call)")), THISREF());
m_bCanceled = sal_False;
m_bExecuting = sal_True;
if ( !impl_ensureDialog_lck() )
return 0;
pDialogToExecute = m_pDialog;
}
// start execution
sal_Int16 nReturn(0);
if ( pDialogToExecute )
nReturn = pDialogToExecute->Execute();
{
::osl::MutexGuard aExecutionGuard(m_aExecutionMutex);
if (m_bCanceled)
nReturn = RET_CANCEL;
}
{
::osl::MutexGuard aGuard(m_aMutex);
// get the settings of the dialog
executedDialog( nReturn );
m_bExecuting = sal_False;
}
// outta here
return nReturn;
}
#ifdef AWT_DIALOG
//-------------------------------------------------------------------------
void SAL_CALL OGenericUnoDialog::endExecute( ) throw(RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
if (!m_bExecuting)
throw RuntimeException();
{
::osl::MutexGuard aExecutionGuard(m_aExecutionMutex);
OSL_ENSURE(m_pDialog, "OGenericUnoDialog::endExecute : executing which dialog ?");
// m_bExecuting is true but we have no dialog ?
if (!m_pDialog)
throw RuntimeException();
if (!m_pDialog->IsInExecute())
// we tighly missed it ... another thread finished the execution of the dialog,
// but did not manage it to reset m_bExecuting, it currently tries to acquire
// m_aMutex or m_aExecutionMutex
// => nothing to do
return;
m_pDialog->EndDialog(RET_CANCEL);
m_bCanceled = sal_True;
}
}
#endif
//-------------------------------------------------------------------------
void OGenericUnoDialog::implInitialize(const Any& _rValue)
{
::osl::MutexGuard aGuard(m_aMutex);
try
{
PropertyValue aProperty;
NamedValue aValue;
if ( _rValue >>= aProperty )
{
setPropertyValue( aProperty.Name, aProperty.Value );
}
else if ( _rValue >>= aValue )
{
setPropertyValue( aValue.Name, aValue.Value );
}
}
catch(const Exception&)
{
DBG_UNHANDLED_EXCEPTION();
}
}
//-------------------------------------------------------------------------
void SAL_CALL OGenericUnoDialog::initialize( const Sequence< Any >& aArguments ) throw(Exception, RuntimeException)
{
const Any* pArguments = aArguments.getConstArray();
for (sal_Int32 i=0; i<aArguments.getLength(); ++i, ++pArguments)
implInitialize(*pArguments);
}
//-------------------------------------------------------------------------
void OGenericUnoDialog::destroyDialog()
{
::vos::OGuard aSolarGuard(Application::GetSolarMutex());
delete m_pDialog;
m_pDialog = NULL;
}
//-------------------------------------------------------------------------
IMPL_LINK( OGenericUnoDialog, OnDialogDying, VclWindowEvent*, _pEvent )
{
OSL_ENSURE( _pEvent->GetWindow() == m_pDialog, "OGenericUnoDialog::OnDialogDying: where does this come from?" );
if ( _pEvent->GetId() == VCLEVENT_OBJECT_DYING )
m_pDialog = NULL;
return 0L;
}
//.........................................................................
} // namespace svt
//.........................................................................
<commit_msg>INTEGRATION: CWS odbmacros2 (1.11.126); FILE MERGED 2008/01/24 10:11:35 fs 1.11.126.2: #i49133# support for derived classes which actually *require* (not only allow) initialization 2008/01/21 12:33:45 fs 1.11.126.1: #i10000#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: genericunodialog.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: kz $ $Date: 2008-03-06 19:26:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include "svtools/genericunodialog.hxx"
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/ucb/AlreadyInitializedException.hpp>
#include <toolkit/awt/vclxwindow.hxx>
#include <cppuhelper/extract.hxx>
#include <cppuhelper/typeprovider.hxx>
#include <comphelper/property.hxx>
#include <osl/diagnose.h>
#include <tools/diagnose_ex.h>
#include <vcl/msgbox.hxx>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>
using namespace ::comphelper;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::ucb;
//.........................................................................
namespace svt
{
//.........................................................................
//=========================================================================
//-------------------------------------------------------------------------
OGenericUnoDialog::OGenericUnoDialog(const Reference< XMultiServiceFactory >& _rxORB)
:OPropertyContainer(GetBroadcastHelper())
,m_pDialog(NULL)
,m_bExecuting(sal_False)
,m_bCanceled(sal_False)
,m_bTitleAmbiguous(sal_True)
,m_bInitialized( false )
,m_bNeedInitialization( false )
,m_xORB( _rxORB )
{
registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_TITLE), UNODIALOG_PROPERTY_ID_TITLE, PropertyAttribute::TRANSIENT,
&m_sTitle, getCppuType(&m_sTitle));
registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_PARENT), UNODIALOG_PROPERTY_ID_PARENT, PropertyAttribute::TRANSIENT,
&m_xParent, getCppuType(&m_xParent));
}
//-------------------------------------------------------------------------
OGenericUnoDialog::OGenericUnoDialog(const Reference< XComponentContext >& _rxContext)
:OPropertyContainer(GetBroadcastHelper())
,m_pDialog(NULL)
,m_bExecuting(sal_False)
,m_bCanceled(sal_False)
,m_bTitleAmbiguous(sal_True)
,m_bInitialized( false )
,m_bNeedInitialization( false )
,m_xORB( _rxContext->getServiceManager(), UNO_QUERY_THROW )
,m_xContext(_rxContext)
{
registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_TITLE), UNODIALOG_PROPERTY_ID_TITLE, PropertyAttribute::TRANSIENT,
&m_sTitle, getCppuType(&m_sTitle));
registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_PARENT), UNODIALOG_PROPERTY_ID_PARENT, PropertyAttribute::TRANSIENT,
&m_xParent, getCppuType(&m_xParent));
}
//-------------------------------------------------------------------------
OGenericUnoDialog::~OGenericUnoDialog()
{
if ( m_pDialog )
{
::vos::OGuard aSolarGuard( Application::GetSolarMutex() );
::osl::MutexGuard aGuard( m_aMutex );
if ( m_pDialog )
destroyDialog();
}
}
//-------------------------------------------------------------------------
Any SAL_CALL OGenericUnoDialog::queryInterface(const Type& _rType) throw (RuntimeException)
{
Any aReturn = OGenericUnoDialogBase::queryInterface(_rType);
if (!aReturn.hasValue())
aReturn = ::cppu::queryInterface(_rType
,static_cast<XPropertySet*>(this)
,static_cast<XMultiPropertySet*>(this)
,static_cast<XFastPropertySet*>(this)
);
return aReturn;
}
//-------------------------------------------------------------------------
Sequence<Type> SAL_CALL OGenericUnoDialog::getTypes( ) throw(RuntimeException)
{
return ::comphelper::concatSequences(
OGenericUnoDialogBase::getTypes(),
::comphelper::OPropertyContainer::getTypes()
);
}
//-------------------------------------------------------------------------
Sequence<sal_Int8> SAL_CALL OGenericUnoDialog::getImplementationId( ) throw(RuntimeException)
{
static ::cppu::OImplementationId aId;
return aId.getImplementationId();
}
//-------------------------------------------------------------------------
sal_Bool SAL_CALL OGenericUnoDialog::supportsService(const ::rtl::OUString& ServiceName) throw(RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
const ::rtl::OUString* pArray = aSupported.getConstArray();
for (sal_Int32 i = 0; i < aSupported.getLength(); ++i, ++pArray)
if (pArray->equals(ServiceName))
return sal_True;
return sal_False;
}
//-------------------------------------------------------------------------
void OGenericUnoDialog::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const Any& rValue ) throw(Exception)
{
// TODO : need some handling if we're currently executing ...
OPropertyContainer::setFastPropertyValue_NoBroadcast(nHandle, rValue);
if (UNODIALOG_PROPERTY_ID_TITLE == nHandle)
{
// from now on m_sTitle is valid
m_bTitleAmbiguous = sal_False;
if (m_pDialog)
m_pDialog->SetText(String(m_sTitle));
}
}
//-------------------------------------------------------------------------
sal_Bool OGenericUnoDialog::convertFastPropertyValue( Any& rConvertedValue, Any& rOldValue, sal_Int32 nHandle, const Any& rValue) throw(IllegalArgumentException)
{
switch (nHandle)
{
case UNODIALOG_PROPERTY_ID_PARENT:
{
Reference<starawt::XWindow> xNew;
::cppu::extractInterface(xNew, rValue);
if (xNew != m_xParent)
{
rConvertedValue <<= xNew;
rOldValue <<= m_xParent;
return sal_True;
}
return sal_False;
}
}
return OPropertyContainer::convertFastPropertyValue(rConvertedValue, rOldValue, nHandle, rValue);
}
//-------------------------------------------------------------------------
void SAL_CALL OGenericUnoDialog::setTitle( const ::rtl::OUString& _rTitle ) throw(RuntimeException)
{
UnoDialogEntryGuard aGuard( *this );
try
{
setPropertyValue(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_TITLE), makeAny(_rTitle));
}
catch(RuntimeException&)
{
// allowed to pass
throw;
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
// not allowed to pass
}
}
//-------------------------------------------------------------------------
bool OGenericUnoDialog::impl_ensureDialog_lck()
{
if ( m_pDialog )
return true;
// get the parameters for the dialog from the current settings
// the parent window
Window* pParent = NULL;
VCLXWindow* pImplementation = VCLXWindow::GetImplementation(m_xParent);
if (pImplementation)
pParent = pImplementation->GetWindow();
// the title
String sTitle = m_sTitle;
Dialog* pDialog = createDialog( pParent );
OSL_ENSURE( pDialog, "OGenericUnoDialog::impl_ensureDialog_lck: createDialog returned nonsense!" );
if ( !pDialog )
return false;
// do some initialisations
if ( !m_bTitleAmbiguous )
pDialog->SetText( sTitle );
// be notified when the dialog is killed by somebody else
// #i65958# / 2006-07-07 / frank.schoenheit@sun.com
pDialog->AddEventListener( LINK( this, OGenericUnoDialog, OnDialogDying ) );
m_pDialog = pDialog;
return true;
}
//-------------------------------------------------------------------------
sal_Int16 SAL_CALL OGenericUnoDialog::execute( ) throw(RuntimeException)
{
// both creation and execution of the dialog must be guarded with the SolarMutex, so be generous here
::vos::OGuard aSolarGuard( Application::GetSolarMutex() );
Dialog* pDialogToExecute = NULL;
// create the dialog, if neccessary
{
UnoDialogEntryGuard aGuard( *this );
if (m_bExecuting)
throw RuntimeException(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "already executing the dialog (recursive call)" ) ),
*this
);
m_bCanceled = sal_False;
m_bExecuting = sal_True;
if ( !impl_ensureDialog_lck() )
return 0;
pDialogToExecute = m_pDialog;
}
// start execution
sal_Int16 nReturn(0);
if ( pDialogToExecute )
nReturn = pDialogToExecute->Execute();
{
::osl::MutexGuard aExecutionGuard(m_aExecutionMutex);
if (m_bCanceled)
nReturn = RET_CANCEL;
}
{
::osl::MutexGuard aGuard(m_aMutex);
// get the settings of the dialog
executedDialog( nReturn );
m_bExecuting = sal_False;
}
// outta here
return nReturn;
}
#ifdef AWT_DIALOG
//-------------------------------------------------------------------------
void SAL_CALL OGenericUnoDialog::endExecute( ) throw(RuntimeException)
{
UnoDialogEntryGuard aGuard( *this );
if (!m_bExecuting)
throw RuntimeException();
{
::osl::MutexGuard aExecutionGuard(m_aExecutionMutex);
OSL_ENSURE(m_pDialog, "OGenericUnoDialog::endExecute : executing which dialog ?");
// m_bExecuting is true but we have no dialog ?
if (!m_pDialog)
throw RuntimeException();
if (!m_pDialog->IsInExecute())
// we tighly missed it ... another thread finished the execution of the dialog,
// but did not manage it to reset m_bExecuting, it currently tries to acquire
// m_aMutex or m_aExecutionMutex
// => nothing to do
return;
m_pDialog->EndDialog(RET_CANCEL);
m_bCanceled = sal_True;
}
}
#endif
//-------------------------------------------------------------------------
void OGenericUnoDialog::implInitialize(const Any& _rValue)
{
try
{
PropertyValue aProperty;
NamedValue aValue;
if ( _rValue >>= aProperty )
{
setPropertyValue( aProperty.Name, aProperty.Value );
}
else if ( _rValue >>= aValue )
{
setPropertyValue( aValue.Name, aValue.Value );
}
}
catch(const Exception&)
{
DBG_UNHANDLED_EXCEPTION();
}
}
//-------------------------------------------------------------------------
void SAL_CALL OGenericUnoDialog::initialize( const Sequence< Any >& aArguments ) throw(Exception, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_bInitialized )
throw AlreadyInitializedException( ::rtl::OUString(), *this );
const Any* pArguments = aArguments.getConstArray();
for (sal_Int32 i=0; i<aArguments.getLength(); ++i, ++pArguments)
implInitialize(*pArguments);
m_bInitialized = true;
}
//-------------------------------------------------------------------------
void OGenericUnoDialog::destroyDialog()
{
delete m_pDialog;
m_pDialog = NULL;
}
//-------------------------------------------------------------------------
IMPL_LINK( OGenericUnoDialog, OnDialogDying, VclWindowEvent*, _pEvent )
{
OSL_ENSURE( _pEvent->GetWindow() == m_pDialog, "OGenericUnoDialog::OnDialogDying: where does this come from?" );
if ( _pEvent->GetId() == VCLEVENT_OBJECT_DYING )
m_pDialog = NULL;
return 0L;
}
//.........................................................................
} // namespace svt
//.........................................................................
<|endoftext|>
|
<commit_before><commit_msg>More compat stuff<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SwXMLBlockExport.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2006-08-14 16:31:24 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SW_XMLBLOCKEXPORT_HXX
#include <SwXMLBlockExport.hxx>
#endif
#ifndef _SW_XMLTEXTBLOCKS_HXX
#include <SwXMLTextBlocks.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
using namespace ::xmloff::token;
using namespace ::rtl;
// #110680#
SwXMLBlockListExport::SwXMLBlockListExport(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
SwXMLTextBlocks & rBlocks,
const rtl::OUString &rFileName,
com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler)
: SvXMLExport( xServiceFactory, rFileName, rHandler ),
rBlockList(rBlocks)
{
_GetNamespaceMap().Add( GetXMLToken ( XML_NP_BLOCK_LIST ),
GetXMLToken ( XML_N_BLOCK_LIST ),
XML_NAMESPACE_BLOCKLIST );
}
sal_uInt32 SwXMLBlockListExport::exportDoc(enum XMLTokenEnum eClass)
{
GetDocHandler()->startDocument();
AddAttribute ( XML_NAMESPACE_NONE,
_GetNamespaceMap().GetAttrNameByKey ( XML_NAMESPACE_BLOCKLIST ),
_GetNamespaceMap().GetNameByKey ( XML_NAMESPACE_BLOCKLIST ) );
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_LIST_NAME,
OUString (rBlockList.GetName()));
{
SvXMLElementExport pRoot (*this, XML_NAMESPACE_BLOCKLIST, XML_BLOCK_LIST, sal_True, sal_True);
sal_uInt16 nBlocks= rBlockList.GetCount();
for ( sal_uInt16 i = 0; i < nBlocks; i++)
{
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_ABBREVIATED_NAME,
OUString(rBlockList.GetShortName(i)));
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_PACKAGE_NAME,
OUString(rBlockList.GetPackageName(i)));
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_NAME,
OUString(rBlockList.GetLongName(i)));
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_UNFORMATTED_TEXT,
rBlockList.IsOnlyTextBlock(i) ? XML_TRUE : XML_FALSE );
SvXMLElementExport aBlock( *this, XML_NAMESPACE_BLOCKLIST, XML_BLOCK, sal_True, sal_True);
}
}
GetDocHandler()->endDocument();
return 0;
}
// #110680#
SwXMLTextBlockExport::SwXMLTextBlockExport(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
SwXMLTextBlocks & rBlocks,
const rtl::OUString &rFileName,
com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler)
: SvXMLExport( xServiceFactory, rFileName, rHandler ),
rBlockList(rBlocks)
{
_GetNamespaceMap().Add( GetXMLToken ( XML_NP_BLOCK_LIST ),
GetXMLToken ( XML_N_BLOCK_LIST ),
XML_NAMESPACE_BLOCKLIST );
_GetNamespaceMap().Add( GetXMLToken ( XML_NP_OFFICE ),
GetXMLToken(XML_N_OFFICE_OOO),
XML_NAMESPACE_OFFICE );
_GetNamespaceMap().Add( GetXMLToken ( XML_NP_TEXT ),
GetXMLToken(XML_N_TEXT_OOO),
XML_NAMESPACE_TEXT );
}
sal_uInt32 SwXMLTextBlockExport::exportDoc(const String &rText)
{
GetDocHandler()->startDocument();
AddAttribute ( XML_NAMESPACE_NONE,
_GetNamespaceMap().GetAttrNameByKey ( XML_NAMESPACE_BLOCKLIST ),
_GetNamespaceMap().GetNameByKey ( XML_NAMESPACE_BLOCKLIST ) );
AddAttribute ( XML_NAMESPACE_NONE,
_GetNamespaceMap().GetAttrNameByKey ( XML_NAMESPACE_TEXT ),
_GetNamespaceMap().GetNameByKey ( XML_NAMESPACE_TEXT ) );
AddAttribute ( XML_NAMESPACE_NONE,
_GetNamespaceMap().GetAttrNameByKey ( XML_NAMESPACE_OFFICE ),
_GetNamespaceMap().GetNameByKey ( XML_NAMESPACE_OFFICE ) );
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_LIST_NAME,
OUString (rBlockList.GetName()));
{
SvXMLElementExport aDocument (*this, XML_NAMESPACE_OFFICE, XML_DOCUMENT, sal_True, sal_True);
{
SvXMLElementExport aBody (*this, XML_NAMESPACE_OFFICE, XML_BODY, sal_True, sal_True);
{
xub_StrLen nPos = 0;
do
{
String sTemp ( rText.GetToken( 0, '\015', nPos ) );
SvXMLElementExport aPara (*this, XML_NAMESPACE_TEXT, XML_P, sal_True, sal_False);
GetDocHandler()->characters(sTemp);
} while (STRING_NOTFOUND != nPos );
}
}
}
GetDocHandler()->endDocument();
return 0;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.11.2); FILE MERGED 2006/09/01 17:51:57 kaib 1.11.2.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SwXMLBlockExport.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2006-09-16 21:27:56 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _SW_XMLBLOCKEXPORT_HXX
#include <SwXMLBlockExport.hxx>
#endif
#ifndef _SW_XMLTEXTBLOCKS_HXX
#include <SwXMLTextBlocks.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
using namespace ::xmloff::token;
using namespace ::rtl;
// #110680#
SwXMLBlockListExport::SwXMLBlockListExport(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
SwXMLTextBlocks & rBlocks,
const rtl::OUString &rFileName,
com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler)
: SvXMLExport( xServiceFactory, rFileName, rHandler ),
rBlockList(rBlocks)
{
_GetNamespaceMap().Add( GetXMLToken ( XML_NP_BLOCK_LIST ),
GetXMLToken ( XML_N_BLOCK_LIST ),
XML_NAMESPACE_BLOCKLIST );
}
sal_uInt32 SwXMLBlockListExport::exportDoc(enum XMLTokenEnum eClass)
{
GetDocHandler()->startDocument();
AddAttribute ( XML_NAMESPACE_NONE,
_GetNamespaceMap().GetAttrNameByKey ( XML_NAMESPACE_BLOCKLIST ),
_GetNamespaceMap().GetNameByKey ( XML_NAMESPACE_BLOCKLIST ) );
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_LIST_NAME,
OUString (rBlockList.GetName()));
{
SvXMLElementExport pRoot (*this, XML_NAMESPACE_BLOCKLIST, XML_BLOCK_LIST, sal_True, sal_True);
sal_uInt16 nBlocks= rBlockList.GetCount();
for ( sal_uInt16 i = 0; i < nBlocks; i++)
{
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_ABBREVIATED_NAME,
OUString(rBlockList.GetShortName(i)));
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_PACKAGE_NAME,
OUString(rBlockList.GetPackageName(i)));
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_NAME,
OUString(rBlockList.GetLongName(i)));
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_UNFORMATTED_TEXT,
rBlockList.IsOnlyTextBlock(i) ? XML_TRUE : XML_FALSE );
SvXMLElementExport aBlock( *this, XML_NAMESPACE_BLOCKLIST, XML_BLOCK, sal_True, sal_True);
}
}
GetDocHandler()->endDocument();
return 0;
}
// #110680#
SwXMLTextBlockExport::SwXMLTextBlockExport(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
SwXMLTextBlocks & rBlocks,
const rtl::OUString &rFileName,
com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler)
: SvXMLExport( xServiceFactory, rFileName, rHandler ),
rBlockList(rBlocks)
{
_GetNamespaceMap().Add( GetXMLToken ( XML_NP_BLOCK_LIST ),
GetXMLToken ( XML_N_BLOCK_LIST ),
XML_NAMESPACE_BLOCKLIST );
_GetNamespaceMap().Add( GetXMLToken ( XML_NP_OFFICE ),
GetXMLToken(XML_N_OFFICE_OOO),
XML_NAMESPACE_OFFICE );
_GetNamespaceMap().Add( GetXMLToken ( XML_NP_TEXT ),
GetXMLToken(XML_N_TEXT_OOO),
XML_NAMESPACE_TEXT );
}
sal_uInt32 SwXMLTextBlockExport::exportDoc(const String &rText)
{
GetDocHandler()->startDocument();
AddAttribute ( XML_NAMESPACE_NONE,
_GetNamespaceMap().GetAttrNameByKey ( XML_NAMESPACE_BLOCKLIST ),
_GetNamespaceMap().GetNameByKey ( XML_NAMESPACE_BLOCKLIST ) );
AddAttribute ( XML_NAMESPACE_NONE,
_GetNamespaceMap().GetAttrNameByKey ( XML_NAMESPACE_TEXT ),
_GetNamespaceMap().GetNameByKey ( XML_NAMESPACE_TEXT ) );
AddAttribute ( XML_NAMESPACE_NONE,
_GetNamespaceMap().GetAttrNameByKey ( XML_NAMESPACE_OFFICE ),
_GetNamespaceMap().GetNameByKey ( XML_NAMESPACE_OFFICE ) );
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_LIST_NAME,
OUString (rBlockList.GetName()));
{
SvXMLElementExport aDocument (*this, XML_NAMESPACE_OFFICE, XML_DOCUMENT, sal_True, sal_True);
{
SvXMLElementExport aBody (*this, XML_NAMESPACE_OFFICE, XML_BODY, sal_True, sal_True);
{
xub_StrLen nPos = 0;
do
{
String sTemp ( rText.GetToken( 0, '\015', nPos ) );
SvXMLElementExport aPara (*this, XML_NAMESPACE_TEXT, XML_P, sal_True, sal_False);
GetDocHandler()->characters(sTemp);
} while (STRING_NOTFOUND != nPos );
}
}
}
GetDocHandler()->endDocument();
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sky/tools/sky_snapshot/loader.h"
#include <memory>
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "sky/tools/sky_snapshot/logging.h"
#include "sky/tools/sky_snapshot/scope.h"
#include "sky/tools/sky_snapshot/switches.h"
#include "sky/engine/tonic/parsers/packages_map.h"
namespace {
// Extract the scheme prefix ('package:' or 'file:' from )
static std::string ExtractSchemePrefix(std::string url) {
if (base::StartsWithASCII(url, "package:", true)) {
return "package:";
} else if (base::StartsWithASCII(url, "file:", true)) {
return "file:";
}
return "";
}
// Extract the path from a package: or file: url.
static std::string ExtractPath(std::string url) {
if (base::StartsWithASCII(url, "package:", true)) {
base::ReplaceFirstSubstringAfterOffset(&url, 0, "package:", "");
} else if (base::StartsWithASCII(url, "file:", true)) {
base::ReplaceFirstSubstringAfterOffset(&url, 0, "file:", "");
}
return url;
}
base::FilePath SimplifyPath(const base::FilePath& path) {
std::vector<base::FilePath::StringType> components;
path.GetComponents(&components);
auto it = components.begin();
base::FilePath result(*it++);
for (; it != components.end(); it++) {
auto& component = *it;
if (component == base::FilePath::kCurrentDirectory)
continue;
if (component == base::FilePath::kParentDirectory)
result = result.DirName();
else
result = result.Append(component);
}
return result;
}
class Loader {
public:
Loader();
void LoadPackagesMap(const base::FilePath& packages);
const std::set<std::string>& dependencies() const { return dependencies_; }
Dart_Handle CanonicalizeURL(Dart_Handle library, Dart_Handle url);
std::string GetFilePathForURL(std::string url);
std::string GetFilePathForPackageURL(std::string url);
std::string GetFilePathForFileURL(std::string url);
std::string Fetch(const std::string& url);
Dart_Handle Import(Dart_Handle url);
Dart_Handle Source(Dart_Handle library, Dart_Handle url);
void set_package_root(const base::FilePath& package_root) {
package_root_ = package_root;
}
private:
std::set<std::string> dependencies_;
base::FilePath packages_;
base::FilePath package_root_;
std::unique_ptr<tonic::PackagesMap> packages_map_;
DISALLOW_COPY_AND_ASSIGN(Loader);
};
Loader::Loader() {
}
void Loader::LoadPackagesMap(const base::FilePath& packages) {
packages_ = base::MakeAbsoluteFilePath(packages);
dependencies_.insert(packages_.AsUTF8Unsafe());
std::string packages_source;
if (!base::ReadFileToString(packages_, &packages_source)) {
fprintf(stderr, "error: Unable to load .packages file '%s'.\n",
packages_.AsUTF8Unsafe().c_str());
exit(1);
}
packages_map_.reset(new tonic::PackagesMap());
std::string error;
if (!packages_map_->Parse(packages_source, &error)) {
fprintf(stderr, "error: Unable to parse .packages file '%s'.\n%s\n",
packages_.AsUTF8Unsafe().c_str(), error.c_str());
exit(1);
}
}
Dart_Handle Loader::CanonicalizeURL(Dart_Handle library, Dart_Handle url) {
std::string string = StringFromDart(url);
if (base::StartsWithASCII(string, "dart:", true))
return url;
if (base::StartsWithASCII(string, "package:", true))
return url;
if (base::StartsWithASCII(string, "file:", true)) {
base::ReplaceFirstSubstringAfterOffset(&string, 0, "file:", "");
return StringToDart(string);;
}
std::string library_url = StringFromDart(Dart_LibraryUrl(library));
std::string prefix = ExtractSchemePrefix(library_url);
std::string path = ExtractPath(library_url);
base::FilePath base_path(path);
base::FilePath resolved_path = base_path.DirName().Append(string);
base::FilePath normalized_path = SimplifyPath(resolved_path);
return StringToDart(prefix + normalized_path.AsUTF8Unsafe());
}
std::string Loader::GetFilePathForURL(std::string url) {
if (base::StartsWithASCII(url, "package:", true))
return GetFilePathForPackageURL(url);
if (base::StartsWithASCII(url, "file:", true))
return GetFilePathForFileURL(url);
return url;
}
std::string Loader::GetFilePathForPackageURL(
std::string url) {
DCHECK(base::StartsWithASCII(url, "package:", true));
base::ReplaceFirstSubstringAfterOffset(&url, 0, "package:", "");
size_t slash = url.find('/');
if (slash == std::string::npos)
return std::string();
std::string package = url.substr(0, slash);
std::string library_path = url.substr(slash + 1);
std::string package_path = packages_map_->Resolve(package);
if (package_path.empty())
return std::string();
if (base::StartsWithASCII(package_path, "file://", true)) {
base::ReplaceFirstSubstringAfterOffset(&package_path, 0, "file://", "");
return package_path + library_path;
}
auto path = packages_.DirName().Append(package_path).Append(library_path);
return SimplifyPath(path).AsUTF8Unsafe();
}
std::string Loader::GetFilePathForFileURL(std::string url) {
DCHECK(base::StartsWithASCII(url, "file://", true));
base::ReplaceFirstSubstringAfterOffset(&url, 0, "file://", "");
return url;
}
std::string Loader::Fetch(const std::string& url) {
base::FilePath path(url);
std::string source;
if (!base::ReadFileToString(path, &source)) {
fprintf(stderr, "error: Unable to find Dart library '%s'.\n", url.c_str());
exit(1);
}
dependencies_.insert(url);
return source;
}
Dart_Handle Loader::Import(Dart_Handle url) {
Dart_Handle source = StringToDart(Fetch(StringFromDart(url)));
Dart_Handle result = Dart_LoadLibrary(url, source, 0, 0);
LogIfError(result);
return result;
}
Dart_Handle Loader::Source(Dart_Handle library, Dart_Handle url) {
Dart_Handle source = StringToDart(Fetch(StringFromDart(url)));
Dart_Handle result = Dart_LoadSource(library, url, source, 0, 0);
LogIfError(result);
return result;
}
Loader* g_loader = nullptr;
Loader& GetLoader() {
if (!g_loader) {
base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess();
g_loader = new Loader();
if (command_line.HasSwitch(switches::kPackages)) {
g_loader->LoadPackagesMap(
command_line.GetSwitchValuePath(switches::kPackages));
} else if (command_line.HasSwitch(switches::kPackageRoot)) {
g_loader->set_package_root(
command_line.GetSwitchValuePath(switches::kPackageRoot));
} else {
fprintf(stderr, "error: Need either --packages or --package-root.\n");
exit(1);
}
}
return *g_loader;
}
} // namespace
Dart_Handle HandleLibraryTag(Dart_LibraryTag tag,
Dart_Handle library,
Dart_Handle url) {
CHECK(Dart_IsLibrary(library));
CHECK(Dart_IsString(url));
if (tag == Dart_kCanonicalizeUrl)
return GetLoader().CanonicalizeURL(library, url);
if (tag == Dart_kImportTag)
return GetLoader().Import(url);
if (tag == Dart_kSourceTag)
return GetLoader().Source(library, url);
return Dart_NewApiError("Unknown library tag.");
}
void LoadScript(const std::string& url) {
LogIfError(
Dart_LoadScript(StringToDart(url), StringToDart(GetLoader().Fetch(url)),
0, 0));
}
const std::set<std::string>& GetDependencies() {
return GetLoader().dependencies();
}
<commit_msg>Fix Loader::Fetch to use the file path and not the uri.<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sky/tools/sky_snapshot/loader.h"
#include <memory>
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "sky/tools/sky_snapshot/logging.h"
#include "sky/tools/sky_snapshot/scope.h"
#include "sky/tools/sky_snapshot/switches.h"
#include "sky/engine/tonic/parsers/packages_map.h"
namespace {
// Extract the scheme prefix ('package:' or 'file:' from )
static std::string ExtractSchemePrefix(std::string url) {
if (base::StartsWithASCII(url, "package:", true)) {
return "package:";
} else if (base::StartsWithASCII(url, "file:", true)) {
return "file:";
}
return "";
}
// Extract the path from a package: or file: url.
static std::string ExtractPath(std::string url) {
if (base::StartsWithASCII(url, "package:", true)) {
base::ReplaceFirstSubstringAfterOffset(&url, 0, "package:", "");
} else if (base::StartsWithASCII(url, "file:", true)) {
base::ReplaceFirstSubstringAfterOffset(&url, 0, "file:", "");
}
return url;
}
base::FilePath SimplifyPath(const base::FilePath& path) {
std::vector<base::FilePath::StringType> components;
path.GetComponents(&components);
auto it = components.begin();
base::FilePath result(*it++);
for (; it != components.end(); it++) {
auto& component = *it;
if (component == base::FilePath::kCurrentDirectory)
continue;
if (component == base::FilePath::kParentDirectory)
result = result.DirName();
else
result = result.Append(component);
}
return result;
}
class Loader {
public:
Loader();
void LoadPackagesMap(const base::FilePath& packages);
const std::set<std::string>& dependencies() const { return dependencies_; }
Dart_Handle CanonicalizeURL(Dart_Handle library, Dart_Handle url);
std::string GetFilePathForURL(std::string url);
std::string GetFilePathForPackageURL(std::string url);
std::string GetFilePathForFileURL(std::string url);
std::string Fetch(const std::string& url);
Dart_Handle Import(Dart_Handle url);
Dart_Handle Source(Dart_Handle library, Dart_Handle url);
void set_package_root(const base::FilePath& package_root) {
package_root_ = package_root;
}
private:
std::set<std::string> dependencies_;
base::FilePath packages_;
base::FilePath package_root_;
std::unique_ptr<tonic::PackagesMap> packages_map_;
DISALLOW_COPY_AND_ASSIGN(Loader);
};
Loader::Loader() {
}
void Loader::LoadPackagesMap(const base::FilePath& packages) {
packages_ = base::MakeAbsoluteFilePath(packages);
dependencies_.insert(packages_.AsUTF8Unsafe());
std::string packages_source;
if (!base::ReadFileToString(packages_, &packages_source)) {
fprintf(stderr, "error: Unable to load .packages file '%s'.\n",
packages_.AsUTF8Unsafe().c_str());
exit(1);
}
packages_map_.reset(new tonic::PackagesMap());
std::string error;
if (!packages_map_->Parse(packages_source, &error)) {
fprintf(stderr, "error: Unable to parse .packages file '%s'.\n%s\n",
packages_.AsUTF8Unsafe().c_str(), error.c_str());
exit(1);
}
}
Dart_Handle Loader::CanonicalizeURL(Dart_Handle library, Dart_Handle url) {
std::string string = StringFromDart(url);
if (base::StartsWithASCII(string, "dart:", true))
return url;
if (base::StartsWithASCII(string, "package:", true))
return url;
if (base::StartsWithASCII(string, "file:", true)) {
base::ReplaceFirstSubstringAfterOffset(&string, 0, "file:", "");
return StringToDart(string);;
}
std::string library_url = StringFromDart(Dart_LibraryUrl(library));
std::string prefix = ExtractSchemePrefix(library_url);
std::string path = ExtractPath(library_url);
base::FilePath base_path(path);
base::FilePath resolved_path = base_path.DirName().Append(string);
base::FilePath normalized_path = SimplifyPath(resolved_path);
return StringToDart(prefix + normalized_path.AsUTF8Unsafe());
}
std::string Loader::GetFilePathForURL(std::string url) {
if (base::StartsWithASCII(url, "package:", true))
return GetFilePathForPackageURL(url);
if (base::StartsWithASCII(url, "file:", true))
return GetFilePathForFileURL(url);
return url;
}
std::string Loader::GetFilePathForPackageURL(
std::string url) {
DCHECK(base::StartsWithASCII(url, "package:", true));
base::ReplaceFirstSubstringAfterOffset(&url, 0, "package:", "");
size_t slash = url.find('/');
if (slash == std::string::npos)
return std::string();
std::string package = url.substr(0, slash);
std::string library_path = url.substr(slash + 1);
std::string package_path = packages_map_->Resolve(package);
if (package_path.empty())
return std::string();
if (base::StartsWithASCII(package_path, "file://", true)) {
base::ReplaceFirstSubstringAfterOffset(&package_path, 0, "file://", "");
return package_path + library_path;
}
auto path = packages_.DirName().Append(package_path).Append(library_path);
return SimplifyPath(path).AsUTF8Unsafe();
}
std::string Loader::GetFilePathForFileURL(std::string url) {
DCHECK(base::StartsWithASCII(url, "file://", true));
base::ReplaceFirstSubstringAfterOffset(&url, 0, "file://", "");
return url;
}
std::string Loader::Fetch(const std::string& url) {
base::FilePath path(GetFilePathForURL(url));
std::string source;
if (!base::ReadFileToString(path, &source)) {
fprintf(stderr, "error: Unable to find Dart library '%s'.\n", url.c_str());
exit(1);
}
dependencies_.insert(url);
return source;
}
Dart_Handle Loader::Import(Dart_Handle url) {
Dart_Handle source = StringToDart(Fetch(StringFromDart(url)));
Dart_Handle result = Dart_LoadLibrary(url, source, 0, 0);
LogIfError(result);
return result;
}
Dart_Handle Loader::Source(Dart_Handle library, Dart_Handle url) {
Dart_Handle source = StringToDart(Fetch(StringFromDart(url)));
Dart_Handle result = Dart_LoadSource(library, url, source, 0, 0);
LogIfError(result);
return result;
}
Loader* g_loader = nullptr;
Loader& GetLoader() {
if (!g_loader) {
base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess();
g_loader = new Loader();
if (command_line.HasSwitch(switches::kPackages)) {
g_loader->LoadPackagesMap(
command_line.GetSwitchValuePath(switches::kPackages));
} else if (command_line.HasSwitch(switches::kPackageRoot)) {
g_loader->set_package_root(
command_line.GetSwitchValuePath(switches::kPackageRoot));
} else {
fprintf(stderr, "error: Need either --packages or --package-root.\n");
exit(1);
}
}
return *g_loader;
}
} // namespace
Dart_Handle HandleLibraryTag(Dart_LibraryTag tag,
Dart_Handle library,
Dart_Handle url) {
CHECK(Dart_IsLibrary(library));
CHECK(Dart_IsString(url));
if (tag == Dart_kCanonicalizeUrl)
return GetLoader().CanonicalizeURL(library, url);
if (tag == Dart_kImportTag)
return GetLoader().Import(url);
if (tag == Dart_kSourceTag)
return GetLoader().Source(library, url);
return Dart_NewApiError("Unknown library tag.");
}
void LoadScript(const std::string& url) {
LogIfError(
Dart_LoadScript(StringToDart(url), StringToDart(GetLoader().Fetch(url)),
0, 0));
}
const std::set<std::string>& GetDependencies() {
return GetLoader().dependencies();
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <sal/config.h>
#include "ThemePanel.hxx"
#include <swtypes.hxx>
#include <cmdid.h>
#include <svl/intitem.hxx>
#include <svx/svxids.hrc>
#include <svx/dlgutil.hxx>
#include <svx/rulritem.hxx>
#include <sfx2/sidebar/ControlFactory.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/viewsh.hxx>
#include <sfx2/objsh.hxx>
#include <com/sun/star/frame/XController.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/frame/DocumentTemplates.hpp>
#include <com/sun/star/frame/XDocumentTemplates.hpp>
#include <com/sun/star/document/XUndoManagerSupplier.hpp>
#include <editeng/fontitem.hxx>
#include <editeng/boxitem.hxx>
#include <editeng/borderline.hxx>
#include "charatr.hxx"
#include "charfmt.hxx"
#include "docstyle.hxx"
#include "fmtcol.hxx"
#include "format.hxx"
namespace
{
class FontSet
{
public:
OUString maName;
OUString msMonoFont;
OUString msHeadingFont;
OUString msBaseFont;
};
class ColorSet
{
public:
OUString maName;
Color maColors[10];
Color getBackgroundColor1()
{
return maColors[0];
}
Color getTextColor1()
{
return maColors[1];
}
Color getBackgroundColor2()
{
return maColors[2];
}
Color getTextColor2()
{
return maColors[3];
}
Color getAccent1()
{
return maColors[4];
}
Color getAccent2()
{
return maColors[5];
}
Color getAccent3()
{
return maColors[6];
}
Color getAccent4()
{
return maColors[7];
}
Color getAccent5()
{
return maColors[8];
}
Color getAccent6()
{
return maColors[9];
}
};
class ColorVariable
{
public:
long mnIndex;
Color maColor;
ColorVariable()
{}
ColorVariable(Color aColor)
: mnIndex(-1)
, maColor(aColor)
{}
ColorVariable(long nIndex)
: mnIndex(nIndex)
, maColor()
{}
};
class StyleRedefinition
{
ColorVariable maVariable;
public:
OUString maElementName;
public:
StyleRedefinition(const OUString& aElementName)
: maElementName(aElementName)
{}
void setColorVariable(ColorVariable aVariable)
{
maVariable = aVariable;
}
Color getColor(ColorSet& rColorSet)
{
if (maVariable.mnIndex > -1)
{
return rColorSet.maColors[maVariable.mnIndex];
}
else
{
return maVariable.maColor;
}
}
};
class StyleSet
{
OUString maName;
std::vector<StyleRedefinition> maStyles;
public:
StyleSet(const OUString& aName)
: maName(aName)
, maStyles()
{}
void add(StyleRedefinition aRedefinition)
{
maStyles.push_back(aRedefinition);
}
StyleRedefinition* get(const OUString& aString)
{
for (size_t i = 0; i < maStyles.size(); i++)
{
if (maStyles[i].maElementName == aString)
{
return &maStyles[i];
}
}
return nullptr;
}
};
StyleSet setupThemes()
{
StyleSet aSet("Default");
StyleRedefinition aRedefinition("Heading");
aRedefinition.setColorVariable(ColorVariable(0));
aSet.add(aRedefinition);
return aSet;
}
void changeFont(SwFmt* pFormat, SwDocStyleSheet* pStyle, FontSet& rFontSet)
{
bool bChanged = false;
if (pFormat->GetAttrSet().GetItem(RES_CHRATR_FONT, false) == nullptr)
{
return;
}
SvxFontItem aFontItem(static_cast<const SvxFontItem&>(pFormat->GetFont(false)));
FontPitch ePitch = aFontItem.GetPitch();
if (ePitch == PITCH_FIXED)
{
aFontItem.SetFamilyName(rFontSet.msMonoFont);
bChanged = true;
}
else if (ePitch == PITCH_VARIABLE)
{
if (pStyle->GetName() == "Heading")
{
aFontItem.SetFamilyName(rFontSet.msHeadingFont);
bChanged = true;
}
else
{
aFontItem.SetFamilyName(rFontSet.msBaseFont);
bChanged = true;
}
}
if (bChanged)
{
pFormat->SetFmtAttr(aFontItem);
}
}
/*void changeBorder(SwTxtFmtColl* pCollection, SwDocStyleSheet* pStyle, StyleSet& rStyleSet)
{
if (pStyle->GetName() == "Heading")
{
SvxBoxItem aBoxItem(pCollection->GetBox());
editeng::SvxBorderLine aBorderLine;
aBorderLine.SetWidth(40); //20 = 1pt
aBorderLine.SetColor(rColorSet.mBaseColors[0]);
aBoxItem.SetLine(&aBorderLine, SvxBoxItemLine::BOTTOM);
pCollection->SetFmtAttr(aBoxItem);
}
}*/
void changeColor(SwTxtFmtColl* pCollection, ColorSet& rColorSet, StyleRedefinition* pRedefinition)
{
Color aColor = pRedefinition->getColor(rColorSet);
SvxColorItem aColorItem(pCollection->GetColor());
aColorItem.SetValue(aColor);
pCollection->SetFmtAttr(aColorItem);
}
std::vector<FontSet> initFontSets()
{
std::vector<FontSet> aFontSets;
{
FontSet aFontSet;
aFontSet.maName = "LibreOffice";
aFontSet.msHeadingFont = "Liberation Sans";
aFontSet.msBaseFont = "Liberation Serif";
aFontSet.msMonoFont = "Liberation Mono";
aFontSets.push_back(aFontSet);
}
{
FontSet aFontSet;
aFontSet.maName = "LibreOffice 2";
aFontSet.msHeadingFont = "DejaVu Sans";
aFontSet.msBaseFont = "DejaVu Serif";
aFontSet.msMonoFont = "DejaVu Sans Mono";
aFontSets.push_back(aFontSet);
}
{
FontSet aFontSet;
aFontSet.maName = "LibreOffice Modern";
aFontSet.msHeadingFont = "Caladea";
aFontSet.msBaseFont = "Carlito";
aFontSet.msMonoFont = "Source Code Pro";
aFontSets.push_back(aFontSet);
}
{
FontSet aFontSet;
aFontSet.maName = "LibreOffice Modern 2";
aFontSet.msHeadingFont = "Source Sans Pro";
aFontSet.msBaseFont = "Source Sans Pro";
aFontSet.msMonoFont = "Source Code Pro";
aFontSets.push_back(aFontSet);
}
{
FontSet aFontSet;
aFontSet.maName = "LibreOffice 3";
aFontSet.msHeadingFont = "Linux Biolinum";
aFontSet.msBaseFont = "Linux Libertine";
aFontSet.msMonoFont = "Liberation Mono";
aFontSets.push_back(aFontSet);
}
{
FontSet aFontSet;
aFontSet.maName = "LibreOffice 4";
aFontSet.msHeadingFont = "OpenSans";
aFontSet.msBaseFont = "OpenSans";
aFontSet.msMonoFont = "Liberation Mono";
aFontSets.push_back(aFontSet);
}
return aFontSets;
}
FontSet getFontSet(const OUString& rFontVariant, std::vector<FontSet>& aFontSets)
{
for (size_t i = 0; i < aFontSets.size(); ++i)
{
if (aFontSets[i].maName == rFontVariant)
return aFontSets[i];
}
return aFontSets[0];
}
std::vector<ColorSet> initColorSets()
{
std::vector<ColorSet> aColorSets;
{
ColorSet aColorSet;
aColorSet.maName = "Default";
aColorSet.maColors[0] = Color(0x00, 0x00, 0x00);
aColorSets.push_back(aColorSet);
}
{
ColorSet aColorSet;
aColorSet.maName = "Red";
aColorSet.maColors[0] = Color(0xa4, 0x00, 0x00);
aColorSets.push_back(aColorSet);
}
{
ColorSet aColorSet;
aColorSet.maName = "Green";
aColorSet.maColors[0] = Color(0x00, 0xa4, 0x00);
aColorSets.push_back(aColorSet);
}
{
ColorSet aColorSet;
aColorSet.maName = "Blue";
aColorSet.maColors[0] = Color(0x00, 0x00, 0xa4);
aColorSets.push_back(aColorSet);
}
return aColorSets;
}
ColorSet getColorSet(const OUString& rColorVariant, std::vector<ColorSet>& aColorSets)
{
for (size_t i = 0; i < aColorSets.size(); ++i)
{
if (aColorSets[i].maName == rColorVariant)
return aColorSets[i];
}
return aColorSets[0];
}
void applyTheme(SfxStyleSheetBasePool* pPool, const OUString& sFontSetName, const OUString& sColorSetName, StyleSet& rStyleSet)
{
SwDocStyleSheet* pStyle;
std::vector<FontSet> aFontSets = initFontSets();
FontSet aFontSet = getFontSet(sFontSetName, aFontSets);
std::vector<ColorSet> aColorSets = initColorSets();
ColorSet aColorSet = getColorSet(sColorSetName, aColorSets);
pPool->SetSearchMask(SFX_STYLE_FAMILY_PARA, SFXSTYLEBIT_ALL);
pStyle = static_cast<SwDocStyleSheet*>(pPool->First());
while (pStyle)
{
SwTxtFmtColl* pCollection = pStyle->GetCollection();
changeFont(pCollection, pStyle, aFontSet);
StyleRedefinition* pRedefinition = rStyleSet.get(pStyle->GetName());
if (pRedefinition)
{
changeColor(pCollection, aColorSet, pRedefinition);
}
pStyle = static_cast<SwDocStyleSheet*>(pPool->Next());
}
pPool->SetSearchMask(SFX_STYLE_FAMILY_CHAR, SFXSTYLEBIT_ALL);
pStyle = static_cast<SwDocStyleSheet*>(pPool->First());
while (pStyle)
{
SwCharFmt* pCharFormat = pStyle->GetCharFmt();
changeFont(static_cast<SwFmt*>(pCharFormat), pStyle, aFontSet);
pStyle = static_cast<SwDocStyleSheet*>(pPool->Next());
}
}
} // end anonymous namespace
namespace sw { namespace sidebar {
ThemePanel* ThemePanel::Create (vcl::Window* pParent,
const css::uno::Reference<css::frame::XFrame>& rxFrame,
SfxBindings* pBindings)
{
if (pParent == NULL)
throw css::lang::IllegalArgumentException("no parent Window given to PagePropertyPanel::Create", NULL, 0);
if (!rxFrame.is())
throw css::lang::IllegalArgumentException("no XFrame given to PagePropertyPanel::Create", NULL, 1);
if (pBindings == NULL)
throw css::lang::IllegalArgumentException("no SfxBindings given to PagePropertyPanel::Create", NULL, 2);
return new ThemePanel(pParent, rxFrame, pBindings);
}
ThemePanel::ThemePanel(vcl::Window* pParent,
const css::uno::Reference<css::frame::XFrame>& rxFrame,
SfxBindings* pBindings)
: PanelLayout(pParent, "ThemePanel", "modules/swriter/ui/sidebartheme.ui", rxFrame)
, mpBindings(pBindings)
{
get(mpListBoxFonts, "listbox_fonts");
get(mpListBoxColors, "listbox_colors");
get(mpApplyButton, "apply");
mpApplyButton->SetClickHdl(LINK(this, ThemePanel, ClickHdl));
mpListBoxFonts->SetDoubleClickHdl(LINK(this, ThemePanel, ClickHdl));
mpListBoxColors->SetDoubleClickHdl(LINK(this, ThemePanel, ClickHdl));
std::vector<FontSet> aFontSets = initFontSets();
for (size_t i = 0; i < aFontSets.size(); ++i)
{
mpListBoxFonts->InsertEntry(aFontSets[i].maName);
}
std::vector<ColorSet> aColorSets = initColorSets();
for (size_t i = 0; i < aColorSets.size(); ++i)
{
mpListBoxColors->InsertEntry(aColorSets[i].maName);
}
}
ThemePanel::~ThemePanel()
{
}
IMPL_LINK_NOARG(ThemePanel, ClickHdl)
{
SwDocShell* pDocSh = static_cast<SwDocShell*>(SfxObjectShell::Current());
if (pDocSh)
{
OUString sEntryFonts = mpListBoxFonts->GetSelectEntry();
OUString sEntryColors = mpListBoxColors->GetSelectEntry();
StyleSet aStyleSet = setupThemes();
applyTheme(pDocSh->GetStyleSheetPool(), sEntryFonts, sEntryColors, aStyleSet);
}
return 1;
}
void ThemePanel::NotifyItemUpdate(const sal_uInt16 /*nSId*/,
const SfxItemState /*eState*/,
const SfxPoolItem* /*pState*/,
const bool /*bIsEnabled*/)
{
}
}} // end of namespace ::sw::sidebar
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: Unreferenced function definition<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <sal/config.h>
#include "ThemePanel.hxx"
#include <swtypes.hxx>
#include <cmdid.h>
#include <svl/intitem.hxx>
#include <svx/svxids.hrc>
#include <svx/dlgutil.hxx>
#include <svx/rulritem.hxx>
#include <sfx2/sidebar/ControlFactory.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/viewsh.hxx>
#include <sfx2/objsh.hxx>
#include <com/sun/star/frame/XController.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/frame/DocumentTemplates.hpp>
#include <com/sun/star/frame/XDocumentTemplates.hpp>
#include <com/sun/star/document/XUndoManagerSupplier.hpp>
#include <editeng/fontitem.hxx>
#include <editeng/boxitem.hxx>
#include <editeng/borderline.hxx>
#include "charatr.hxx"
#include "charfmt.hxx"
#include "docstyle.hxx"
#include "fmtcol.hxx"
#include "format.hxx"
namespace
{
class FontSet
{
public:
OUString maName;
OUString msMonoFont;
OUString msHeadingFont;
OUString msBaseFont;
};
class ColorSet
{
public:
OUString maName;
Color maColors[10];
};
class ColorVariable
{
public:
long mnIndex;
Color maColor;
ColorVariable()
{}
ColorVariable(long nIndex)
: mnIndex(nIndex)
, maColor()
{}
};
class StyleRedefinition
{
ColorVariable maVariable;
public:
OUString maElementName;
public:
StyleRedefinition(const OUString& aElementName)
: maElementName(aElementName)
{}
void setColorVariable(ColorVariable aVariable)
{
maVariable = aVariable;
}
Color getColor(ColorSet& rColorSet)
{
if (maVariable.mnIndex > -1)
{
return rColorSet.maColors[maVariable.mnIndex];
}
else
{
return maVariable.maColor;
}
}
};
class StyleSet
{
OUString maName;
std::vector<StyleRedefinition> maStyles;
public:
StyleSet(const OUString& aName)
: maName(aName)
, maStyles()
{}
void add(StyleRedefinition aRedefinition)
{
maStyles.push_back(aRedefinition);
}
StyleRedefinition* get(const OUString& aString)
{
for (size_t i = 0; i < maStyles.size(); i++)
{
if (maStyles[i].maElementName == aString)
{
return &maStyles[i];
}
}
return nullptr;
}
};
StyleSet setupThemes()
{
StyleSet aSet("Default");
StyleRedefinition aRedefinition("Heading");
aRedefinition.setColorVariable(ColorVariable(0));
aSet.add(aRedefinition);
return aSet;
}
void changeFont(SwFmt* pFormat, SwDocStyleSheet* pStyle, FontSet& rFontSet)
{
bool bChanged = false;
if (pFormat->GetAttrSet().GetItem(RES_CHRATR_FONT, false) == nullptr)
{
return;
}
SvxFontItem aFontItem(static_cast<const SvxFontItem&>(pFormat->GetFont(false)));
FontPitch ePitch = aFontItem.GetPitch();
if (ePitch == PITCH_FIXED)
{
aFontItem.SetFamilyName(rFontSet.msMonoFont);
bChanged = true;
}
else if (ePitch == PITCH_VARIABLE)
{
if (pStyle->GetName() == "Heading")
{
aFontItem.SetFamilyName(rFontSet.msHeadingFont);
bChanged = true;
}
else
{
aFontItem.SetFamilyName(rFontSet.msBaseFont);
bChanged = true;
}
}
if (bChanged)
{
pFormat->SetFmtAttr(aFontItem);
}
}
/*void changeBorder(SwTxtFmtColl* pCollection, SwDocStyleSheet* pStyle, StyleSet& rStyleSet)
{
if (pStyle->GetName() == "Heading")
{
SvxBoxItem aBoxItem(pCollection->GetBox());
editeng::SvxBorderLine aBorderLine;
aBorderLine.SetWidth(40); //20 = 1pt
aBorderLine.SetColor(rColorSet.mBaseColors[0]);
aBoxItem.SetLine(&aBorderLine, SvxBoxItemLine::BOTTOM);
pCollection->SetFmtAttr(aBoxItem);
}
}*/
void changeColor(SwTxtFmtColl* pCollection, ColorSet& rColorSet, StyleRedefinition* pRedefinition)
{
Color aColor = pRedefinition->getColor(rColorSet);
SvxColorItem aColorItem(pCollection->GetColor());
aColorItem.SetValue(aColor);
pCollection->SetFmtAttr(aColorItem);
}
std::vector<FontSet> initFontSets()
{
std::vector<FontSet> aFontSets;
{
FontSet aFontSet;
aFontSet.maName = "LibreOffice";
aFontSet.msHeadingFont = "Liberation Sans";
aFontSet.msBaseFont = "Liberation Serif";
aFontSet.msMonoFont = "Liberation Mono";
aFontSets.push_back(aFontSet);
}
{
FontSet aFontSet;
aFontSet.maName = "LibreOffice 2";
aFontSet.msHeadingFont = "DejaVu Sans";
aFontSet.msBaseFont = "DejaVu Serif";
aFontSet.msMonoFont = "DejaVu Sans Mono";
aFontSets.push_back(aFontSet);
}
{
FontSet aFontSet;
aFontSet.maName = "LibreOffice Modern";
aFontSet.msHeadingFont = "Caladea";
aFontSet.msBaseFont = "Carlito";
aFontSet.msMonoFont = "Source Code Pro";
aFontSets.push_back(aFontSet);
}
{
FontSet aFontSet;
aFontSet.maName = "LibreOffice Modern 2";
aFontSet.msHeadingFont = "Source Sans Pro";
aFontSet.msBaseFont = "Source Sans Pro";
aFontSet.msMonoFont = "Source Code Pro";
aFontSets.push_back(aFontSet);
}
{
FontSet aFontSet;
aFontSet.maName = "LibreOffice 3";
aFontSet.msHeadingFont = "Linux Biolinum";
aFontSet.msBaseFont = "Linux Libertine";
aFontSet.msMonoFont = "Liberation Mono";
aFontSets.push_back(aFontSet);
}
{
FontSet aFontSet;
aFontSet.maName = "LibreOffice 4";
aFontSet.msHeadingFont = "OpenSans";
aFontSet.msBaseFont = "OpenSans";
aFontSet.msMonoFont = "Liberation Mono";
aFontSets.push_back(aFontSet);
}
return aFontSets;
}
FontSet getFontSet(const OUString& rFontVariant, std::vector<FontSet>& aFontSets)
{
for (size_t i = 0; i < aFontSets.size(); ++i)
{
if (aFontSets[i].maName == rFontVariant)
return aFontSets[i];
}
return aFontSets[0];
}
std::vector<ColorSet> initColorSets()
{
std::vector<ColorSet> aColorSets;
{
ColorSet aColorSet;
aColorSet.maName = "Default";
aColorSet.maColors[0] = Color(0x00, 0x00, 0x00);
aColorSets.push_back(aColorSet);
}
{
ColorSet aColorSet;
aColorSet.maName = "Red";
aColorSet.maColors[0] = Color(0xa4, 0x00, 0x00);
aColorSets.push_back(aColorSet);
}
{
ColorSet aColorSet;
aColorSet.maName = "Green";
aColorSet.maColors[0] = Color(0x00, 0xa4, 0x00);
aColorSets.push_back(aColorSet);
}
{
ColorSet aColorSet;
aColorSet.maName = "Blue";
aColorSet.maColors[0] = Color(0x00, 0x00, 0xa4);
aColorSets.push_back(aColorSet);
}
return aColorSets;
}
ColorSet getColorSet(const OUString& rColorVariant, std::vector<ColorSet>& aColorSets)
{
for (size_t i = 0; i < aColorSets.size(); ++i)
{
if (aColorSets[i].maName == rColorVariant)
return aColorSets[i];
}
return aColorSets[0];
}
void applyTheme(SfxStyleSheetBasePool* pPool, const OUString& sFontSetName, const OUString& sColorSetName, StyleSet& rStyleSet)
{
SwDocStyleSheet* pStyle;
std::vector<FontSet> aFontSets = initFontSets();
FontSet aFontSet = getFontSet(sFontSetName, aFontSets);
std::vector<ColorSet> aColorSets = initColorSets();
ColorSet aColorSet = getColorSet(sColorSetName, aColorSets);
pPool->SetSearchMask(SFX_STYLE_FAMILY_PARA, SFXSTYLEBIT_ALL);
pStyle = static_cast<SwDocStyleSheet*>(pPool->First());
while (pStyle)
{
SwTxtFmtColl* pCollection = pStyle->GetCollection();
changeFont(pCollection, pStyle, aFontSet);
StyleRedefinition* pRedefinition = rStyleSet.get(pStyle->GetName());
if (pRedefinition)
{
changeColor(pCollection, aColorSet, pRedefinition);
}
pStyle = static_cast<SwDocStyleSheet*>(pPool->Next());
}
pPool->SetSearchMask(SFX_STYLE_FAMILY_CHAR, SFXSTYLEBIT_ALL);
pStyle = static_cast<SwDocStyleSheet*>(pPool->First());
while (pStyle)
{
SwCharFmt* pCharFormat = pStyle->GetCharFmt();
changeFont(static_cast<SwFmt*>(pCharFormat), pStyle, aFontSet);
pStyle = static_cast<SwDocStyleSheet*>(pPool->Next());
}
}
} // end anonymous namespace
namespace sw { namespace sidebar {
ThemePanel* ThemePanel::Create (vcl::Window* pParent,
const css::uno::Reference<css::frame::XFrame>& rxFrame,
SfxBindings* pBindings)
{
if (pParent == NULL)
throw css::lang::IllegalArgumentException("no parent Window given to PagePropertyPanel::Create", NULL, 0);
if (!rxFrame.is())
throw css::lang::IllegalArgumentException("no XFrame given to PagePropertyPanel::Create", NULL, 1);
if (pBindings == NULL)
throw css::lang::IllegalArgumentException("no SfxBindings given to PagePropertyPanel::Create", NULL, 2);
return new ThemePanel(pParent, rxFrame, pBindings);
}
ThemePanel::ThemePanel(vcl::Window* pParent,
const css::uno::Reference<css::frame::XFrame>& rxFrame,
SfxBindings* pBindings)
: PanelLayout(pParent, "ThemePanel", "modules/swriter/ui/sidebartheme.ui", rxFrame)
, mpBindings(pBindings)
{
get(mpListBoxFonts, "listbox_fonts");
get(mpListBoxColors, "listbox_colors");
get(mpApplyButton, "apply");
mpApplyButton->SetClickHdl(LINK(this, ThemePanel, ClickHdl));
mpListBoxFonts->SetDoubleClickHdl(LINK(this, ThemePanel, ClickHdl));
mpListBoxColors->SetDoubleClickHdl(LINK(this, ThemePanel, ClickHdl));
std::vector<FontSet> aFontSets = initFontSets();
for (size_t i = 0; i < aFontSets.size(); ++i)
{
mpListBoxFonts->InsertEntry(aFontSets[i].maName);
}
std::vector<ColorSet> aColorSets = initColorSets();
for (size_t i = 0; i < aColorSets.size(); ++i)
{
mpListBoxColors->InsertEntry(aColorSets[i].maName);
}
}
ThemePanel::~ThemePanel()
{
}
IMPL_LINK_NOARG(ThemePanel, ClickHdl)
{
SwDocShell* pDocSh = static_cast<SwDocShell*>(SfxObjectShell::Current());
if (pDocSh)
{
OUString sEntryFonts = mpListBoxFonts->GetSelectEntry();
OUString sEntryColors = mpListBoxColors->GetSelectEntry();
StyleSet aStyleSet = setupThemes();
applyTheme(pDocSh->GetStyleSheetPool(), sEntryFonts, sEntryColors, aStyleSet);
}
return 1;
}
void ThemePanel::NotifyItemUpdate(const sal_uInt16 /*nSId*/,
const SfxItemState /*eState*/,
const SfxPoolItem* /*pState*/,
const bool /*bIsEnabled*/)
{
}
}} // end of namespace ::sw::sidebar
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>// Copyright 2013 The Flutter 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 "flutter/shell/platform/linux/public/flutter_linux/fl_method_response.h"
#include <gmodule.h>
G_DEFINE_QUARK(fl_method_response_error_quark, fl_method_response_error)
struct _FlMethodSuccessResponse {
FlMethodResponse parent_instance;
FlValue* result;
};
struct _FlMethodErrorResponse {
FlMethodResponse parent_instance;
gchar* code;
gchar* message;
FlValue* details;
};
struct _FlMethodNotImplementedResponse {
FlMethodResponse parent_instance;
};
// Added here to stop the compiler from optimising this function away.
G_MODULE_EXPORT GType fl_method_response_get_type();
G_DEFINE_TYPE(FlMethodResponse, fl_method_response, G_TYPE_OBJECT)
G_DEFINE_TYPE(FlMethodSuccessResponse,
fl_method_success_response,
fl_method_response_get_type())
G_DEFINE_TYPE(FlMethodErrorResponse,
fl_method_error_response,
fl_method_response_get_type())
G_DEFINE_TYPE(FlMethodNotImplementedResponse,
fl_method_not_implemented_response,
fl_method_response_get_type())
static void fl_method_response_class_init(FlMethodResponseClass* klass) {}
static void fl_method_response_init(FlMethodResponse* self) {}
static void fl_method_success_response_dispose(GObject* object) {
FlMethodSuccessResponse* self = FL_METHOD_SUCCESS_RESPONSE(object);
g_clear_pointer(&self->result, fl_value_unref);
G_OBJECT_CLASS(fl_method_success_response_parent_class)->dispose(object);
}
static void fl_method_success_response_class_init(
FlMethodSuccessResponseClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_method_success_response_dispose;
}
static void fl_method_success_response_init(FlMethodSuccessResponse* self) {}
static void fl_method_error_response_dispose(GObject* object) {
FlMethodErrorResponse* self = FL_METHOD_ERROR_RESPONSE(object);
g_clear_pointer(&self->code, g_free);
g_clear_pointer(&self->message, g_free);
g_clear_pointer(&self->details, fl_value_unref);
G_OBJECT_CLASS(fl_method_error_response_parent_class)->dispose(object);
}
static void fl_method_error_response_class_init(
FlMethodErrorResponseClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_method_error_response_dispose;
}
static void fl_method_error_response_init(FlMethodErrorResponse* self) {}
static void fl_method_not_implemented_response_class_init(
FlMethodNotImplementedResponseClass* klass) {}
static void fl_method_not_implemented_response_init(
FlMethodNotImplementedResponse* self) {}
G_MODULE_EXPORT FlValue* fl_method_response_get_result(FlMethodResponse* self,
GError** error) {
if (FL_IS_METHOD_SUCCESS_RESPONSE(self)) {
return fl_method_success_response_get_result(
FL_METHOD_SUCCESS_RESPONSE(self));
}
if (FL_IS_METHOD_ERROR_RESPONSE(self)) {
const gchar* code =
fl_method_error_response_get_code(FL_METHOD_ERROR_RESPONSE(self));
const gchar* message =
fl_method_error_response_get_message(FL_METHOD_ERROR_RESPONSE(self));
FlValue* details =
fl_method_error_response_get_details(FL_METHOD_ERROR_RESPONSE(self));
g_autofree gchar* details_text = nullptr;
if (details != nullptr) {
details_text = fl_value_to_string(details);
}
g_autoptr(GString) error_message = g_string_new("");
g_string_append_printf(error_message, "Remote code returned error %s",
code);
if (message != nullptr) {
g_string_append_printf(error_message, ": %s", message);
}
if (details_text != nullptr) {
g_string_append_printf(error_message, " %s", details_text);
}
g_set_error_literal(error, FL_METHOD_RESPONSE_ERROR,
FL_METHOD_RESPONSE_ERROR_REMOTE_ERROR,
error_message->str);
return nullptr;
} else if (FL_IS_METHOD_NOT_IMPLEMENTED_RESPONSE(self)) {
g_set_error(error, FL_METHOD_RESPONSE_ERROR,
FL_METHOD_RESPONSE_ERROR_NOT_IMPLEMENTED,
"Requested method is not implemented");
return nullptr;
} else {
g_set_error(error, FL_METHOD_RESPONSE_ERROR,
FL_METHOD_RESPONSE_ERROR_FAILED, "Unknown response type");
return nullptr;
}
}
G_MODULE_EXPORT FlMethodSuccessResponse* fl_method_success_response_new(
FlValue* result) {
FlMethodSuccessResponse* self = FL_METHOD_SUCCESS_RESPONSE(
g_object_new(fl_method_success_response_get_type(), nullptr));
if (result != nullptr) {
self->result = fl_value_ref(result);
}
return self;
}
G_MODULE_EXPORT FlValue* fl_method_success_response_get_result(
FlMethodSuccessResponse* self) {
g_return_val_if_fail(FL_IS_METHOD_SUCCESS_RESPONSE(self), nullptr);
return self->result;
}
G_MODULE_EXPORT FlMethodErrorResponse* fl_method_error_response_new(
const gchar* code,
const gchar* message,
FlValue* details) {
g_return_val_if_fail(code != nullptr, nullptr);
FlMethodErrorResponse* self = FL_METHOD_ERROR_RESPONSE(
g_object_new(fl_method_error_response_get_type(), nullptr));
self->code = g_strdup(code);
self->message = g_strdup(message);
self->details = details != nullptr ? fl_value_ref(details) : nullptr;
return self;
}
G_MODULE_EXPORT const gchar* fl_method_error_response_get_code(
FlMethodErrorResponse* self) {
g_return_val_if_fail(FL_IS_METHOD_ERROR_RESPONSE(self), nullptr);
return self->code;
}
G_MODULE_EXPORT const gchar* fl_method_error_response_get_message(
FlMethodErrorResponse* self) {
g_return_val_if_fail(FL_IS_METHOD_ERROR_RESPONSE(self), nullptr);
return self->message;
}
G_MODULE_EXPORT FlValue* fl_method_error_response_get_details(
FlMethodErrorResponse* self) {
g_return_val_if_fail(FL_IS_METHOD_ERROR_RESPONSE(self), nullptr);
return self->details;
}
G_MODULE_EXPORT FlMethodNotImplementedResponse*
fl_method_not_implemented_response_new() {
return FL_METHOD_NOT_IMPLEMENTED_RESPONSE(
g_object_new(fl_method_not_implemented_response_get_type(), nullptr));
}
<commit_msg>Add workaround for missing fl_method_xxx_response_get_type() symbols (#21405)<commit_after>// Copyright 2013 The Flutter 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 "flutter/shell/platform/linux/public/flutter_linux/fl_method_response.h"
#include <gmodule.h>
G_DEFINE_QUARK(fl_method_response_error_quark, fl_method_response_error)
struct _FlMethodSuccessResponse {
FlMethodResponse parent_instance;
FlValue* result;
};
struct _FlMethodErrorResponse {
FlMethodResponse parent_instance;
gchar* code;
gchar* message;
FlValue* details;
};
struct _FlMethodNotImplementedResponse {
FlMethodResponse parent_instance;
};
// Added here to stop the compiler from optimising these functions away.
G_MODULE_EXPORT GType fl_method_response_get_type();
G_MODULE_EXPORT GType fl_method_success_response_get_type();
G_MODULE_EXPORT GType fl_method_error_response_get_type();
G_MODULE_EXPORT GType fl_method_not_implemented_response_get_type();
G_DEFINE_TYPE(FlMethodResponse, fl_method_response, G_TYPE_OBJECT)
G_DEFINE_TYPE(FlMethodSuccessResponse,
fl_method_success_response,
fl_method_response_get_type())
G_DEFINE_TYPE(FlMethodErrorResponse,
fl_method_error_response,
fl_method_response_get_type())
G_DEFINE_TYPE(FlMethodNotImplementedResponse,
fl_method_not_implemented_response,
fl_method_response_get_type())
static void fl_method_response_class_init(FlMethodResponseClass* klass) {}
static void fl_method_response_init(FlMethodResponse* self) {}
static void fl_method_success_response_dispose(GObject* object) {
FlMethodSuccessResponse* self = FL_METHOD_SUCCESS_RESPONSE(object);
g_clear_pointer(&self->result, fl_value_unref);
G_OBJECT_CLASS(fl_method_success_response_parent_class)->dispose(object);
}
static void fl_method_success_response_class_init(
FlMethodSuccessResponseClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_method_success_response_dispose;
}
static void fl_method_success_response_init(FlMethodSuccessResponse* self) {}
static void fl_method_error_response_dispose(GObject* object) {
FlMethodErrorResponse* self = FL_METHOD_ERROR_RESPONSE(object);
g_clear_pointer(&self->code, g_free);
g_clear_pointer(&self->message, g_free);
g_clear_pointer(&self->details, fl_value_unref);
G_OBJECT_CLASS(fl_method_error_response_parent_class)->dispose(object);
}
static void fl_method_error_response_class_init(
FlMethodErrorResponseClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_method_error_response_dispose;
}
static void fl_method_error_response_init(FlMethodErrorResponse* self) {}
static void fl_method_not_implemented_response_class_init(
FlMethodNotImplementedResponseClass* klass) {}
static void fl_method_not_implemented_response_init(
FlMethodNotImplementedResponse* self) {}
G_MODULE_EXPORT FlValue* fl_method_response_get_result(FlMethodResponse* self,
GError** error) {
if (FL_IS_METHOD_SUCCESS_RESPONSE(self)) {
return fl_method_success_response_get_result(
FL_METHOD_SUCCESS_RESPONSE(self));
}
if (FL_IS_METHOD_ERROR_RESPONSE(self)) {
const gchar* code =
fl_method_error_response_get_code(FL_METHOD_ERROR_RESPONSE(self));
const gchar* message =
fl_method_error_response_get_message(FL_METHOD_ERROR_RESPONSE(self));
FlValue* details =
fl_method_error_response_get_details(FL_METHOD_ERROR_RESPONSE(self));
g_autofree gchar* details_text = nullptr;
if (details != nullptr) {
details_text = fl_value_to_string(details);
}
g_autoptr(GString) error_message = g_string_new("");
g_string_append_printf(error_message, "Remote code returned error %s",
code);
if (message != nullptr) {
g_string_append_printf(error_message, ": %s", message);
}
if (details_text != nullptr) {
g_string_append_printf(error_message, " %s", details_text);
}
g_set_error_literal(error, FL_METHOD_RESPONSE_ERROR,
FL_METHOD_RESPONSE_ERROR_REMOTE_ERROR,
error_message->str);
return nullptr;
} else if (FL_IS_METHOD_NOT_IMPLEMENTED_RESPONSE(self)) {
g_set_error(error, FL_METHOD_RESPONSE_ERROR,
FL_METHOD_RESPONSE_ERROR_NOT_IMPLEMENTED,
"Requested method is not implemented");
return nullptr;
} else {
g_set_error(error, FL_METHOD_RESPONSE_ERROR,
FL_METHOD_RESPONSE_ERROR_FAILED, "Unknown response type");
return nullptr;
}
}
G_MODULE_EXPORT FlMethodSuccessResponse* fl_method_success_response_new(
FlValue* result) {
FlMethodSuccessResponse* self = FL_METHOD_SUCCESS_RESPONSE(
g_object_new(fl_method_success_response_get_type(), nullptr));
if (result != nullptr) {
self->result = fl_value_ref(result);
}
return self;
}
G_MODULE_EXPORT FlValue* fl_method_success_response_get_result(
FlMethodSuccessResponse* self) {
g_return_val_if_fail(FL_IS_METHOD_SUCCESS_RESPONSE(self), nullptr);
return self->result;
}
G_MODULE_EXPORT FlMethodErrorResponse* fl_method_error_response_new(
const gchar* code,
const gchar* message,
FlValue* details) {
g_return_val_if_fail(code != nullptr, nullptr);
FlMethodErrorResponse* self = FL_METHOD_ERROR_RESPONSE(
g_object_new(fl_method_error_response_get_type(), nullptr));
self->code = g_strdup(code);
self->message = g_strdup(message);
self->details = details != nullptr ? fl_value_ref(details) : nullptr;
return self;
}
G_MODULE_EXPORT const gchar* fl_method_error_response_get_code(
FlMethodErrorResponse* self) {
g_return_val_if_fail(FL_IS_METHOD_ERROR_RESPONSE(self), nullptr);
return self->code;
}
G_MODULE_EXPORT const gchar* fl_method_error_response_get_message(
FlMethodErrorResponse* self) {
g_return_val_if_fail(FL_IS_METHOD_ERROR_RESPONSE(self), nullptr);
return self->message;
}
G_MODULE_EXPORT FlValue* fl_method_error_response_get_details(
FlMethodErrorResponse* self) {
g_return_val_if_fail(FL_IS_METHOD_ERROR_RESPONSE(self), nullptr);
return self->details;
}
G_MODULE_EXPORT FlMethodNotImplementedResponse*
fl_method_not_implemented_response_new() {
return FL_METHOD_NOT_IMPLEMENTED_RESPONSE(
g_object_new(fl_method_not_implemented_response_get_type(), nullptr));
}
<|endoftext|>
|
<commit_before><commit_msg>stats: fix compute_pcr_time macro to take base & ext<commit_after><|endoftext|>
|
<commit_before>
#include "example_edison_gpio.hpp"
#include <cossb.hpp>
USE_COMPONENT_INTERFACE(example_edison_gpio)
example_edison_gpio::example_edison_gpio()
:cossb::interface::icomponent(COMPONENT(example_edison_gpio))
{
}
example_edison_gpio::~example_edison_gpio()
{
}
bool example_edison_gpio::setup()
{
return true;
}
bool example_edison_gpio::run()
{
return true;
}
bool example_edison_gpio::stop()
{
return true;
}
void example_edison_gpio::request(cossb::base::message* const msg)
{
switch(msg->get_frame()->type)
{
case cossb::base::msg_type::DATA:
if(!msg->get_frame()->topic.compare("service/print"))
printout(msg->show().c_str());
break;
case cossb::base::msg_type::SIGNAL: break;
case cossb::base::msg_type::REQUEST: break;
case cossb::base::msg_type::RESPONSE: break;
}
}
void example_edison_gpio::printout(const char* msg)
{
cossb_log->log(cossb::log::loglevel::INFO, fmt::format("[Message Received] : {}", msg));
}
<commit_msg>change show function to raw<commit_after>
#include "example_edison_gpio.hpp"
#include <cossb.hpp>
USE_COMPONENT_INTERFACE(example_edison_gpio)
example_edison_gpio::example_edison_gpio()
:cossb::interface::icomponent(COMPONENT(example_edison_gpio))
{
}
example_edison_gpio::~example_edison_gpio()
{
}
bool example_edison_gpio::setup()
{
return true;
}
bool example_edison_gpio::run()
{
return true;
}
bool example_edison_gpio::stop()
{
return true;
}
void example_edison_gpio::request(cossb::base::message* const msg)
{
switch(msg->get_frame()->type)
{
case cossb::base::msg_type::DATA:
if(!msg->get_frame()->topic.compare("service/print"))
printout(msg->raw().c_str());
break;
case cossb::base::msg_type::SIGNAL: break;
case cossb::base::msg_type::REQUEST: break;
case cossb::base::msg_type::RESPONSE: break;
}
}
void example_edison_gpio::printout(const char* msg)
{
cossb_log->log(cossb::log::loglevel::INFO, fmt::format("[Message Received] : {}", msg));
}
<|endoftext|>
|
<commit_before>#ifndef HASH_ID_HPP_
#define HASH_ID_HPP_
#include <chrono>
#include <cstring>
#include <functional>
#include <iomanip>
#include <iostream>
#include <random>
namespace sm {
struct Is64BitArch {
static constexpr bool value = sizeof(void*) == 8;
};
template<bool Is64BitArch>
struct HashPrimeAndBase {
static constexpr std::size_t kPrime = 16777619u;
static constexpr std::size_t kOffsetBasis = 2166136261u;
};
template<>
struct HashPrimeAndBase<true> {
static constexpr std::size_t kPrime = 1099511628211u;
static constexpr std::size_t kOffsetBasis = 14695981039346656037u;
};
/**
* 128 bit hash. Can be used as key to unordered containers.
*/
class HashId {
public:
/**
* Initializes to an invalid Hash
*/
inline HashId() {
setInvalid();
}
/**
* Copy constructor
*/
inline HashId(const HashId& other){
*this = other;
}
/**
* Generates a random Hash ID seeded from the nanosecond time of the first
* call of this function
*/
inline static HashId random() {
HashId generated;
generated.randomize();
return generated;
}
/**
* Returns hexadecimal string for debugging or serialization
*/
inline const std::string hexString() const {
char buffer[2*sizeof(val_) + 1]; // 1 for the \0 character
buffer[2*sizeof(val_)] = '\0';
for (size_t i = 0; i < sizeof(val_); ++i){
buffer[2 * i + 1] = kHexConversion[val_.c[i] & 0xf];
buffer[2 * i] = kHexConversion[val_.c[i] >> 4];
}
return std::string(buffer);
}
/**
* Deserialize from hexadecimal string. Serialization and Deserialization
* could be made more performant by using blobs.
*/
inline bool fromHexString(const std::string& hexString) {
// hexadecimal string takes 2 characters per byte
if (hexString.size() != 2*sizeof(val_)){
return false;
}
for (size_t i = 0; i < sizeof(val_); ++i){
val_.c[i] = static_cast<unsigned char>(
stoul(std::string(hexString, 2*i, 2), 0, 16));
}
return true;
}
/**
* Rehashes the 128 bit hash to a 32/64 bit hash that can be used in STL
* containers. This means that we will get collisions on the buckets, which
* is fine since we can disambiguate the actual hashes using operator==.
* So this does not increase the probability of ID collision.
*/
inline size_t hashToSizeT() const {
size_t hash = HashPrimeAndBase<Is64BitArch::value>::kOffsetBasis;
hash ^= val_.u64[0];
hash *= HashPrimeAndBase<Is64BitArch::value>::kPrime;
hash ^= val_.u64[1];
hash *= HashPrimeAndBase<Is64BitArch::value>::kPrime;
return hash;
}
/**
* Rehashes the 128 bit hash to a 32/64 bit hash that can be used in STL
* containers. This means that we will get collisions on the buckets, which
* is fine since we can disambiguate the actual hashes using operator==.
* So this does not increase the probability of ID collision.
* Version that skips prime multiplication for seeds that are already well
* distributed.
*/
inline size_t hashToSizeTFast() const {
size_t hash = HashPrimeAndBase<Is64BitArch::value>::kOffsetBasis;
hash ^= val_.u64[0];
hash ^= val_.u64[1];
return hash;
}
/**
* Randomizes to ID seeded from the nanosecond time of the first
* call of this function
*/
inline void randomize(){
static std::mt19937_64 rng(time64());
val_.u64[0] = rng();
val_.u64[1] = rng();
}
inline void operator =(const HashId& other) {
memcpy(&val_, &other.val_, sizeof(val_));
}
inline bool operator <(const HashId& other) const {
if (val_.u64[0] == other.val_.u64[0]){
return val_.u64[1] < other.val_.u64[1];
}
return val_.u64[0] < other.val_.u64[0];
}
inline bool operator >(const HashId& other) const {
if (val_.u64[0] == other.val_.u64[0]){
return val_.u64[1] > other.val_.u64[1];
}
return val_.u64[0] > other.val_.u64[0];
}
inline bool operator ==(const HashId& other) const {
return val_.u64[0] == other.val_.u64[0] && val_.u64[1] == other.val_.u64[1];
}
inline bool operator !=(const HashId& other) const{
return !(*this == other);
}
/**
* Invalidation mechanism
*/
inline void setInvalid() {
memset(&val_, 0, sizeof(val_));
}
inline bool isValid() const {
return val_.u64[0] != 0 || val_.u64[1] != 0;
}
private:
/**
* Time seed from nanoseconds. Covers 584 years if we assume no two agents
* initialize in the same nanosecond.
*/
inline static int64_t time64() {
std::chrono::high_resolution_clock::duration current =
std::chrono::high_resolution_clock::now().time_since_epoch();
using std::chrono::duration_cast;
using std::chrono::nanoseconds;
// count() specified to return at least 64 bits
return duration_cast<nanoseconds>(current).count();
}
/**
* Internal representation
*/
union HashVal {
unsigned char c[16];
uint_fast64_t u64[2];
};
HashVal val_;
static const char kHexConversion[];
};
} // namespace sm
namespace std{
inline ostream& operator<<(ostream& out, const sm::HashId& hash) {
out << hash.hexString();
return out;
}
template<>
struct hash<sm::HashId>{
typedef sm::HashId argument_type;
typedef std::size_t value_type;
value_type operator()(const argument_type& hash_id) const {
return hash_id.hashToSizeT();
}
};
} // namespace std
/// \brief Define the hash function for types derived from HashId
#define SM_DEFINE_HASHID_HASH(FullyQualifiedIdTypeName) \
namespace std { \
template<> \
struct hash<FullyQualifiedIdTypeName>{ \
typedef FullyQualifiedIdTypeName argument_type; \
typedef std::size_t value_type; \
value_type operator()(const argument_type& hash_id) const { \
return hash_id.hashToSizeT(); \
} \
}; \
} /* namespace std */ \
extern void DefineIDHash ## __FILE__ ## __LINE__(void)
#endif /* HASH_ID_HPP_ */
<commit_msg>Hash id hash for 32 bits and simplified.<commit_after>#ifndef HASH_ID_HPP_
#define HASH_ID_HPP_
#include <chrono>
#include <cstring>
#include <functional>
#include <iomanip>
#include <iostream>
#include <random>
namespace sm {
constexpr bool kIs64BitArch = (sizeof(void*) == 8);
struct HashPrimeAndBase {
static constexpr std::size_t kPrime =
kIs64BitArch ? 1099511628211ull : 16777619u;
static constexpr std::size_t kOffsetBasis =
kIs64BitArch ? 14695981039346656037ull : 2166136261u;
};
/**
* 128 bit hash. Can be used as key to unordered containers.
*/
class HashId {
public:
/**
* Initializes to an invalid Hash
*/
inline HashId() {
setInvalid();
}
/**
* Copy constructor
*/
inline HashId(const HashId& other){
*this = other;
}
/**
* Generates a random Hash ID seeded from the nanosecond time of the first
* call of this function
*/
inline static HashId random() {
HashId generated;
generated.randomize();
return generated;
}
/**
* Returns hexadecimal string for debugging or serialization
*/
inline const std::string hexString() const {
char buffer[2*sizeof(val_) + 1]; // 1 for the \0 character
buffer[2*sizeof(val_)] = '\0';
for (size_t i = 0; i < sizeof(val_); ++i){
buffer[2 * i + 1] = kHexConversion[val_.c[i] & 0xf];
buffer[2 * i] = kHexConversion[val_.c[i] >> 4];
}
return std::string(buffer);
}
/**
* Deserialize from hexadecimal string. Serialization and Deserialization
* could be made more performant by using blobs.
*/
inline bool fromHexString(const std::string& hexString) {
// hexadecimal string takes 2 characters per byte
if (hexString.size() != 2*sizeof(val_)){
return false;
}
for (size_t i = 0; i < sizeof(val_); ++i){
val_.c[i] = static_cast<unsigned char>(
stoul(std::string(hexString, 2*i, 2), 0, 16));
}
return true;
}
/**
* Rehashes the 128 bit hash to a 32/64 bit hash that can be used in STL
* containers. This means that we will get collisions on the buckets, which
* is fine since we can disambiguate the actual hashes using operator==.
* So this does not increase the probability of ID collision.
*/
inline size_t hashToSizeT() const {
size_t hash = HashPrimeAndBase::kOffsetBasis;
hash ^= val_.u64[0];
hash *= HashPrimeAndBase::kPrime;
hash ^= val_.u64[1];
hash *= HashPrimeAndBase::kPrime;
return hash;
}
/**
* Rehashes the 128 bit hash to a 32/64 bit hash that can be used in STL
* containers. This means that we will get collisions on the buckets, which
* is fine since we can disambiguate the actual hashes using operator==.
* So this does not increase the probability of ID collision.
* Version that skips prime multiplication for seeds that are already well
* distributed.
*/
inline size_t hashToSizeTFast() const {
size_t hash = HashPrimeAndBase::kOffsetBasis;
hash ^= val_.u64[0];
hash ^= val_.u64[1];
return hash;
}
/**
* Randomizes to ID seeded from the nanosecond time of the first
* call of this function
*/
inline void randomize(){
static std::mt19937_64 rng(time64());
val_.u64[0] = rng();
val_.u64[1] = rng();
}
inline void operator =(const HashId& other) {
memcpy(&val_, &other.val_, sizeof(val_));
}
inline bool operator <(const HashId& other) const {
if (val_.u64[0] == other.val_.u64[0]){
return val_.u64[1] < other.val_.u64[1];
}
return val_.u64[0] < other.val_.u64[0];
}
inline bool operator >(const HashId& other) const {
if (val_.u64[0] == other.val_.u64[0]){
return val_.u64[1] > other.val_.u64[1];
}
return val_.u64[0] > other.val_.u64[0];
}
inline bool operator ==(const HashId& other) const {
return val_.u64[0] == other.val_.u64[0] && val_.u64[1] == other.val_.u64[1];
}
inline bool operator !=(const HashId& other) const{
return !(*this == other);
}
/**
* Invalidation mechanism
*/
inline void setInvalid() {
memset(&val_, 0, sizeof(val_));
}
inline bool isValid() const {
return val_.u64[0] != 0 || val_.u64[1] != 0;
}
private:
/**
* Time seed from nanoseconds. Covers 584 years if we assume no two agents
* initialize in the same nanosecond.
*/
inline static int64_t time64() {
std::chrono::high_resolution_clock::duration current =
std::chrono::high_resolution_clock::now().time_since_epoch();
using std::chrono::duration_cast;
using std::chrono::nanoseconds;
// count() specified to return at least 64 bits
return duration_cast<nanoseconds>(current).count();
}
/**
* Internal representation
*/
union HashVal {
unsigned char c[16];
uint_fast64_t u64[2];
};
HashVal val_;
static const char kHexConversion[];
};
} // namespace sm
namespace std{
inline ostream& operator<<(ostream& out, const sm::HashId& hash) {
out << hash.hexString();
return out;
}
template<>
struct hash<sm::HashId>{
typedef sm::HashId argument_type;
typedef std::size_t value_type;
value_type operator()(const argument_type& hash_id) const {
return hash_id.hashToSizeT();
}
};
} // namespace std
/// \brief Define the hash function for types derived from HashId
#define SM_DEFINE_HASHID_HASH(FullyQualifiedIdTypeName) \
namespace std { \
template<> \
struct hash<FullyQualifiedIdTypeName>{ \
typedef FullyQualifiedIdTypeName argument_type; \
typedef std::size_t value_type; \
value_type operator()(const argument_type& hash_id) const { \
return hash_id.hashToSizeT(); \
} \
}; \
} /* namespace std */ \
extern void DefineIDHash ## __FILE__ ## __LINE__(void)
#endif /* HASH_ID_HPP_ */
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// This file contains the WebRTC suppressions for ThreadSanitizer.
// Please refer to
// http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for more info.
#if defined(THREAD_SANITIZER)
// Please make sure the code below declares a single string variable
// kTSanDefaultSuppressions contains TSan suppressions delimited by newlines.
// See http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for the instructions on writing suppressions.
char kTSanDefaultSuppressions[] =
// WebRTC specific suppressions.
// Split up suppressions covered previously by thread.cc and messagequeue.cc.
"race:rtc::MessageQueue::Quit\n"
"race:FileVideoCapturerTest::VideoCapturerListener::OnFrameCaptured\n"
"race:vp8cx_remove_encoder_threads\n"
"race:third_party/libvpx_new/source/libvpx/vp9/common/vp9_scan.h\n"
// Usage of trace callback and trace level is racy in libjingle_media_unittests.
// https://code.google.com/p/webrtc/issues/detail?id=3372
"race:webrtc::TraceImpl::WriteToFile\n"
"race:webrtc::VideoEngine::SetTraceFilter\n"
"race:webrtc::VoiceEngine::SetTraceFilter\n"
"race:webrtc::Trace::set_level_filter\n"
"race:webrtc::GetStaticInstance<webrtc::TraceImpl>\n"
// Audio processing
// https://code.google.com/p/webrtc/issues/detail?id=2521 for details.
"race:webrtc/modules/audio_processing/aec/aec_core.c\n"
"race:webrtc/modules/audio_processing/aec/aec_rdft.c\n"
// rtc_unittest
// https://code.google.com/p/webrtc/issues/detail?id=3911 for details.
"race:rtc::AsyncInvoker::OnMessage\n"
"race:rtc::FireAndForgetAsyncClosure<FunctorB>::Execute\n"
"race:rtc::MessageQueueManager::Clear\n"
"race:rtc::Thread::Clear\n"
// https://code.google.com/p/webrtc/issues/detail?id=3914
"race:rtc::AsyncInvoker::~AsyncInvoker\n"
// https://code.google.com/p/webrtc/issues/detail?id=2080
"race:webrtc/base/logging.cc\n"
"race:webrtc/base/sharedexclusivelock_unittest.cc\n"
"race:webrtc/base/signalthread_unittest.cc\n"
// https://code.google.com/p/webrtc/issues/detail?id=4456
"deadlock:rtc::MessageQueueManager::Clear\n"
"deadlock:rtc::MessageQueueManager::ClearInternal\n"
// libjingle_p2p_unittest
// https://code.google.com/p/webrtc/issues/detail?id=2079
"race:webrtc/base/testclient.cc\n"
"race:webrtc/base/virtualsocketserver.cc\n"
"race:talk/p2p/base/stunserver_unittest.cc\n"
// third_party/usrsctp
// TODO(jiayl): https://code.google.com/p/webrtc/issues/detail?id=3492
"race:user_sctp_timer_iterate\n"
// https://code.google.com/p/webrtc/issues/detail?id=5151
"race:sctp_close\n"
// Potential deadlocks detected after roll in r6516.
// https://code.google.com/p/webrtc/issues/detail?id=3509
"deadlock:webrtc::RTCPReceiver::SetSsrcs\n"
"deadlock:webrtc::test::UdpSocketManagerPosixImpl::RemoveSocket\n"
"deadlock:webrtc::vcm::VideoReceiver::RegisterPacketRequestCallback\n"
"deadlock:webrtc::ViEEncoder::OnLocalSsrcChanged\n"
// TODO(pbos): Trace events are racy due to lack of proper POD atomics.
// https://code.google.com/p/webrtc/issues/detail?id=2497
"race:*trace_event_unique_catstatic*\n"
// https://code.google.com/p/webrtc/issues/detail?id=4719
"race:webrtc::voe::TransmitMixer::PrepareDemux\n"
"race:webrtc::voe::TransmitMixer::EnableStereoChannelSwapping\n"
// Race between InitCpuFlags and TestCpuFlag in libyuv.
// https://code.google.com/p/libyuv/issues/detail?id=508
"race:InitCpuFlags\n"
// End of suppressions.
; // Please keep this semicolon.
#endif // THREAD_SANITIZER
<commit_msg>Suppress data races in AudioDeviceLinuxPulse::Init.<commit_after>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// This file contains the WebRTC suppressions for ThreadSanitizer.
// Please refer to
// http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for more info.
#if defined(THREAD_SANITIZER)
// Please make sure the code below declares a single string variable
// kTSanDefaultSuppressions contains TSan suppressions delimited by newlines.
// See http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for the instructions on writing suppressions.
char kTSanDefaultSuppressions[] =
// WebRTC specific suppressions.
// Split up suppressions covered previously by thread.cc and messagequeue.cc.
"race:rtc::MessageQueue::Quit\n"
"race:FileVideoCapturerTest::VideoCapturerListener::OnFrameCaptured\n"
"race:vp8cx_remove_encoder_threads\n"
"race:third_party/libvpx_new/source/libvpx/vp9/common/vp9_scan.h\n"
// Usage of trace callback and trace level is racy in libjingle_media_unittests.
// https://code.google.com/p/webrtc/issues/detail?id=3372
"race:webrtc::TraceImpl::WriteToFile\n"
"race:webrtc::VideoEngine::SetTraceFilter\n"
"race:webrtc::VoiceEngine::SetTraceFilter\n"
"race:webrtc::Trace::set_level_filter\n"
"race:webrtc::GetStaticInstance<webrtc::TraceImpl>\n"
// Audio processing
// https://code.google.com/p/webrtc/issues/detail?id=2521 for details.
"race:webrtc/modules/audio_processing/aec/aec_core.c\n"
"race:webrtc/modules/audio_processing/aec/aec_rdft.c\n"
// Race in pulse initialization.
// https://code.google.com/p/webrtc/issues/detail?id=5152
"race:webrtc::AudioDeviceLinuxPulse::Init\n"
// rtc_unittest
// https://code.google.com/p/webrtc/issues/detail?id=3911 for details.
"race:rtc::AsyncInvoker::OnMessage\n"
"race:rtc::FireAndForgetAsyncClosure<FunctorB>::Execute\n"
"race:rtc::MessageQueueManager::Clear\n"
"race:rtc::Thread::Clear\n"
// https://code.google.com/p/webrtc/issues/detail?id=3914
"race:rtc::AsyncInvoker::~AsyncInvoker\n"
// https://code.google.com/p/webrtc/issues/detail?id=2080
"race:webrtc/base/logging.cc\n"
"race:webrtc/base/sharedexclusivelock_unittest.cc\n"
"race:webrtc/base/signalthread_unittest.cc\n"
// https://code.google.com/p/webrtc/issues/detail?id=4456
"deadlock:rtc::MessageQueueManager::Clear\n"
"deadlock:rtc::MessageQueueManager::ClearInternal\n"
// libjingle_p2p_unittest
// https://code.google.com/p/webrtc/issues/detail?id=2079
"race:webrtc/base/testclient.cc\n"
"race:webrtc/base/virtualsocketserver.cc\n"
"race:talk/p2p/base/stunserver_unittest.cc\n"
// third_party/usrsctp
// TODO(jiayl): https://code.google.com/p/webrtc/issues/detail?id=3492
"race:user_sctp_timer_iterate\n"
// https://code.google.com/p/webrtc/issues/detail?id=5151
"race:sctp_close\n"
// Potential deadlocks detected after roll in r6516.
// https://code.google.com/p/webrtc/issues/detail?id=3509
"deadlock:webrtc::RTCPReceiver::SetSsrcs\n"
"deadlock:webrtc::test::UdpSocketManagerPosixImpl::RemoveSocket\n"
"deadlock:webrtc::vcm::VideoReceiver::RegisterPacketRequestCallback\n"
"deadlock:webrtc::ViEEncoder::OnLocalSsrcChanged\n"
// TODO(pbos): Trace events are racy due to lack of proper POD atomics.
// https://code.google.com/p/webrtc/issues/detail?id=2497
"race:*trace_event_unique_catstatic*\n"
// https://code.google.com/p/webrtc/issues/detail?id=4719
"race:webrtc::voe::TransmitMixer::PrepareDemux\n"
"race:webrtc::voe::TransmitMixer::EnableStereoChannelSwapping\n"
// Race between InitCpuFlags and TestCpuFlag in libyuv.
// https://code.google.com/p/libyuv/issues/detail?id=508
"race:InitCpuFlags\n"
// End of suppressions.
; // Please keep this semicolon.
#endif // THREAD_SANITIZER
<|endoftext|>
|
<commit_before>/**
MiracleGrue - Model Generator for toolpathing. <http://www.grue.makerbot.com>
Copyright (C) 2011 Far McKon <Far@makerbot.com>, Hugo Boyer (hugo@makerbot.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
*/
#include <iostream>
#include <string>
#include <stdlib.h>
#include "mgl/abstractable.h"
#include "mgl/configuration.h"
#include "mgl/miracle.h"
#include "libthing/Vector2.h"
#include "optionparser.h"
#include "mgl/log.h"
using namespace std;
using namespace mgl;
/// Extends options::Arg to specifiy limitations on arguments
struct Arg: public option::Arg
{
static void printError(const char* msg1, const option::Option& opt, const char* msg2)
{
fprintf(stderr, "%s", msg1);
fwrite(opt.name, opt.namelen, 1, stderr);
fprintf(stderr, "%s", msg2);
}
static option::ArgStatus Unknown(const option::Option& option, bool msg)
{
if (msg) printError("Unknown option '", option, "'\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus Required(const option::Option& option, bool msg)
{
if (option.arg != 0)
return option::ARG_OK;
if (msg) printError("Option '", option, "' requires an argument\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus NonEmpty(const option::Option& option, bool msg)
{
if (option.arg != 0 && option.arg[0] != 0)
return option::ARG_OK;
if (msg) printError("Option '", option, "' requires a non-empty argument\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus Numeric(const option::Option& option, bool msg)
{
char* endptr = 0;
if (option.arg != 0 && strtod(option.arg, &endptr)){};
if (endptr != option.arg && *endptr == 0)
return option::ARG_OK;
if (msg) printError("Option '", option, "' requires a numeric argument\n");
return option::ARG_ILLEGAL;
}
};
// all ID's of the options we expect
enum optionIndex {UNKNOWN, HELP, CONFIG, FIRST_Z,LAYER_H,LAYER_W, FILL_ANGLE, FILL_DENSITY,
N_SHELLS, BOTTOM_SLICE_IDX, TOP_SLICE_IDX, DEBUG_ME, START_GCODE,
END_GCODE, OUT_FILENAME};
// options descriptor table
const option::Descriptor usageDescriptor[] =
{
{UNKNOWN, 0, "", "",Arg::None, "miracle-grue [OPTIONS] FILE.STL \n\n"
"Options:" },
{HELP, 0,"", "help",Arg::None, " --help \tPrint usage and exit." },
{CONFIG, 1,"c", "config", Arg::NonEmpty, "-c \tconfig data in a config.json file."
"(default is local miracle.config)" },
{FIRST_Z, 2,"f", "firstLayerZ", Arg::Numeric,
"-f \tfirst layer height (mm)" },
{LAYER_H, 3,"h", "layerH", Arg::Numeric,
" -h \tgeneral layer height(mm)" },
{LAYER_W, 4,"w", "layerW", Arg::Numeric,
" -w \tlayer width(mm)" },
{ FILL_ANGLE, 5, "a","angle", Arg::Numeric,
" -a \tinfill grid inter slice angle(radians)" },
{ FILL_DENSITY, 6, "p", "density", Arg::Numeric,
" -p \tapprox infill density(percent), aka rho aka p" },
{ N_SHELLS, 7, "n", "nShells", Arg::Numeric,
" -n \tnumber of shells per layer" },
{ BOTTOM_SLICE_IDX, 8, "b", "bottomIdx", Arg::Numeric,
" -b \tbottom slice index" },
{ TOP_SLICE_IDX, 9, "t", "topIdx", Arg::Numeric,
" -t \ttop slice index" },
{ DEBUG_ME, 10, "d", "debug", Arg::Numeric,
" -d \tdebug level, 0 to 99. 60 is 'info'" },
{ START_GCODE, 11, "s", "header", Arg::NonEmpty,
" -s \tstart gcode file" },
{ END_GCODE, 12, "e", "footer", Arg::NonEmpty,
" -e \tend gcode file" },
{ OUT_FILENAME, 13, "o", "outFilename", Arg::NonEmpty,
" -o \twrite gcode to specific filename (defaults to <model>.gcode" },
{0,0,0,0,0,0},
};
void usage() {
Log::severe() <<" test Log::severe " <<endl;
Log::info()<<" test Log::info " <<endl;
Log::fine() <<" test Log::fine " <<endl;
Log::finer() <<" test Log::finer " <<endl;
Log::finest() <<" test Log::finest " <<endl;
cout << endl;
cout << "It is pitch black. You are likely to be eaten by a grue." << endl;
cout << endl;
cout << "This program translates a 3d model file in STL format to GCODE toolpath for a " << endl;
cout << "3D printer." << " Another fine MakerBot Industries product!"<< endl;
cout << endl;
option::printUsage(std::cout, usageDescriptor);
cout << endl;
}
int newParseArgs( Configuration &config,
int argc, char *argv[],
string &modelFile,
int &firstSliceIdx,
int &lastSliceIdx) {
string configFilename = "";
argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present
option::Stats stats(usageDescriptor, argc, argv);
option::Option* options = new option::Option[stats.options_max];
option::Option* buffer = new option::Option[stats.buffer_max];
option::Parser parse(usageDescriptor, argc, argv, options, buffer);
if (parse.error())
return -20;
///read config file and/or help option first
for (int i = 0; i < parse.optionsCount(); ++i)
{
option::Option& opt = buffer[i];
if(opt.index() == CONFIG )
configFilename = string(opt.arg);
if(opt.index() == HELP ) {
usage();
exit(0);
}
}
// fallback to default config
if (configFilename.compare(string("")) == 0)
configFilename = "miracle.config";
config.readFromFile(configFilename);
for (int i = 0; i < parse.optionsCount(); ++i)
{
option::Option& opt = buffer[i];
fprintf(stdout, "Argument #%d name %s is #%s\n", i, opt.desc->longopt, opt.arg );
switch (opt.index())
{
case LAYER_H:
case LAYER_W:
case FILL_ANGLE:
case FILL_DENSITY:
case N_SHELLS:
case BOTTOM_SLICE_IDX:
case TOP_SLICE_IDX:
case FIRST_Z:
config["slicer"][opt.desc->longopt] = atof(opt.arg);
break;
case DEBUG_ME:
config["meta"][opt.desc->longopt] = atof(opt.arg);
break;
case START_GCODE:
case END_GCODE:
case OUT_FILENAME:
config["gcoder"][opt.desc->longopt] = opt.arg;
break;
case CONFIG:
// handled above before other config values
break;
case HELP:
// not possible, because handled further above and exits the program
default:
break;
}
}
/// handle parameters (not options!)
if ( parse.nonOptionsCount() == 0) {
usage();
}
else if ( parse.nonOptionsCount() != 1) {
Log::severe() << "too many parameters" << endl;
for (int i = 0; i < parse.nonOptionsCount(); ++i)
Log::severe() << "Parameter #" << i << ": " << parse.nonOption(i) << "\n";
exit(-10);
}
else {
//handle the unnamed parameter separately
modelFile = parse.nonOption(0);
Log::finer() << "filename " << modelFile << endl;
ifstream testmodel(modelFile.c_str(), ifstream::in);
if (testmodel.fail()) {
usage();
throw mgl::Exception(("Invalid model file [" + modelFile + "]").c_str());
exit(-10);
}
}
firstSliceIdx = -1;
lastSliceIdx = -1;
// [programName] and [versionStr] are always hard-code overwritten
config["programName"] = GRUE_PROGRAM_NAME;
config["versionStr"] = GRUE_VERSION;
config["firmware"] = "unknown";
/// convert debug data to a module/level specific setting
g_debugVerbosity = log_verbosity_unset;
if ( config["meta"].isMember("debug") ) {
try {
uint32_t debugLvl = config["meta"]["debug"].asUInt();
if ( debugLvl < 90 ) g_debugVerbosity = log_finest;
else if ( debugLvl < 80 ) g_debugVerbosity = log_finer;
else if ( debugLvl < 70 ) g_debugVerbosity = log_fine;
else if ( debugLvl < 60 ) g_debugVerbosity = log_info;
else if ( debugLvl < 10 ) g_debugVerbosity = log_severe;
else g_debugVerbosity = log_verbosity_unset;
}
catch (...){
cout << "fail sauce on debug level" << endl;
// passed -d sans option. Assume default dbg level
g_debugVerbosity = log_default_level;
}
}
return 0;
}
int main(int argc, char *argv[], char *[]) // envp
{
string modelFile;
Configuration config;
try
{
int firstSliceIdx, lastSliceIdx;
int ret = newParseArgs(config, argc, argv, modelFile, firstSliceIdx, lastSliceIdx);
if(ret != 0){
usage();
exit(ret);
}
// cout << config.asJson() << endl;
Log::finer() << "Tube spacing: " << config["slicer"]["tubeSpacing"] << endl;
MyComputer computer;
Log::fine() << endl << endl;
Log::fine() << "behold!" << endl;
Log::fine() << "Materialization of \"" << modelFile << "\" has begun at " << computer.clock.now() << endl;
std::string scadFile = "."; // outDir
scadFile += computer.fileSystem.getPathSeparatorCharacter();
scadFile = computer.fileSystem.ChangeExtension(computer.fileSystem.ExtractFilename(modelFile.c_str()).c_str(), ".scad" );
std::string gcodeFile = config["gcoder"]["outFilename"].asString();
if (gcodeFile.empty()) {
gcodeFile = ".";
gcodeFile += computer.fileSystem.getPathSeparatorCharacter();
gcodeFile = computer.fileSystem.ChangeExtension(computer.fileSystem.ExtractFilename(modelFile.c_str()).c_str(), ".gcode" );
}
Log::fine() << endl << endl;
Log::fine() << modelFile << " to \"" << gcodeFile << "\" and \"" << scadFile << "\"" << endl;
GCoderConfig gcoderCfg;
loadGCoderConfigFromFile(config, gcoderCfg);
SlicerConfig slicerCfg;
loadSlicerConfigFromFile(config, slicerCfg);
const char* scad = NULL;
if (scadFile.size() > 0 )
scad = scadFile.c_str();
Tomograph tomograph;
Regions regions;
std::vector<mgl::SliceData> slices;
ProgressLog log;
miracleGrue(gcoderCfg, slicerCfg, modelFile.c_str(),
scad,
gcodeFile.c_str(),
firstSliceIdx,
lastSliceIdx,
tomograph,
regions,
slices,
&log);
}
catch(mgl::Exception &mixup)
{
Log::severe() << "ERROR: "<< mixup.error << endl;
return -1;
}
}
<commit_msg>Add stdint.h so that uint types work<commit_after>/**
MiracleGrue - Model Generator for toolpathing. <http://www.grue.makerbot.com>
Copyright (C) 2011 Far McKon <Far@makerbot.com>, Hugo Boyer (hugo@makerbot.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
*/
#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdint.h>
#include "mgl/abstractable.h"
#include "mgl/configuration.h"
#include "mgl/miracle.h"
#include "libthing/Vector2.h"
#include "optionparser.h"
#include "mgl/log.h"
using namespace std;
using namespace mgl;
/// Extends options::Arg to specifiy limitations on arguments
struct Arg: public option::Arg
{
static void printError(const char* msg1, const option::Option& opt, const char* msg2)
{
fprintf(stderr, "%s", msg1);
fwrite(opt.name, opt.namelen, 1, stderr);
fprintf(stderr, "%s", msg2);
}
static option::ArgStatus Unknown(const option::Option& option, bool msg)
{
if (msg) printError("Unknown option '", option, "'\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus Required(const option::Option& option, bool msg)
{
if (option.arg != 0)
return option::ARG_OK;
if (msg) printError("Option '", option, "' requires an argument\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus NonEmpty(const option::Option& option, bool msg)
{
if (option.arg != 0 && option.arg[0] != 0)
return option::ARG_OK;
if (msg) printError("Option '", option, "' requires a non-empty argument\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus Numeric(const option::Option& option, bool msg)
{
char* endptr = 0;
if (option.arg != 0 && strtod(option.arg, &endptr)){};
if (endptr != option.arg && *endptr == 0)
return option::ARG_OK;
if (msg) printError("Option '", option, "' requires a numeric argument\n");
return option::ARG_ILLEGAL;
}
};
// all ID's of the options we expect
enum optionIndex {UNKNOWN, HELP, CONFIG, FIRST_Z,LAYER_H,LAYER_W, FILL_ANGLE, FILL_DENSITY,
N_SHELLS, BOTTOM_SLICE_IDX, TOP_SLICE_IDX, DEBUG_ME, START_GCODE,
END_GCODE, OUT_FILENAME};
// options descriptor table
const option::Descriptor usageDescriptor[] =
{
{UNKNOWN, 0, "", "",Arg::None, "miracle-grue [OPTIONS] FILE.STL \n\n"
"Options:" },
{HELP, 0,"", "help",Arg::None, " --help \tPrint usage and exit." },
{CONFIG, 1,"c", "config", Arg::NonEmpty, "-c \tconfig data in a config.json file."
"(default is local miracle.config)" },
{FIRST_Z, 2,"f", "firstLayerZ", Arg::Numeric,
"-f \tfirst layer height (mm)" },
{LAYER_H, 3,"h", "layerH", Arg::Numeric,
" -h \tgeneral layer height(mm)" },
{LAYER_W, 4,"w", "layerW", Arg::Numeric,
" -w \tlayer width(mm)" },
{ FILL_ANGLE, 5, "a","angle", Arg::Numeric,
" -a \tinfill grid inter slice angle(radians)" },
{ FILL_DENSITY, 6, "p", "density", Arg::Numeric,
" -p \tapprox infill density(percent), aka rho aka p" },
{ N_SHELLS, 7, "n", "nShells", Arg::Numeric,
" -n \tnumber of shells per layer" },
{ BOTTOM_SLICE_IDX, 8, "b", "bottomIdx", Arg::Numeric,
" -b \tbottom slice index" },
{ TOP_SLICE_IDX, 9, "t", "topIdx", Arg::Numeric,
" -t \ttop slice index" },
{ DEBUG_ME, 10, "d", "debug", Arg::Numeric,
" -d \tdebug level, 0 to 99. 60 is 'info'" },
{ START_GCODE, 11, "s", "header", Arg::NonEmpty,
" -s \tstart gcode file" },
{ END_GCODE, 12, "e", "footer", Arg::NonEmpty,
" -e \tend gcode file" },
{ OUT_FILENAME, 13, "o", "outFilename", Arg::NonEmpty,
" -o \twrite gcode to specific filename (defaults to <model>.gcode" },
{0,0,0,0,0,0},
};
void usage() {
Log::severe() <<" test Log::severe " <<endl;
Log::info()<<" test Log::info " <<endl;
Log::fine() <<" test Log::fine " <<endl;
Log::finer() <<" test Log::finer " <<endl;
Log::finest() <<" test Log::finest " <<endl;
cout << endl;
cout << "It is pitch black. You are likely to be eaten by a grue." << endl;
cout << endl;
cout << "This program translates a 3d model file in STL format to GCODE toolpath for a " << endl;
cout << "3D printer." << " Another fine MakerBot Industries product!"<< endl;
cout << endl;
option::printUsage(std::cout, usageDescriptor);
cout << endl;
}
int newParseArgs( Configuration &config,
int argc, char *argv[],
string &modelFile,
int &firstSliceIdx,
int &lastSliceIdx) {
string configFilename = "";
argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present
option::Stats stats(usageDescriptor, argc, argv);
option::Option* options = new option::Option[stats.options_max];
option::Option* buffer = new option::Option[stats.buffer_max];
option::Parser parse(usageDescriptor, argc, argv, options, buffer);
if (parse.error())
return -20;
///read config file and/or help option first
for (int i = 0; i < parse.optionsCount(); ++i)
{
option::Option& opt = buffer[i];
if(opt.index() == CONFIG )
configFilename = string(opt.arg);
if(opt.index() == HELP ) {
usage();
exit(0);
}
}
// fallback to default config
if (configFilename.compare(string("")) == 0)
configFilename = "miracle.config";
config.readFromFile(configFilename);
for (int i = 0; i < parse.optionsCount(); ++i)
{
option::Option& opt = buffer[i];
fprintf(stdout, "Argument #%d name %s is #%s\n", i, opt.desc->longopt, opt.arg );
switch (opt.index())
{
case LAYER_H:
case LAYER_W:
case FILL_ANGLE:
case FILL_DENSITY:
case N_SHELLS:
case BOTTOM_SLICE_IDX:
case TOP_SLICE_IDX:
case FIRST_Z:
config["slicer"][opt.desc->longopt] = atof(opt.arg);
break;
case DEBUG_ME:
config["meta"][opt.desc->longopt] = atof(opt.arg);
break;
case START_GCODE:
case END_GCODE:
case OUT_FILENAME:
config["gcoder"][opt.desc->longopt] = opt.arg;
break;
case CONFIG:
// handled above before other config values
break;
case HELP:
// not possible, because handled further above and exits the program
default:
break;
}
}
/// handle parameters (not options!)
if ( parse.nonOptionsCount() == 0) {
usage();
}
else if ( parse.nonOptionsCount() != 1) {
Log::severe() << "too many parameters" << endl;
for (int i = 0; i < parse.nonOptionsCount(); ++i)
Log::severe() << "Parameter #" << i << ": " << parse.nonOption(i) << "\n";
exit(-10);
}
else {
//handle the unnamed parameter separately
modelFile = parse.nonOption(0);
Log::finer() << "filename " << modelFile << endl;
ifstream testmodel(modelFile.c_str(), ifstream::in);
if (testmodel.fail()) {
usage();
throw mgl::Exception(("Invalid model file [" + modelFile + "]").c_str());
exit(-10);
}
}
firstSliceIdx = -1;
lastSliceIdx = -1;
// [programName] and [versionStr] are always hard-code overwritten
config["programName"] = GRUE_PROGRAM_NAME;
config["versionStr"] = GRUE_VERSION;
config["firmware"] = "unknown";
/// convert debug data to a module/level specific setting
g_debugVerbosity = log_verbosity_unset;
if ( config["meta"].isMember("debug") ) {
try {
uint32_t debugLvl = config["meta"]["debug"].asUInt();
if ( debugLvl < 90 ) g_debugVerbosity = log_finest;
else if ( debugLvl < 80 ) g_debugVerbosity = log_finer;
else if ( debugLvl < 70 ) g_debugVerbosity = log_fine;
else if ( debugLvl < 60 ) g_debugVerbosity = log_info;
else if ( debugLvl < 10 ) g_debugVerbosity = log_severe;
else g_debugVerbosity = log_verbosity_unset;
}
catch (...){
cout << "fail sauce on debug level" << endl;
// passed -d sans option. Assume default dbg level
g_debugVerbosity = log_default_level;
}
}
return 0;
}
int main(int argc, char *argv[], char *[]) // envp
{
string modelFile;
Configuration config;
try
{
int firstSliceIdx, lastSliceIdx;
int ret = newParseArgs(config, argc, argv, modelFile, firstSliceIdx, lastSliceIdx);
if(ret != 0){
usage();
exit(ret);
}
// cout << config.asJson() << endl;
Log::finer() << "Tube spacing: " << config["slicer"]["tubeSpacing"] << endl;
MyComputer computer;
Log::fine() << endl << endl;
Log::fine() << "behold!" << endl;
Log::fine() << "Materialization of \"" << modelFile << "\" has begun at " << computer.clock.now() << endl;
std::string scadFile = "."; // outDir
scadFile += computer.fileSystem.getPathSeparatorCharacter();
scadFile = computer.fileSystem.ChangeExtension(computer.fileSystem.ExtractFilename(modelFile.c_str()).c_str(), ".scad" );
std::string gcodeFile = config["gcoder"]["outFilename"].asString();
if (gcodeFile.empty()) {
gcodeFile = ".";
gcodeFile += computer.fileSystem.getPathSeparatorCharacter();
gcodeFile = computer.fileSystem.ChangeExtension(computer.fileSystem.ExtractFilename(modelFile.c_str()).c_str(), ".gcode" );
}
Log::fine() << endl << endl;
Log::fine() << modelFile << " to \"" << gcodeFile << "\" and \"" << scadFile << "\"" << endl;
GCoderConfig gcoderCfg;
loadGCoderConfigFromFile(config, gcoderCfg);
SlicerConfig slicerCfg;
loadSlicerConfigFromFile(config, slicerCfg);
const char* scad = NULL;
if (scadFile.size() > 0 )
scad = scadFile.c_str();
Tomograph tomograph;
Regions regions;
std::vector<mgl::SliceData> slices;
ProgressLog log;
miracleGrue(gcoderCfg, slicerCfg, modelFile.c_str(),
scad,
gcodeFile.c_str(),
firstSliceIdx,
lastSliceIdx,
tomograph,
regions,
slices,
&log);
}
catch(mgl::Exception &mixup)
{
Log::severe() << "ERROR: "<< mixup.error << endl;
return -1;
}
}
<|endoftext|>
|
<commit_before>//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "LightningTree.h"
#include "../utils/linearAlg2D.h"
using namespace cura;
coord_t LightningTreeNode::getWeightedDistance(const Point& unsupported_loc, const coord_t& supporting_radius) const
{
size_t valence = (!is_root) + children.size();
coord_t boost = (0 < valence && valence < 4) ? 4 * supporting_radius : 0;
return vSize(getLocation() - unsupported_loc) - boost;
}
bool LightningTreeNode::hasOffspring(const std::shared_ptr<LightningTreeNode>& to_be_checked) const
{
if (to_be_checked == shared_from_this()) return true;
for (auto child_ptr : children)
{
if (child_ptr->hasOffspring(to_be_checked)) return true;
}
return false;
}
const Point& LightningTreeNode::getLocation() const
{
return p;
}
void LightningTreeNode::setLocation(const Point& loc)
{
p = loc;
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::addChild(const Point& child_loc)
{
assert(p != child_loc);
children.push_back(LightningTreeNode::create(child_loc));
return children.back();
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::addChild(std::shared_ptr<LightningTreeNode>& new_child)
{
assert(new_child != shared_from_this());
// assert(p != new_child->p);
if (p == new_child->p)
std::cerr << "wtf\n";
children.push_back(new_child);
new_child->is_root = false;
return new_child;
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::findClosestNode(const Point& x, const coord_t& supporting_radius)
{
coord_t closest_distance = getWeightedDistance(x, supporting_radius);
std::shared_ptr<LightningTreeNode> closest_node = shared_from_this();
findClosestNodeHelper(x, supporting_radius, closest_distance, closest_node);
return closest_node;
}
void LightningTreeNode::propagateToNextLayer
(
std::vector<std::shared_ptr<LightningTreeNode>>& next_trees,
const Polygons& next_outlines,
const coord_t& prune_distance,
const coord_t& smooth_magnitude
) const
{
auto tree_below = deepCopy();
// TODO: What is the correct order of the following operations?
// (NOTE: in case realign turns out _not_ to be last, would need to rewrite a few things, see the 'rerooted_parts' parameter of that function).
tree_below->prune(prune_distance);
tree_below->straighten(smooth_magnitude);
if (tree_below->realign(next_outlines, next_trees))
{
next_trees.push_back(tree_below);
}
}
// NOTE: Depth-first, as currently implemented.
// Skips the root (because that has no root itself), but all initial nodes will have the root point anyway.
void LightningTreeNode::visitBranches(const branch_visitor_func_t& visitor) const
{
for (const auto& node : children)
{
visitor(p, node->p);
node->visitBranches(visitor);
}
}
// NOTE: Depth-first, as currently implemented.
void LightningTreeNode::visitNodes(const node_visitor_func_t& visitor)
{
visitor(shared_from_this());
for (const auto& node : children)
{
node->visitNodes(visitor);
}
}
// Node:
LightningTreeNode::LightningTreeNode(const Point& p) : is_root(false), p(p) {}
// Root (and Trunk):
LightningTreeNode::LightningTreeNode(const Point& a, const Point& b) : LightningTreeNode(a)
{
children.push_back(LightningTreeNode::create(b));
is_root = true;
}
void LightningTreeNode::findClosestNodeHelper(const Point& x, const coord_t supporting_radius, coord_t& closest_distance, std::shared_ptr<LightningTreeNode>& closest_node)
{
for (const auto& node : children)
{
node->findClosestNodeHelper(x, supporting_radius, closest_distance, closest_node);
const coord_t distance = node->getWeightedDistance(x, supporting_radius);
if (distance < closest_distance)
{
closest_node = node;
closest_distance = distance;
}
}
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::deepCopy() const
{
std::shared_ptr<LightningTreeNode> local_root = LightningTreeNode::create(p);
local_root->is_root = is_root;
local_root->children.reserve(children.size());
for (const auto& node : children)
{
local_root->children.push_back(node->deepCopy());
}
return local_root;
}
bool LightningTreeNode::realign(const Polygons& outlines, std::vector<std::shared_ptr<LightningTreeNode>>& rerooted_parts, const bool& connected_to_parent)
{
// TODO: Hole(s) in the _middle_ of a line-segement, not unlikely since reconnect.
// TODO: Reconnect if not on outline -> plan is: yes, but not here anymore!
if (outlines.empty())
{
return false;
}
if (outlines.inside(p, true))
{
// Only keep children that have an unbroken connection to here, realign will put the rest in rerooted parts due to recursion:
const std::function<bool(const std::shared_ptr<LightningTreeNode>& child)> remove_unconnected_func
(
[&outlines, &rerooted_parts](const std::shared_ptr<LightningTreeNode>& child)
{
constexpr bool argument_with_connected = true;
return !child->realign(outlines, rerooted_parts, argument_with_connected);
}
);
children.erase(std::remove_if(children.begin(), children.end(), remove_unconnected_func), children.end());
return true;
}
// 'Lift' any decendants out of this tree:
for (auto& child : children)
{
constexpr bool argument_with_disconnect = false;
if (child->realign(outlines, rerooted_parts, argument_with_disconnect))
{
rerooted_parts.push_back(child);
}
}
children.clear();
if (connected_to_parent)
{
// This will now be a (new_ leaf:
p = PolygonUtils::findClosest(p, outlines).p();
return true;
}
return false;
}
void LightningTreeNode::straighten(const coord_t& magnitude)
{
straighten(magnitude, p, 0);
}
LightningTreeNode::RectilinearJunction LightningTreeNode::straighten(const coord_t& magnitude, Point junction_above, coord_t accumulated_dist)
{
const coord_t junction_magnitude = magnitude * 3 / 4;
if (children.size() == 1)
{
auto child_p = children.front();
coord_t child_dist = vSize(p - child_p->p);
RectilinearJunction junction_below = child_p->straighten(magnitude, junction_above, accumulated_dist + child_dist);
coord_t total_dist_to_junction_below = junction_below.total_recti_dist;
Point a = junction_above;
Point b = junction_below.junction_loc;
if (a != b) // should always be true!
{
Point ab = b - a;
Point destination = a + ab * accumulated_dist / std::max(coord_t(1), total_dist_to_junction_below);
if (shorterThen(destination - p, magnitude))
{
p = destination;
}
else
{
p = p + normal(destination - p, magnitude);
}
}
return junction_below;
}
else
{
coord_t small_branch = 800;
auto weight = [magnitude, small_branch](coord_t d) { return std::max(10 * (small_branch - d), coord_t(std::sqrt(small_branch * d))); };
Point junction_moving_dir = normal(junction_above - p, weight(accumulated_dist));
for (auto child_p : children)
{
coord_t child_dist = vSize(p - child_p->p);
RectilinearJunction below = child_p->straighten(magnitude, p, child_dist);
junction_moving_dir += normal(below.junction_loc - p, weight(below.total_recti_dist));
}
if (junction_moving_dir != Point(0, 0) && ! children.empty())
{
coord_t junction_moving_dir_len = vSize(junction_moving_dir);
if (junction_moving_dir_len > junction_magnitude)
{
junction_moving_dir = junction_moving_dir * junction_magnitude / junction_moving_dir_len;
}
p += junction_moving_dir;
}
return RectilinearJunction{ accumulated_dist, p };
}
}
// Prune the tree from the extremeties (leaf-nodes) until the pruning distance is reached.
coord_t LightningTreeNode::prune(const coord_t& pruning_distance)
{
if (pruning_distance <= 0)
{
return 0;
}
coord_t max_distance_pruned = 0;
for (auto child_it = children.begin(); child_it != children.end(); )
{
auto& child = *child_it;
coord_t dist_pruned_child = child->prune(pruning_distance);
if (dist_pruned_child >= pruning_distance)
{ // pruning is finished for child; dont modify further
max_distance_pruned = std::max(max_distance_pruned, dist_pruned_child);
++child_it;
}
else
{
Point a = getLocation();
Point b = child->getLocation();
Point ba = a - b;
coord_t ab_len = vSize(ba);
if (dist_pruned_child + ab_len <= pruning_distance)
{ // we're still in the process of pruning
assert(child->children.empty() && "when pruning away a node all it's children must already have been pruned away");
max_distance_pruned = std::max(max_distance_pruned, dist_pruned_child + ab_len);
child_it = children.erase(child_it);
}
else
{ // pruning stops in between this node and the child
Point n = b + normal(ba, pruning_distance - dist_pruned_child);
assert(std::abs(vSize(n - b) + dist_pruned_child - pruning_distance) < 10 && "total pruned distance must be equal to the pruning_distance");
max_distance_pruned = std::max(max_distance_pruned, pruning_distance);
child->setLocation(n);
++child_it;
}
}
}
return max_distance_pruned;
}
void LightningTreeNode::convertToPolylines(Polygons& output) const
{
Polygons result;
result.newPoly();
convertToPolylines(0, result);
removeJunctionOverlap(result);
output.add(result);
}
void LightningTreeNode::convertToPolylines(size_t long_line_idx, Polygons& output) const
{
if (children.empty())
{
output[long_line_idx].add(p);
return;
}
size_t first_child_idx = rand() % children.size();
children[first_child_idx]->convertToPolylines(long_line_idx, output);
output[long_line_idx].add(p);
for (size_t idx_offset = 1; idx_offset < children.size(); idx_offset++)
{
size_t child_idx = (first_child_idx + idx_offset) % children.size();
const LightningTreeNode& child = *children[child_idx];
output.newPoly();
size_t child_line_idx = output.size() - 1;
child.convertToPolylines(child_line_idx, output);
output[child_line_idx].add(p);
}
}
void LightningTreeNode::removeJunctionOverlap(Polygons& result_lines) const
{
// TODO: only reduce lines that start at junctions, not the roots!
const coord_t reduction = 200; // TODO make configurable!
for (auto poly_it = result_lines.begin(); poly_it != result_lines.end(); )
{
PolygonRef polyline = *poly_it;
if (polyline.size() <= 1)
{
polyline = std::move(result_lines.back());
result_lines.pop_back();
continue;
}
coord_t to_be_reduced = reduction;
Point a = polyline.back();
for (int point_idx = polyline.size() - 2; point_idx >= 0; point_idx--)
{
Point b = polyline[point_idx];
Point ab = b - a;
coord_t ab_len = vSize(ab);
if (ab_len >= to_be_reduced)
{
polyline.back() = a + ab * to_be_reduced / ab_len;
break;
}
else
{
to_be_reduced -= ab_len;
polyline.pop_back();
}
a = b;
}
if (polyline.size() <= 1)
{
polyline = std::move(result_lines.back());
result_lines.pop_back();
}
else
{
++poly_it;
}
}
}
<commit_msg>fix: prevent flipflopping in branches due to straightening and junctoin moving clashing<commit_after>//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "LightningTree.h"
#include "../utils/linearAlg2D.h"
using namespace cura;
coord_t LightningTreeNode::getWeightedDistance(const Point& unsupported_loc, const coord_t& supporting_radius) const
{
size_t valence = (!is_root) + children.size();
coord_t boost = (0 < valence && valence < 4) ? 4 * supporting_radius : 0;
return vSize(getLocation() - unsupported_loc) - boost;
}
bool LightningTreeNode::hasOffspring(const std::shared_ptr<LightningTreeNode>& to_be_checked) const
{
if (to_be_checked == shared_from_this()) return true;
for (auto child_ptr : children)
{
if (child_ptr->hasOffspring(to_be_checked)) return true;
}
return false;
}
const Point& LightningTreeNode::getLocation() const
{
return p;
}
void LightningTreeNode::setLocation(const Point& loc)
{
p = loc;
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::addChild(const Point& child_loc)
{
assert(p != child_loc);
children.push_back(LightningTreeNode::create(child_loc));
return children.back();
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::addChild(std::shared_ptr<LightningTreeNode>& new_child)
{
assert(new_child != shared_from_this());
// assert(p != new_child->p);
if (p == new_child->p)
std::cerr << "wtf\n";
children.push_back(new_child);
new_child->is_root = false;
return new_child;
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::findClosestNode(const Point& x, const coord_t& supporting_radius)
{
coord_t closest_distance = getWeightedDistance(x, supporting_radius);
std::shared_ptr<LightningTreeNode> closest_node = shared_from_this();
findClosestNodeHelper(x, supporting_radius, closest_distance, closest_node);
return closest_node;
}
void LightningTreeNode::propagateToNextLayer
(
std::vector<std::shared_ptr<LightningTreeNode>>& next_trees,
const Polygons& next_outlines,
const coord_t& prune_distance,
const coord_t& smooth_magnitude
) const
{
auto tree_below = deepCopy();
// TODO: What is the correct order of the following operations?
// (NOTE: in case realign turns out _not_ to be last, would need to rewrite a few things, see the 'rerooted_parts' parameter of that function).
tree_below->prune(prune_distance);
tree_below->straighten(smooth_magnitude);
if (tree_below->realign(next_outlines, next_trees))
{
next_trees.push_back(tree_below);
}
}
// NOTE: Depth-first, as currently implemented.
// Skips the root (because that has no root itself), but all initial nodes will have the root point anyway.
void LightningTreeNode::visitBranches(const branch_visitor_func_t& visitor) const
{
for (const auto& node : children)
{
visitor(p, node->p);
node->visitBranches(visitor);
}
}
// NOTE: Depth-first, as currently implemented.
void LightningTreeNode::visitNodes(const node_visitor_func_t& visitor)
{
visitor(shared_from_this());
for (const auto& node : children)
{
node->visitNodes(visitor);
}
}
// Node:
LightningTreeNode::LightningTreeNode(const Point& p) : is_root(false), p(p) {}
// Root (and Trunk):
LightningTreeNode::LightningTreeNode(const Point& a, const Point& b) : LightningTreeNode(a)
{
children.push_back(LightningTreeNode::create(b));
is_root = true;
}
void LightningTreeNode::findClosestNodeHelper(const Point& x, const coord_t supporting_radius, coord_t& closest_distance, std::shared_ptr<LightningTreeNode>& closest_node)
{
for (const auto& node : children)
{
node->findClosestNodeHelper(x, supporting_radius, closest_distance, closest_node);
const coord_t distance = node->getWeightedDistance(x, supporting_radius);
if (distance < closest_distance)
{
closest_node = node;
closest_distance = distance;
}
}
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::deepCopy() const
{
std::shared_ptr<LightningTreeNode> local_root = LightningTreeNode::create(p);
local_root->is_root = is_root;
local_root->children.reserve(children.size());
for (const auto& node : children)
{
local_root->children.push_back(node->deepCopy());
}
return local_root;
}
bool LightningTreeNode::realign(const Polygons& outlines, std::vector<std::shared_ptr<LightningTreeNode>>& rerooted_parts, const bool& connected_to_parent)
{
// TODO: Hole(s) in the _middle_ of a line-segement, not unlikely since reconnect.
// TODO: Reconnect if not on outline -> plan is: yes, but not here anymore!
if (outlines.empty())
{
return false;
}
if (outlines.inside(p, true))
{
// Only keep children that have an unbroken connection to here, realign will put the rest in rerooted parts due to recursion:
const std::function<bool(const std::shared_ptr<LightningTreeNode>& child)> remove_unconnected_func
(
[&outlines, &rerooted_parts](const std::shared_ptr<LightningTreeNode>& child)
{
constexpr bool argument_with_connected = true;
return !child->realign(outlines, rerooted_parts, argument_with_connected);
}
);
children.erase(std::remove_if(children.begin(), children.end(), remove_unconnected_func), children.end());
return true;
}
// 'Lift' any decendants out of this tree:
for (auto& child : children)
{
constexpr bool argument_with_disconnect = false;
if (child->realign(outlines, rerooted_parts, argument_with_disconnect))
{
rerooted_parts.push_back(child);
}
}
children.clear();
if (connected_to_parent)
{
// This will now be a (new_ leaf:
p = PolygonUtils::findClosest(p, outlines).p();
return true;
}
return false;
}
void LightningTreeNode::straighten(const coord_t& magnitude)
{
straighten(magnitude, p, 0);
}
LightningTreeNode::RectilinearJunction LightningTreeNode::straighten(const coord_t& magnitude, Point junction_above, coord_t accumulated_dist)
{
const coord_t junction_magnitude = magnitude * 3 / 4;
if (children.size() == 1)
{
auto child_p = children.front();
coord_t child_dist = vSize(p - child_p->p);
RectilinearJunction junction_below = child_p->straighten(magnitude, junction_above, accumulated_dist + child_dist);
coord_t total_dist_to_junction_below = junction_below.total_recti_dist;
Point a = junction_above;
Point b = junction_below.junction_loc;
if (a != b) // should always be true!
{
Point ab = b - a;
Point destination = a + ab * accumulated_dist / std::max(coord_t(1), total_dist_to_junction_below);
if (shorterThen(destination - p, magnitude))
{
p = destination;
}
else
{
p = p + normal(destination - p, magnitude);
}
}
return junction_below;
}
else
{
coord_t small_branch = 800;
auto weight = [magnitude, small_branch](coord_t d) { return std::max(10 * (small_branch - d), coord_t(std::sqrt(small_branch * d))); };
Point junction_moving_dir = normal(junction_above - p, weight(accumulated_dist));
bool prevent_junction_moving = false;
for (auto child_p : children)
{
coord_t child_dist = vSize(p - child_p->p);
RectilinearJunction below = child_p->straighten(magnitude, p, child_dist);
junction_moving_dir += normal(below.junction_loc - p, weight(below.total_recti_dist));
if (below.total_recti_dist < magnitude) // TODO: make configurable?
{
prevent_junction_moving = true; // prevent flipflopping in branches due to straightening and junctoin moving clashing
}
}
if (junction_moving_dir != Point(0, 0) && ! children.empty() && ! prevent_junction_moving)
{
coord_t junction_moving_dir_len = vSize(junction_moving_dir);
if (junction_moving_dir_len > junction_magnitude)
{
junction_moving_dir = junction_moving_dir * junction_magnitude / junction_moving_dir_len;
}
p += junction_moving_dir;
}
return RectilinearJunction{ accumulated_dist, p };
}
}
// Prune the tree from the extremeties (leaf-nodes) until the pruning distance is reached.
coord_t LightningTreeNode::prune(const coord_t& pruning_distance)
{
if (pruning_distance <= 0)
{
return 0;
}
coord_t max_distance_pruned = 0;
for (auto child_it = children.begin(); child_it != children.end(); )
{
auto& child = *child_it;
coord_t dist_pruned_child = child->prune(pruning_distance);
if (dist_pruned_child >= pruning_distance)
{ // pruning is finished for child; dont modify further
max_distance_pruned = std::max(max_distance_pruned, dist_pruned_child);
++child_it;
}
else
{
Point a = getLocation();
Point b = child->getLocation();
Point ba = a - b;
coord_t ab_len = vSize(ba);
if (dist_pruned_child + ab_len <= pruning_distance)
{ // we're still in the process of pruning
assert(child->children.empty() && "when pruning away a node all it's children must already have been pruned away");
max_distance_pruned = std::max(max_distance_pruned, dist_pruned_child + ab_len);
child_it = children.erase(child_it);
}
else
{ // pruning stops in between this node and the child
Point n = b + normal(ba, pruning_distance - dist_pruned_child);
assert(std::abs(vSize(n - b) + dist_pruned_child - pruning_distance) < 10 && "total pruned distance must be equal to the pruning_distance");
max_distance_pruned = std::max(max_distance_pruned, pruning_distance);
child->setLocation(n);
++child_it;
}
}
}
return max_distance_pruned;
}
void LightningTreeNode::convertToPolylines(Polygons& output) const
{
Polygons result;
result.newPoly();
convertToPolylines(0, result);
removeJunctionOverlap(result);
output.add(result);
}
void LightningTreeNode::convertToPolylines(size_t long_line_idx, Polygons& output) const
{
if (children.empty())
{
output[long_line_idx].add(p);
return;
}
size_t first_child_idx = rand() % children.size();
children[first_child_idx]->convertToPolylines(long_line_idx, output);
output[long_line_idx].add(p);
for (size_t idx_offset = 1; idx_offset < children.size(); idx_offset++)
{
size_t child_idx = (first_child_idx + idx_offset) % children.size();
const LightningTreeNode& child = *children[child_idx];
output.newPoly();
size_t child_line_idx = output.size() - 1;
child.convertToPolylines(child_line_idx, output);
output[child_line_idx].add(p);
}
}
void LightningTreeNode::removeJunctionOverlap(Polygons& result_lines) const
{
// TODO: only reduce lines that start at junctions, not the roots!
const coord_t reduction = 200; // TODO make configurable!
for (auto poly_it = result_lines.begin(); poly_it != result_lines.end(); )
{
PolygonRef polyline = *poly_it;
if (polyline.size() <= 1)
{
polyline = std::move(result_lines.back());
result_lines.pop_back();
continue;
}
coord_t to_be_reduced = reduction;
Point a = polyline.back();
for (int point_idx = polyline.size() - 2; point_idx >= 0; point_idx--)
{
Point b = polyline[point_idx];
Point ab = b - a;
coord_t ab_len = vSize(ab);
if (ab_len >= to_be_reduced)
{
polyline.back() = a + ab * to_be_reduced / ab_len;
break;
}
else
{
to_be_reduced -= ab_len;
polyline.pop_back();
}
a = b;
}
if (polyline.size() <= 1)
{
polyline = std::move(result_lines.back());
result_lines.pop_back();
}
else
{
++poly_it;
}
}
}
<|endoftext|>
|
<commit_before>//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "LightningTree.h"
#include "../utils/linearAlg2D.h"
using namespace cura;
coord_t LightningTreeNode::getWeightedDistance(const Point& unsupported_loc, const coord_t& supporting_radius) const
{
size_t valence = (!is_root) + children.size();
coord_t valence_boost = (0 < valence && valence < 4) ? 4 * supporting_radius : 0;
coord_t dist_here = vSize(getLocation() - unsupported_loc);
return dist_here - valence_boost;
}
bool LightningTreeNode::hasOffspring(const std::shared_ptr<LightningTreeNode>& to_be_checked) const
{
if (to_be_checked == shared_from_this()) return true;
for (auto child_ptr : children)
{
if (child_ptr->hasOffspring(to_be_checked)) return true;
}
return false;
}
const Point& LightningTreeNode::getLocation() const
{
return p;
}
void LightningTreeNode::setLocation(const Point& loc)
{
p = loc;
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::addChild(const Point& child_loc)
{
assert(p != child_loc);
std::shared_ptr<LightningTreeNode> child = LightningTreeNode::create(child_loc);
return addChild(child);
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::addChild(std::shared_ptr<LightningTreeNode>& new_child)
{
assert(new_child != shared_from_this());
// assert(p != new_child->p);
if (p == new_child->p)
std::cerr << "wtf\n";
children.push_back(new_child);
new_child->parent = shared_from_this();
new_child->is_root = false;
return new_child;
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::findClosestNode(const Point& x, const coord_t& supporting_radius)
{
coord_t closest_distance = getWeightedDistance(x, supporting_radius);
std::shared_ptr<LightningTreeNode> closest_node = shared_from_this();
findClosestNodeHelper(x, supporting_radius, closest_distance, closest_node);
return closest_node;
}
void LightningTreeNode::propagateToNextLayer
(
std::vector<std::shared_ptr<LightningTreeNode>>& next_trees,
const Polygons& next_outlines,
const coord_t& prune_distance,
const coord_t& smooth_magnitude
) const
{
auto tree_below = deepCopy();
// TODO: What is the correct order of the following operations?
// (NOTE: in case realign turns out _not_ to be last, would need to rewrite a few things, see the 'rerooted_parts' parameter of that function).
tree_below->prune(prune_distance);
tree_below->straighten(smooth_magnitude);
if (tree_below->realign(next_outlines, next_trees))
{
next_trees.push_back(tree_below);
}
}
// NOTE: Depth-first, as currently implemented.
// Skips the root (because that has no root itself), but all initial nodes will have the root point anyway.
void LightningTreeNode::visitBranches(const std::function<void(const Point&, const Point&)>& visitor) const
{
for (const auto& node : children)
{
visitor(p, node->p);
node->visitBranches(visitor);
}
}
// NOTE: Depth-first, as currently implemented.
void LightningTreeNode::visitNodes(const std::function<void(std::shared_ptr<LightningTreeNode>)>& visitor)
{
visitor(shared_from_this());
for (const auto& node : children)
{
node->visitNodes(visitor);
}
}
LightningTreeNode::LightningTreeNode(const Point& p)
: is_root(true)
, p(p)
{}
void LightningTreeNode::findClosestNodeHelper(const Point& x, const coord_t supporting_radius, coord_t& closest_distance, std::shared_ptr<LightningTreeNode>& closest_node)
{
for (const auto& node : children)
{
node->findClosestNodeHelper(x, supporting_radius, closest_distance, closest_node);
const coord_t distance = node->getWeightedDistance(x, supporting_radius);
if (distance < closest_distance)
{
closest_node = node;
closest_distance = distance;
}
}
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::deepCopy() const
{
std::shared_ptr<LightningTreeNode> local_root = LightningTreeNode::create(p);
local_root->is_root = is_root;
local_root->children.reserve(children.size());
for (const auto& node : children)
{
std::shared_ptr<LightningTreeNode> child = node->deepCopy();
child->parent = local_root;
local_root->children.push_back(child);
}
return local_root;
}
bool LightningTreeNode::realign(const Polygons& outlines, std::vector<std::shared_ptr<LightningTreeNode>>& rerooted_parts, const bool& connected_to_parent)
{
// TODO: Hole(s) in the _middle_ of a line-segement, not unlikely since reconnect.
// TODO: Reconnect if not on outline -> plan is: yes, but not here anymore!
if (outlines.empty())
{
return false;
}
if (outlines.inside(p, true))
{
// Only keep children that have an unbroken connection to here, realign will put the rest in rerooted parts due to recursion:
const std::function<bool(const std::shared_ptr<LightningTreeNode>& child)> remove_unconnected_func
(
[&outlines, &rerooted_parts](const std::shared_ptr<LightningTreeNode>& child)
{
constexpr bool argument_with_connected = true;
return !child->realign(outlines, rerooted_parts, argument_with_connected);
}
);
children.erase(std::remove_if(children.begin(), children.end(), remove_unconnected_func), children.end());
return true;
}
// 'Lift' any decendants out of this tree:
for (auto& child : children)
{
constexpr bool argument_with_disconnect = false;
if (child->realign(outlines, rerooted_parts, argument_with_disconnect))
{
rerooted_parts.push_back(child);
}
}
children.clear();
if (connected_to_parent)
{
// This will now be a (new_ leaf:
p = PolygonUtils::findClosest(p, outlines).p();
return true;
}
return false;
}
void LightningTreeNode::straighten(const coord_t& magnitude)
{
straighten(magnitude, p, 0);
}
LightningTreeNode::RectilinearJunction LightningTreeNode::straighten(const coord_t& magnitude, const Point& junction_above, const coord_t accumulated_dist)
{
const coord_t junction_magnitude = magnitude * 3 / 4; // TODO: hardcoded value!
if (children.size() == 1)
{
auto child_p = children.front();
coord_t child_dist = vSize(p - child_p->p);
RectilinearJunction junction_below = child_p->straighten(magnitude, junction_above, accumulated_dist + child_dist);
coord_t total_dist_to_junction_below = junction_below.total_recti_dist;
Point a = junction_above;
Point b = junction_below.junction_loc;
if (a != b) // should always be true!
{
Point ab = b - a;
Point destination = a + ab * accumulated_dist / std::max(coord_t(1), total_dist_to_junction_below);
if (shorterThen(destination - p, magnitude))
{
p = destination;
}
else
{
p = p + normal(destination - p, magnitude);
}
}
{ // remove nodes on linear segments
const std::shared_ptr<LightningTreeNode>& parent_node = parent.lock();
if (parent_node && LinearAlg2D::getDist2FromLineSegment(parent_node->p, p, child_p->p) < 10)
{
child_p->parent = parent;
for (auto sibling : parent_node->children)
{
if (sibling == shared_from_this())
{
sibling = child_p;
}
}
}
}
return junction_below;
}
else
{
constexpr coord_t weight = 1000;
Point junction_moving_dir = normal(junction_above - p, weight);
bool prevent_junction_moving = false;
for (auto child_p : children)
{
coord_t child_dist = vSize(p - child_p->p);
RectilinearJunction below = child_p->straighten(magnitude, p, child_dist);
junction_moving_dir += normal(below.junction_loc - p, weight);
if (below.total_recti_dist < magnitude) // TODO: make configurable?
{
prevent_junction_moving = true; // prevent flipflopping in branches due to straightening and junctoin moving clashing
}
}
if (junction_moving_dir != Point(0, 0) && ! children.empty() && ! is_root && ! prevent_junction_moving)
{
coord_t junction_moving_dir_len = vSize(junction_moving_dir);
if (junction_moving_dir_len > junction_magnitude)
{
junction_moving_dir = junction_moving_dir * junction_magnitude / junction_moving_dir_len;
}
p += junction_moving_dir;
}
return RectilinearJunction{ accumulated_dist, p };
}
}
// Prune the tree from the extremeties (leaf-nodes) until the pruning distance is reached.
coord_t LightningTreeNode::prune(const coord_t& pruning_distance)
{
if (pruning_distance <= 0)
{
return 0;
}
coord_t max_distance_pruned = 0;
for (auto child_it = children.begin(); child_it != children.end(); )
{
auto& child = *child_it;
coord_t dist_pruned_child = child->prune(pruning_distance);
if (dist_pruned_child >= pruning_distance)
{ // pruning is finished for child; dont modify further
max_distance_pruned = std::max(max_distance_pruned, dist_pruned_child);
++child_it;
}
else
{
Point a = getLocation();
Point b = child->getLocation();
Point ba = a - b;
coord_t ab_len = vSize(ba);
if (dist_pruned_child + ab_len <= pruning_distance)
{ // we're still in the process of pruning
assert(child->children.empty() && "when pruning away a node all it's children must already have been pruned away");
max_distance_pruned = std::max(max_distance_pruned, dist_pruned_child + ab_len);
child_it = children.erase(child_it);
}
else
{ // pruning stops in between this node and the child
Point n = b + normal(ba, pruning_distance - dist_pruned_child);
assert(std::abs(vSize(n - b) + dist_pruned_child - pruning_distance) < 10 && "total pruned distance must be equal to the pruning_distance");
max_distance_pruned = std::max(max_distance_pruned, pruning_distance);
child->setLocation(n);
++child_it;
}
}
}
return max_distance_pruned;
}
void LightningTreeNode::convertToPolylines(Polygons& output, const coord_t line_width) const
{
Polygons result;
result.newPoly();
convertToPolylines(0, result);
removeJunctionOverlap(result, line_width);
output.add(result);
}
void LightningTreeNode::convertToPolylines(size_t long_line_idx, Polygons& output) const
{
if (children.empty())
{
output[long_line_idx].add(p);
return;
}
size_t first_child_idx = rand() % children.size();
children[first_child_idx]->convertToPolylines(long_line_idx, output);
output[long_line_idx].add(p);
for (size_t idx_offset = 1; idx_offset < children.size(); idx_offset++)
{
size_t child_idx = (first_child_idx + idx_offset) % children.size();
const LightningTreeNode& child = *children[child_idx];
output.newPoly();
size_t child_line_idx = output.size() - 1;
child.convertToPolylines(child_line_idx, output);
output[child_line_idx].add(p);
}
}
void LightningTreeNode::removeJunctionOverlap(Polygons& result_lines, const coord_t line_width) const
{
// TODO: only reduce lines that start at junctions, not the roots!
const coord_t reduction = line_width / 2; // TODO make configurable?
for (auto poly_it = result_lines.begin(); poly_it != result_lines.end(); )
{
PolygonRef polyline = *poly_it;
if (polyline.size() <= 1)
{
polyline = std::move(result_lines.back());
result_lines.pop_back();
continue;
}
coord_t to_be_reduced = reduction;
Point a = polyline.back();
for (int point_idx = polyline.size() - 2; point_idx >= 0; point_idx--)
{
Point b = polyline[point_idx];
Point ab = b - a;
coord_t ab_len = vSize(ab);
if (ab_len >= to_be_reduced)
{
polyline.back() = a + ab * to_be_reduced / ab_len;
break;
}
else
{
to_be_reduced -= ab_len;
polyline.pop_back();
}
a = b;
}
if (polyline.size() <= 1)
{
polyline = std::move(result_lines.back());
result_lines.pop_back();
}
else
{
++poly_it;
}
}
}
<commit_msg>fix tree modification functions<commit_after>//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "LightningTree.h"
#include "../utils/linearAlg2D.h"
using namespace cura;
coord_t LightningTreeNode::getWeightedDistance(const Point& unsupported_loc, const coord_t& supporting_radius) const
{
size_t valence = (!is_root) + children.size();
coord_t valence_boost = (0 < valence && valence < 4) ? 4 * supporting_radius : 0;
coord_t dist_here = vSize(getLocation() - unsupported_loc);
return dist_here - valence_boost;
}
bool LightningTreeNode::hasOffspring(const std::shared_ptr<LightningTreeNode>& to_be_checked) const
{
if (to_be_checked == shared_from_this()) return true;
for (auto& child_ptr : children)
{
if (child_ptr->hasOffspring(to_be_checked)) return true;
}
return false;
}
const Point& LightningTreeNode::getLocation() const
{
return p;
}
void LightningTreeNode::setLocation(const Point& loc)
{
p = loc;
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::addChild(const Point& child_loc)
{
assert(p != child_loc);
std::shared_ptr<LightningTreeNode> child = LightningTreeNode::create(child_loc);
return addChild(child);
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::addChild(std::shared_ptr<LightningTreeNode>& new_child)
{
assert(new_child != shared_from_this());
// assert(p != new_child->p);
if (p == new_child->p)
std::cerr << "wtf\n";
children.push_back(new_child);
new_child->parent = shared_from_this();
new_child->is_root = false;
return new_child;
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::findClosestNode(const Point& x, const coord_t& supporting_radius)
{
coord_t closest_distance = getWeightedDistance(x, supporting_radius);
std::shared_ptr<LightningTreeNode> closest_node = shared_from_this();
findClosestNodeHelper(x, supporting_radius, closest_distance, closest_node);
return closest_node;
}
void LightningTreeNode::propagateToNextLayer
(
std::vector<std::shared_ptr<LightningTreeNode>>& next_trees,
const Polygons& next_outlines,
const coord_t& prune_distance,
const coord_t& smooth_magnitude
) const
{
auto tree_below = deepCopy();
// TODO: What is the correct order of the following operations?
// (NOTE: in case realign turns out _not_ to be last, would need to rewrite a few things, see the 'rerooted_parts' parameter of that function).
tree_below->prune(prune_distance);
tree_below->straighten(smooth_magnitude);
if (tree_below->realign(next_outlines, next_trees))
{
next_trees.push_back(tree_below);
}
}
// NOTE: Depth-first, as currently implemented.
// Skips the root (because that has no root itself), but all initial nodes will have the root point anyway.
void LightningTreeNode::visitBranches(const std::function<void(const Point&, const Point&)>& visitor) const
{
for (const auto& node : children)
{
assert(node->parent.lock() == shared_from_this());
visitor(p, node->p);
node->visitBranches(visitor);
}
}
// NOTE: Depth-first, as currently implemented.
void LightningTreeNode::visitNodes(const std::function<void(std::shared_ptr<LightningTreeNode>)>& visitor)
{
visitor(shared_from_this());
for (const auto& node : children)
{
assert(node->parent.lock() == shared_from_this());
node->visitNodes(visitor);
}
}
LightningTreeNode::LightningTreeNode(const Point& p)
: is_root(true)
, p(p)
{}
void LightningTreeNode::findClosestNodeHelper(const Point& x, const coord_t supporting_radius, coord_t& closest_distance, std::shared_ptr<LightningTreeNode>& closest_node)
{
for (const auto& node : children)
{
node->findClosestNodeHelper(x, supporting_radius, closest_distance, closest_node);
const coord_t distance = node->getWeightedDistance(x, supporting_radius);
if (distance < closest_distance)
{
closest_node = node;
closest_distance = distance;
}
}
}
std::shared_ptr<LightningTreeNode> LightningTreeNode::deepCopy() const
{
std::shared_ptr<LightningTreeNode> local_root = LightningTreeNode::create(p);
local_root->is_root = is_root;
local_root->children.reserve(children.size());
for (const auto& node : children)
{
std::shared_ptr<LightningTreeNode> child = node->deepCopy();
child->parent = local_root;
local_root->children.push_back(child);
}
return local_root;
}
bool LightningTreeNode::realign(const Polygons& outlines, std::vector<std::shared_ptr<LightningTreeNode>>& rerooted_parts, const bool& connected_to_parent)
{
// TODO: Hole(s) in the _middle_ of a line-segement, not unlikely since reconnect.
// TODO: Reconnect if not on outline -> plan is: yes, but not here anymore!
if (outlines.empty())
{
return false;
}
if (outlines.inside(p, true))
{
// Only keep children that have an unbroken connection to here, realign will put the rest in rerooted parts due to recursion:
const std::function<bool(const std::shared_ptr<LightningTreeNode>& child)> remove_unconnected_func
(
[&outlines, &rerooted_parts](const std::shared_ptr<LightningTreeNode>& child)
{
constexpr bool argument_with_connected = true;
return !child->realign(outlines, rerooted_parts, argument_with_connected);
}
);
children.erase(std::remove_if(children.begin(), children.end(), remove_unconnected_func), children.end());
return true;
}
// 'Lift' any decendants out of this tree:
for (auto& child : children)
{
constexpr bool argument_with_disconnect = false;
if (child->realign(outlines, rerooted_parts, argument_with_disconnect))
{
rerooted_parts.push_back(child);
}
}
children.clear();
if (connected_to_parent)
{
// This will now be a (new_ leaf:
p = PolygonUtils::findClosest(p, outlines).p();
return true;
}
return false;
}
void LightningTreeNode::straighten(const coord_t& magnitude)
{
straighten(magnitude, p, 0);
}
LightningTreeNode::RectilinearJunction LightningTreeNode::straighten(const coord_t& magnitude, const Point& junction_above, const coord_t accumulated_dist)
{
const coord_t junction_magnitude = magnitude * 3 / 4; // TODO: hardcoded value!
if (children.size() == 1)
{
auto child_p = children.front();
coord_t child_dist = vSize(p - child_p->p);
RectilinearJunction junction_below = child_p->straighten(magnitude, junction_above, accumulated_dist + child_dist);
coord_t total_dist_to_junction_below = junction_below.total_recti_dist;
Point a = junction_above;
Point b = junction_below.junction_loc;
if (a != b) // should always be true!
{
Point ab = b - a;
Point destination = a + ab * accumulated_dist / std::max(coord_t(1), total_dist_to_junction_below);
if (shorterThen(destination - p, magnitude))
{
p = destination;
}
else
{
p = p + normal(destination - p, magnitude);
}
}
{ // remove nodes on linear segments
child_p = children.front(); //recursive call to straighten might have removed the child
const std::shared_ptr<LightningTreeNode>& parent_node = parent.lock();
if (parent_node && LinearAlg2D::getDist2FromLineSegment(parent_node->p, p, child_p->p) < 10)
{
child_p->parent = parent;
for (auto& sibling : parent_node->children)
{ // find this node among siblings
if (sibling == shared_from_this())
{
sibling = child_p; // replace this node by child
break;
}
}
}
}
return junction_below;
}
else
{
constexpr coord_t weight = 1000;
Point junction_moving_dir = normal(junction_above - p, weight);
bool prevent_junction_moving = false;
for (auto& child_p : children)
{
coord_t child_dist = vSize(p - child_p->p);
RectilinearJunction below = child_p->straighten(magnitude, p, child_dist);
junction_moving_dir += normal(below.junction_loc - p, weight);
if (below.total_recti_dist < magnitude) // TODO: make configurable?
{
prevent_junction_moving = true; // prevent flipflopping in branches due to straightening and junctoin moving clashing
}
}
if (junction_moving_dir != Point(0, 0) && ! children.empty() && ! is_root && ! prevent_junction_moving)
{
coord_t junction_moving_dir_len = vSize(junction_moving_dir);
if (junction_moving_dir_len > junction_magnitude)
{
junction_moving_dir = junction_moving_dir * junction_magnitude / junction_moving_dir_len;
}
p += junction_moving_dir;
}
return RectilinearJunction{ accumulated_dist, p };
}
}
// Prune the tree from the extremeties (leaf-nodes) until the pruning distance is reached.
coord_t LightningTreeNode::prune(const coord_t& pruning_distance)
{
if (pruning_distance <= 0)
{
return 0;
}
coord_t max_distance_pruned = 0;
for (auto child_it = children.begin(); child_it != children.end(); )
{
auto& child = *child_it;
coord_t dist_pruned_child = child->prune(pruning_distance);
if (dist_pruned_child >= pruning_distance)
{ // pruning is finished for child; dont modify further
max_distance_pruned = std::max(max_distance_pruned, dist_pruned_child);
++child_it;
}
else
{
Point a = getLocation();
Point b = child->getLocation();
Point ba = a - b;
coord_t ab_len = vSize(ba);
if (dist_pruned_child + ab_len <= pruning_distance)
{ // we're still in the process of pruning
assert(child->children.empty() && "when pruning away a node all it's children must already have been pruned away");
max_distance_pruned = std::max(max_distance_pruned, dist_pruned_child + ab_len);
child_it = children.erase(child_it);
}
else
{ // pruning stops in between this node and the child
Point n = b + normal(ba, pruning_distance - dist_pruned_child);
assert(std::abs(vSize(n - b) + dist_pruned_child - pruning_distance) < 10 && "total pruned distance must be equal to the pruning_distance");
max_distance_pruned = std::max(max_distance_pruned, pruning_distance);
child->setLocation(n);
++child_it;
}
}
}
return max_distance_pruned;
}
void LightningTreeNode::convertToPolylines(Polygons& output, const coord_t line_width) const
{
Polygons result;
result.newPoly();
convertToPolylines(0, result);
removeJunctionOverlap(result, line_width);
output.add(result);
}
void LightningTreeNode::convertToPolylines(size_t long_line_idx, Polygons& output) const
{
if (children.empty())
{
output[long_line_idx].add(p);
return;
}
size_t first_child_idx = rand() % children.size();
children[first_child_idx]->convertToPolylines(long_line_idx, output);
output[long_line_idx].add(p);
for (size_t idx_offset = 1; idx_offset < children.size(); idx_offset++)
{
size_t child_idx = (first_child_idx + idx_offset) % children.size();
const LightningTreeNode& child = *children[child_idx];
output.newPoly();
size_t child_line_idx = output.size() - 1;
child.convertToPolylines(child_line_idx, output);
output[child_line_idx].add(p);
}
}
void LightningTreeNode::removeJunctionOverlap(Polygons& result_lines, const coord_t line_width) const
{
// TODO: only reduce lines that start at junctions, not the roots!
const coord_t reduction = line_width / 2; // TODO make configurable?
for (auto poly_it = result_lines.begin(); poly_it != result_lines.end(); )
{
PolygonRef polyline = *poly_it;
if (polyline.size() <= 1)
{
polyline = std::move(result_lines.back());
result_lines.pop_back();
continue;
}
coord_t to_be_reduced = reduction;
Point a = polyline.back();
for (int point_idx = polyline.size() - 2; point_idx >= 0; point_idx--)
{
Point b = polyline[point_idx];
Point ab = b - a;
coord_t ab_len = vSize(ab);
if (ab_len >= to_be_reduced)
{
polyline.back() = a + ab * to_be_reduced / ab_len;
break;
}
else
{
to_be_reduced -= ab_len;
polyline.pop_back();
}
a = b;
}
if (polyline.size() <= 1)
{
polyline = std::move(result_lines.back());
result_lines.pop_back();
}
else
{
++poly_it;
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/pivx/coldstakingmodel.h"
#include "uint256.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include <iostream>
#include "addressbook.h"
ColdStakingModel::ColdStakingModel(WalletModel* _model,
TransactionTableModel* _tableModel,
AddressTableModel* _addressTableModel,
QObject *parent) : QAbstractTableModel(parent), model(_model), tableModel(_tableModel), addressTableModel(_addressTableModel){
updateCSList();
}
void ColdStakingModel::updateCSList() {
refresh();
emit dataChanged(index(0, 0, QModelIndex()), index(rowCount(), COLUMN_COUNT, QModelIndex()) );
}
void ColdStakingModel::refresh() {
cachedDelegations.clear();
// First get all of the p2cs utxo inside the wallet
std::vector<COutput> utxoList;
pwalletMain->GetAvailableP2CSCoins(utxoList);
if (!utxoList.empty()) {
// Loop over each COutput into a CSDelegation
for (const auto& utxo : utxoList) {
const auto *wtx = utxo.tx;
const QString txId = QString::fromStdString(wtx->GetHash().GetHex());
const CTxOut& out = wtx->vout[utxo.i];
// First parse the cs delegation
CSDelegation delegation;
if (!parseCSDelegation(out, delegation, txId, utxo.i))
continue;
// it's spendable only when this wallet has the keys to spend it, a.k.a is the owner
delegation.isSpendable = pwalletMain->IsMine(out) & ISMINE_SPENDABLE_DELEGATED;
delegation.cachedTotalAmount += out.nValue;
delegation.delegatedUtxo.insert(txId, utxo.i);
// Now verify if the delegation exists in the cached list
int indexDel = cachedDelegations.indexOf(delegation);
if (indexDel == -1) {
// If it doesn't, let's append it.
cachedDelegations.append(delegation);
} else {
CSDelegation& del = cachedDelegations[indexDel];
del.delegatedUtxo.unite(delegation.delegatedUtxo);
del.cachedTotalAmount += delegation.cachedTotalAmount;
}
}
}
}
bool ColdStakingModel::parseCSDelegation(const CTxOut& out, CSDelegation& ret, const QString& txId, const int& utxoIndex) {
CTxDestination stakingAddressDest;
CTxDestination ownerAddressDest;
if (!ExtractDestination(out.scriptPubKey, stakingAddressDest, true)) {
return error("Error extracting staking destination for: %1 , output index: %2", txId.toStdString(), utxoIndex);
}
if (!ExtractDestination(out.scriptPubKey, ownerAddressDest, false)) {
return error("Error extracting owner destination for: %1 , output index: %2", txId.toStdString(), utxoIndex);
}
std::string stakingAddressStr = CBitcoinAddress(
stakingAddressDest,
CChainParams::STAKING_ADDRESS
).ToString();
std::string ownerAddressStr = CBitcoinAddress(
ownerAddressDest,
CChainParams::PUBKEY_ADDRESS
).ToString();
ret = CSDelegation(stakingAddressStr, ownerAddressStr);
return true;
}
int ColdStakingModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return cachedDelegations.size();
}
int ColdStakingModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return COLUMN_COUNT;
}
QVariant ColdStakingModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
int row = index.row();
CSDelegation rec = cachedDelegations[row];
if (role == Qt::DisplayRole || role == Qt::EditRole) {
switch (index.column()) {
case OWNER_ADDRESS:
return QString::fromStdString(rec.ownerAddress);
case OWNER_ADDRESS_LABEL:
return addressTableModel->labelForAddress(QString::fromStdString(rec.ownerAddress));
case STAKING_ADDRESS:
return QString::fromStdString(rec.stakingAddress);
case STAKING_ADDRESS_LABEL:
return addressTableModel->labelForAddress(QString::fromStdString(rec.stakingAddress));
case IS_WHITELISTED:
return addressTableModel->purposeForAddress(rec.ownerAddress).compare(AddressBook::AddressBookPurpose::DELEGATOR) == 0;
case IS_WHITELISTED_STRING:
return (addressTableModel->purposeForAddress(rec.ownerAddress) == AddressBook::AddressBookPurpose::DELEGATOR ? "Staking" : "Not staking");
case TOTAL_STACKEABLE_AMOUNT_STR:
return GUIUtil::formatBalance(rec.cachedTotalAmount);
case TOTAL_STACKEABLE_AMOUNT:
return qint64(rec.cachedTotalAmount);
case IS_RECEIVED_DELEGATION:
return !rec.isSpendable;
}
}
return QVariant();
}
bool ColdStakingModel::whitelist(const QModelIndex& modelIndex) {
QString address = modelIndex.data(Qt::DisplayRole).toString();
int idx = modelIndex.row();
beginRemoveRows(QModelIndex(), idx, idx);
bool ret = model->whitelistAddressFromColdStaking(address);
endRemoveRows();
emit dataChanged(index(idx, 0, QModelIndex()), index(idx, COLUMN_COUNT, QModelIndex()) );
return ret;
}
bool ColdStakingModel::blacklist(const QModelIndex& modelIndex) {
QString address = modelIndex.data(Qt::DisplayRole).toString();
int idx = modelIndex.row();
beginRemoveRows(QModelIndex(), idx, idx);
bool ret = model->blacklistAddressFromColdStaking(address);
endRemoveRows();
emit dataChanged(index(idx, 0, QModelIndex()), index(idx, COLUMN_COUNT, QModelIndex()) );
return ret;
}<commit_msg>[Model] Use ExtractDestinations to get recipients of P2CS scripts<commit_after>// Copyright (c) 2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/pivx/coldstakingmodel.h"
#include "uint256.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include <iostream>
#include "addressbook.h"
ColdStakingModel::ColdStakingModel(WalletModel* _model,
TransactionTableModel* _tableModel,
AddressTableModel* _addressTableModel,
QObject *parent) : QAbstractTableModel(parent), model(_model), tableModel(_tableModel), addressTableModel(_addressTableModel){
updateCSList();
}
void ColdStakingModel::updateCSList() {
refresh();
emit dataChanged(index(0, 0, QModelIndex()), index(rowCount(), COLUMN_COUNT, QModelIndex()) );
}
void ColdStakingModel::refresh() {
cachedDelegations.clear();
// First get all of the p2cs utxo inside the wallet
std::vector<COutput> utxoList;
pwalletMain->GetAvailableP2CSCoins(utxoList);
if (!utxoList.empty()) {
// Loop over each COutput into a CSDelegation
for (const auto& utxo : utxoList) {
const auto *wtx = utxo.tx;
const QString txId = QString::fromStdString(wtx->GetHash().GetHex());
const CTxOut& out = wtx->vout[utxo.i];
// First parse the cs delegation
CSDelegation delegation;
if (!parseCSDelegation(out, delegation, txId, utxo.i))
continue;
// it's spendable only when this wallet has the keys to spend it, a.k.a is the owner
delegation.isSpendable = pwalletMain->IsMine(out) & ISMINE_SPENDABLE_DELEGATED;
delegation.cachedTotalAmount += out.nValue;
delegation.delegatedUtxo.insert(txId, utxo.i);
// Now verify if the delegation exists in the cached list
int indexDel = cachedDelegations.indexOf(delegation);
if (indexDel == -1) {
// If it doesn't, let's append it.
cachedDelegations.append(delegation);
} else {
CSDelegation& del = cachedDelegations[indexDel];
del.delegatedUtxo.unite(delegation.delegatedUtxo);
del.cachedTotalAmount += delegation.cachedTotalAmount;
}
}
}
}
bool ColdStakingModel::parseCSDelegation(const CTxOut& out, CSDelegation& ret, const QString& txId, const int& utxoIndex) {
txnouttype type;
std::vector<CTxDestination> addresses;
int nRequired;
if (!ExtractDestinations(out.scriptPubKey, type, addresses, nRequired) || addresses.size() != 2) {
return error("%s : Error extracting P2CS destinations for utxo: %s-%d",
__func__, txId.toStdString(), utxoIndex);
}
std::string stakingAddressStr = CBitcoinAddress(
addresses[0],
CChainParams::STAKING_ADDRESS
).ToString();
std::string ownerAddressStr = CBitcoinAddress(
addresses[1],
CChainParams::PUBKEY_ADDRESS
).ToString();
ret = CSDelegation(stakingAddressStr, ownerAddressStr);
return true;
}
int ColdStakingModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return cachedDelegations.size();
}
int ColdStakingModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return COLUMN_COUNT;
}
QVariant ColdStakingModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
int row = index.row();
CSDelegation rec = cachedDelegations[row];
if (role == Qt::DisplayRole || role == Qt::EditRole) {
switch (index.column()) {
case OWNER_ADDRESS:
return QString::fromStdString(rec.ownerAddress);
case OWNER_ADDRESS_LABEL:
return addressTableModel->labelForAddress(QString::fromStdString(rec.ownerAddress));
case STAKING_ADDRESS:
return QString::fromStdString(rec.stakingAddress);
case STAKING_ADDRESS_LABEL:
return addressTableModel->labelForAddress(QString::fromStdString(rec.stakingAddress));
case IS_WHITELISTED:
return addressTableModel->purposeForAddress(rec.ownerAddress).compare(AddressBook::AddressBookPurpose::DELEGATOR) == 0;
case IS_WHITELISTED_STRING:
return (addressTableModel->purposeForAddress(rec.ownerAddress) == AddressBook::AddressBookPurpose::DELEGATOR ? "Staking" : "Not staking");
case TOTAL_STACKEABLE_AMOUNT_STR:
return GUIUtil::formatBalance(rec.cachedTotalAmount);
case TOTAL_STACKEABLE_AMOUNT:
return qint64(rec.cachedTotalAmount);
case IS_RECEIVED_DELEGATION:
return !rec.isSpendable;
}
}
return QVariant();
}
bool ColdStakingModel::whitelist(const QModelIndex& modelIndex) {
QString address = modelIndex.data(Qt::DisplayRole).toString();
int idx = modelIndex.row();
beginRemoveRows(QModelIndex(), idx, idx);
bool ret = model->whitelistAddressFromColdStaking(address);
endRemoveRows();
emit dataChanged(index(idx, 0, QModelIndex()), index(idx, COLUMN_COUNT, QModelIndex()) );
return ret;
}
bool ColdStakingModel::blacklist(const QModelIndex& modelIndex) {
QString address = modelIndex.data(Qt::DisplayRole).toString();
int idx = modelIndex.row();
beginRemoveRows(QModelIndex(), idx, idx);
bool ret = model->blacklistAddressFromColdStaking(address);
endRemoveRows();
emit dataChanged(index(idx, 0, QModelIndex()), index(idx, COLUMN_COUNT, QModelIndex()) );
return ret;
}
<|endoftext|>
|
<commit_before>
#include "../interface/Color.h"
Color::Color() {
// Default constructor
}
Color::Color(int a1, int a2, int a3, int a4) :
id_(a1)
{
r_ = a2/255.;
g_ = a3/255.;
b_ = a4/255.;
}
//Static function to initialize all custom colors into vector of Colors
std::vector<Color> Color::init() {
std::vector<Color> mycolors;
//Define all custom colors
mycolors.push_back(Color(vNinerRed , 175, 30, 44));
mycolors.push_back(Color(vArsenalRed , 234, 34, 18));//lightest
mycolors.push_back(Color(vStanfordRed , 140, 21, 21));//darkest
mycolors.push_back(Color(vArgentineBlue , 117, 170, 219));//sample
mycolors.push_back(Color(vSharkBlue , 5, 83, 93));//'dark' teal
mycolors.push_back(Color(vQuakesBlue , 0, 81, 186));//brighter
mycolors.push_back(Color(vSabercatGreen , 0, 102, 51));
mycolors.push_back(Color(vOregonGreen , 0, 79, 39));
mycolors.push_back(Color(vIndianGreen , 19, 136, 8));//lightest
mycolors.push_back(Color(vGiantOrange , 242, 85, 44));//darkest
mycolors.push_back(Color(vSharkOrange , 243, 143, 32));//more yellowish
mycolors.push_back(Color(vDutchOrange , 255, 79, 0));//lightest
mycolors.push_back(Color(vWarriorYellow , 255, 204, 51));//darkest
mycolors.push_back(Color(vAthleticYellow , 255, 216, 0));//lightest
mycolors.push_back(Color(vUCRYellow , 241, 171, 0));//gold-ish
mycolors.push_back(Color(vKingsPurple , 117, 59, 189));//lightest
mycolors.push_back(Color(vKStatePurple , 79, 38, 131));//darkest
mycolors.push_back(Color(vUCRPurple , 98, 74, 126));//dull
mycolors.push_back(Color(vNeonGreen , 57, 255, 20));
mycolors.push_back(Color(vNeonPink , 213, 38, 181));
mycolors.push_back(Color(vNeonOrange , 255, 103, 0));
mycolors.push_back(Color(vNinerGold , 230, 190, 138));
mycolors.push_back(Color(vKingsSilver , 138, 141, 143));//darker
mycolors.push_back(Color(vQuakesSilver , 177, 180, 178));//lighter
//
//mycolors.push_back(Color(9999 , 50, 132, 191));//sample
mycolors.push_back(Color(3004,255,253,208));//Giants Offwhite
//Retired colors..
////mycolors.push_back(Color(vAthleticGreen , 0, 56, 49));//darkest
////mycolors.push_back(Color(vWarriorBlue , 4, 82, 156));
return mycolors;
}
//Plot all custom colors
//Can call this static function without DrawTree object created beforehand (perhaps even recommended)
void Color::plotTheColors() {
myp("Creating plot of all custom colors\n");
rt::pts(vInfo);
TCanvas * can = new TCanvas("can","",400,400);
std::vector<Color> mycolors = init();
std::vector<TColor *> theColors;
std::vector<TH2I *> hists;
std::vector<TLine *> vert;
std::vector<TLine *> hori;
//Create all custom TColors
for ( std::vector<Color>::const_iterator col = mycolors.begin(); col != mycolors.end(); ++col )
theColors.push_back(col->convert());
//Set initial values
//TLine values
int lcolor = kBlack;
int lwidth = 3;
//Logic for a RxC grid of colors
int ncolors = mycolors.size();
int rows = 3;
int columns = ncolors / rows;
columns = ncolors % rows == 0 ? columns : columns + 1;
//Create objects
for ( std::vector<Color>::const_iterator itr = mycolors.begin() ; itr != mycolors.end() ; ++itr) {
TString name = "hist"; name += itr->getId();
hists.push_back(new TH2I(name.Data(),name.Data(),rows,0,rows*10,columns,0,columns*5));
}
//Create lines to separate the boxes
TH2I * first = * hists.begin();
int xmax = first->GetXaxis()->GetXmax();
int ymax = first->GetYaxis()->GetXmax();
for (int ix = 1; ix <= first->GetXaxis()->GetNbins()+1; ++ix ) {
vert.push_back(new TLine(first->GetXaxis()->GetBinLowEdge(ix),0,first->GetXaxis()->GetBinLowEdge(ix),ymax));
}
for (int iy = 1; iy <= first->GetYaxis()->GetNbins()+1; ++iy ) {
hori.push_back(new TLine(0,first->GetYaxis()->GetBinLowEdge(iy),xmax,first->GetYaxis()->GetBinLowEdge(iy)));
}
//Stylize the objects
int bin = 0, binx = 1, biny = 0;
for ( std::vector<TH2I *>::const_iterator itr = hists.begin() ; itr != hists.end() ; ++itr) {
if ( (bin)%rows==0 ) { binx = 1; ++biny; }
else { ++binx; }
(*itr)->SetBinContent(binx,biny,mycolors[bin].getId());
(*itr)->SetFillColor(mycolors[bin].getId());
(*itr)->SetTitle("Custom Colors");
(*itr)->SetStats(0);
++bin;
}
//Draw the objects
for ( std::vector<TH2I *>::const_iterator itr = hists.begin() ; itr != hists.end() ; ++itr) {
TString opt = "text a box";
if ( itr != hists.begin() ) opt += " same";
(*itr)->Draw(opt);
}
for ( std::vector<TLine *>::const_iterator itr = vert.begin() ; itr != vert.end() ; ++itr) {
(*itr)->SetLineWidth(lwidth);
(*itr)->SetLineColor(lcolor);
(*itr)->Draw("same");
}
for ( std::vector<TLine *>::const_iterator itr = hori.begin() ; itr != hori.end() ; ++itr) {
(*itr)->SetLineWidth(lwidth);
(*itr)->SetLineColor(lcolor);
(*itr)->Draw("same");
}
//Save it somewhere obvious
can->SaveAs("AllCustomColors.pdf");
}
<commit_msg>fix typo in Color plot<commit_after>
#include "../interface/Color.h"
Color::Color() {
// Default constructor
}
Color::Color(int a1, int a2, int a3, int a4) :
id_(a1)
{
r_ = a2/255.;
g_ = a3/255.;
b_ = a4/255.;
}
//Static function to initialize all custom colors into vector of Colors
std::vector<Color> Color::init() {
std::vector<Color> mycolors;
//Define all custom colors
mycolors.push_back(Color(vNinerRed , 175, 30, 44));
mycolors.push_back(Color(vArsenalRed , 234, 34, 18));//lightest
mycolors.push_back(Color(vStanfordRed , 140, 21, 21));//darkest
mycolors.push_back(Color(vArgentineBlue , 117, 170, 219));//sample
mycolors.push_back(Color(vSharkBlue , 5, 83, 93));//'dark' teal
mycolors.push_back(Color(vQuakesBlue , 0, 81, 186));//brighter
mycolors.push_back(Color(vSabercatGreen , 0, 102, 51));
mycolors.push_back(Color(vOregonGreen , 0, 79, 39));
mycolors.push_back(Color(vIndianGreen , 19, 136, 8));//lightest
mycolors.push_back(Color(vGiantOrange , 242, 85, 44));//darkest
mycolors.push_back(Color(vSharkOrange , 243, 143, 32));//more yellowish
mycolors.push_back(Color(vDutchOrange , 255, 79, 0));//lightest
mycolors.push_back(Color(vWarriorYellow , 255, 204, 51));//darkest
mycolors.push_back(Color(vAthleticYellow , 255, 216, 0));//lightest
mycolors.push_back(Color(vUCRYellow , 241, 171, 0));//gold-ish
mycolors.push_back(Color(vKingsPurple , 117, 59, 189));//lightest
mycolors.push_back(Color(vKStatePurple , 79, 38, 131));//darkest
mycolors.push_back(Color(vUCRPurple , 98, 74, 126));//dull
mycolors.push_back(Color(vNeonGreen , 57, 255, 20));
mycolors.push_back(Color(vNeonPink , 213, 38, 181));
mycolors.push_back(Color(vNeonOrange , 255, 103, 0));
mycolors.push_back(Color(vNinerGold , 230, 190, 138));
mycolors.push_back(Color(vKingsSilver , 138, 141, 143));//darker
mycolors.push_back(Color(vQuakesSilver , 177, 180, 178));//lighter
//
//mycolors.push_back(Color(9999 , 50, 132, 191));//sample
mycolors.push_back(Color(3004,255,253,208));//Giants Offwhite
//Retired colors..
////mycolors.push_back(Color(vAthleticGreen , 0, 56, 49));//darkest
////mycolors.push_back(Color(vWarriorBlue , 4, 82, 156));
return mycolors;
}
//Plot all custom colors
//Can call this static function without DrawTree object created beforehand (perhaps even recommended)
void Color::plotTheColors() {
myp("Creating plot of all custom colors\n");
rt::pts(vInfo);
TCanvas * can = new TCanvas("can","",400,400);
std::vector<Color> mycolors = init();
std::vector<TColor *> theColors;
std::vector<TH2I *> hists;
std::vector<TLine *> vert;
std::vector<TLine *> hori;
//Create all custom TColors
for ( std::vector<Color>::const_iterator col = mycolors.begin(); col != mycolors.end(); ++col )
theColors.push_back(col->convert());
//Set initial values
//TLine values
int lcolor = kBlack;
int lwidth = 3;
//Logic for a RxC grid of colors
// - For now keep only 3 columns, as there are not enough colors to justify a fourth column
int ncolors = mycolors.size();
int columns = 3;
int rows = ncolors / columns;
rows = ncolors % columns == 0 ? rows : rows + 1;
//Create objects
for ( std::vector<Color>::const_iterator itr = mycolors.begin() ; itr != mycolors.end() ; ++itr) {
TString name = "hist"; name += itr->getId();
hists.push_back(new TH2I(name.Data(),name.Data(),columns,0,columns*10,rows,0,rows*5));
}
//Create lines to separate the boxes
TH2I * first = * hists.begin();
int xmax = first->GetXaxis()->GetXmax();
int ymax = first->GetYaxis()->GetXmax();
for (int ix = 1; ix <= first->GetXaxis()->GetNbins()+1; ++ix ) {
vert.push_back(new TLine(first->GetXaxis()->GetBinLowEdge(ix),0,first->GetXaxis()->GetBinLowEdge(ix),ymax));
}
for (int iy = 1; iy <= first->GetYaxis()->GetNbins()+1; ++iy ) {
hori.push_back(new TLine(0,first->GetYaxis()->GetBinLowEdge(iy),xmax,first->GetYaxis()->GetBinLowEdge(iy)));
}
//Stylize the objects
int bin = 0, binx = 1, biny = 0;
for ( std::vector<TH2I *>::const_iterator itr = hists.begin() ; itr != hists.end() ; ++itr) {
if ( (bin)%columns==0 ) { binx = 1; ++biny; }
else { ++binx; }
(*itr)->SetBinContent(binx,biny,mycolors[bin].getId());
(*itr)->SetFillColor(mycolors[bin].getId());
(*itr)->SetTitle("Custom Colors");
(*itr)->SetStats(0);
++bin;
}
//Draw the objects
for ( std::vector<TH2I *>::const_iterator itr = hists.begin() ; itr != hists.end() ; ++itr) {
TString opt = "text a box";
if ( itr != hists.begin() ) opt += " same";
(*itr)->Draw(opt);
}
for ( std::vector<TLine *>::const_iterator itr = vert.begin() ; itr != vert.end() ; ++itr) {
(*itr)->SetLineWidth(lwidth);
(*itr)->SetLineColor(lcolor);
(*itr)->Draw("same");
}
for ( std::vector<TLine *>::const_iterator itr = hori.begin() ; itr != hori.end() ; ++itr) {
(*itr)->SetLineWidth(lwidth);
(*itr)->SetLineColor(lcolor);
(*itr)->Draw("same");
}
//Save it somewhere obvious
can->SaveAs("AllCustomColors.pdf");
}
<|endoftext|>
|
<commit_before>#include "MWViewController.h"
#include "MWGameScene.h"
#include "MWGameView.h"
#include "MWViewSegue.h"
#if MW_ENABLE_SCRIPT_BINDING
#include "../lua/MWLuaUtils.h"
#endif
#include <new>
using namespace cocos2d;
using namespace std;
MW_FRAMEWORK_BEGIN
MWViewController *MWViewController::create(MWViewSegue *segue)
{
auto pVc = new (nothrow) MWViewController();
if (pVc && pVc->init(segue)) {
pVc->autorelease();
return pVc;
}
CC_SAFE_RELEASE(pVc);
return nullptr;
}
bool MWViewController::init(MWViewSegue *segue)
{
_segue = segue;
return true;
}
MWViewController::MWViewController()
: _scene(nullptr)
, _view(nullptr)
, _segue(nullptr)
, _identifer()
{
}
MWViewController::~MWViewController()
{
CC_SAFE_RELEASE(_view);
}
void MWViewController::viewDidLoad()
{
if (!_view) {
_view = MWGameView::create();
_view->retain();
}
#if MW_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeLua) {
MWLuaUtils::getInstance()->executePeertableFunction(this, "viewDidLoad", nullptr, nullptr, false);
} else if (_scriptType == kScriptTypeJavascript) {
// js todo
}
#endif
}
void MWViewController::viewDidUnload()
{
#if MW_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeLua) {
MWLuaUtils::getInstance()->executePeertableFunction(this, "viewDidUnload", nullptr, nullptr, false);
} else if (_scriptType == kScriptTypeJavascript) {
// js todo
}
#endif
if (_view && _view->getParent()) {
_view->removeFromParent();
}
}
void MWViewController::didReceiveMemoryWarning()
{
#if MW_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeLua) {
MWLuaUtils::getInstance()->executePeertableFunction(this, "didReceiveMemoryWarning", nullptr, nullptr, false);
} else if (_scriptType == kScriptTypeJavascript) {
// js todo
}
#endif
}
MW_FRAMEWORK_END
<commit_msg>fix vc segue bug<commit_after>#include "MWViewController.h"
#include "MWGameScene.h"
#include "MWGameView.h"
#include "MWViewSegue.h"
#if MW_ENABLE_SCRIPT_BINDING
#include "../lua/MWLuaUtils.h"
#endif
#include <new>
using namespace cocos2d;
using namespace std;
MW_FRAMEWORK_BEGIN
MWViewController *MWViewController::create(MWViewSegue *segue)
{
auto pVc = new (nothrow) MWViewController();
if (pVc && pVc->init(segue)) {
pVc->autorelease();
return pVc;
}
CC_SAFE_RELEASE(pVc);
return nullptr;
}
bool MWViewController::init(MWViewSegue *segue)
{
CC_SAFE_RELEASE(_segue);
_segue = segue;
CC_SAFE_RETAIN(_segue);
return true;
}
MWViewController::MWViewController()
: _scene(nullptr)
, _view(nullptr)
, _segue(nullptr)
, _identifer()
{
}
MWViewController::~MWViewController()
{
CC_SAFE_RELEASE(_view);
CC_SAFE_RELEASE(_segue);
}
void MWViewController::viewDidLoad()
{
if (!_view) {
_view = MWGameView::create();
_view->retain();
}
#if MW_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeLua) {
MWLuaUtils::getInstance()->executePeertableFunction(this, "viewDidLoad", nullptr, nullptr, false);
} else if (_scriptType == kScriptTypeJavascript) {
// js todo
}
#endif
}
void MWViewController::viewDidUnload()
{
#if MW_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeLua) {
MWLuaUtils::getInstance()->executePeertableFunction(this, "viewDidUnload", nullptr, nullptr, false);
} else if (_scriptType == kScriptTypeJavascript) {
// js todo
}
#endif
if (_view && _view->getParent()) {
_view->removeFromParent();
}
}
void MWViewController::didReceiveMemoryWarning()
{
#if MW_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeLua) {
MWLuaUtils::getInstance()->executePeertableFunction(this, "didReceiveMemoryWarning", nullptr, nullptr, false);
} else if (_scriptType == kScriptTypeJavascript) {
// js todo
}
#endif
}
MW_FRAMEWORK_END
<|endoftext|>
|
<commit_before>#pragma once
#include "DxLib.h"
#include <string>
#include "IState.hpp"
using namespace std;
class Core
{
public: static Core &GetInstance(void) { static Core instance; return instance; }
private: Core(void)
{
}
private:
vector<IState*> StateList;
string NowStateName;
public:
// 場面を追加します
void AddState(IState* state)
{
StateList.push_back(state);
}
// 現在の場面名を設定します
void SetNowStateName(string nowStateName)
{
NowStateName = nowStateName;
}
// 現在の場面名を取得します
string GetNowStateName()
{
return NowStateName;
}
// 対象場面のUpdateメソッドを呼び出します
void UpdateTriger()
{
for (auto state : StateList)
if (state->StateName() == NowStateName)
{
state->Update();
return;
}
throw new exception("場面が見つかりませんでした。");
}
// 全ての場面のDrawメソッドを呼び出します
void DrawTriger()
{
for (auto state : StateList)
state->Draw();
}
// インスタンスを初期化します
bool Initialize(string title, int sizeX, int sizeY, int backR, int backG, int backB)
{
if (SetMainWindowText((title + string(" - Initializing...")).c_str()) != 0)
return false;
if (SetGraphMode(sizeX, sizeY, 32) != DX_CHANGESCREEN_OK)
return false;
if (SetBackgroundColor(backR, backG, backB) != 0)
return false;
if (ChangeWindowMode(true) != DX_CHANGESCREEN_OK)
return false;
if (DxLib_Init() != 0)
return false;
if (SetDrawScreen(DX_SCREEN_BACK) != 0)
return false;
if (SetMainWindowText(title.c_str()) != 0)
return false;
return true;
}
// 毎フレーム呼び出す必要がある基本処理を呼び出します
bool ProcessContext()
{
if (ScreenFlip() != 0)
return false;
if (ProcessMessage() != 0)
return false;
if (ClearDrawScreen() != 0)
return false;
return true;
}
// インスタンスを破棄します
bool Finalize()
{
DxLib_End();
return true;
}
};<commit_msg>Fix code format<commit_after>#pragma once
#include "DxLib.h"
#include <string>
#include "IState.hpp"
using namespace std;
class Core
{
public: static Core &GetInstance(void) { static Core instance; return instance; }
private: Core(void) { }
private:
vector<IState*> StateList;
string NowStateName;
public:
// 場面を追加します
void AddState(IState* state)
{
StateList.push_back(state);
}
// 現在の場面名を設定します
void SetNowStateName(string nowStateName)
{
NowStateName = nowStateName;
}
// 現在の場面名を取得します
string GetNowStateName()
{
return NowStateName;
}
// 対象場面のUpdateメソッドを呼び出します
void UpdateTriger()
{
for (auto state : StateList)
if (state->StateName() == NowStateName)
{
state->Update();
return;
}
throw new exception("場面が見つかりませんでした。");
}
// 全ての場面のDrawメソッドを呼び出します
void DrawTriger()
{
for (auto state : StateList)
state->Draw();
}
// インスタンスを初期化します
bool Initialize(string title, int sizeX, int sizeY, int backR, int backG, int backB)
{
if (SetMainWindowText((title + string(" - Initializing...")).c_str()) != 0)
return false;
if (SetGraphMode(sizeX, sizeY, 32) != DX_CHANGESCREEN_OK)
return false;
if (SetBackgroundColor(backR, backG, backB) != 0)
return false;
if (ChangeWindowMode(true) != DX_CHANGESCREEN_OK)
return false;
if (DxLib_Init() != 0)
return false;
if (SetDrawScreen(DX_SCREEN_BACK) != 0)
return false;
if (SetMainWindowText(title.c_str()) != 0)
return false;
return true;
}
// 毎フレーム呼び出す必要がある基本処理を呼び出します
bool ProcessContext()
{
if (ScreenFlip() != 0)
return false;
if (ProcessMessage() != 0)
return false;
if (ClearDrawScreen() != 0)
return false;
return true;
}
// インスタンスを破棄します
bool Finalize()
{
DxLib_End();
return true;
}
};<|endoftext|>
|
<commit_before>/*
c2ffi
Copyright (C) 2013 Ryan Pavlik
This file is part of c2ffi.
c2ffi 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.
c2ffi 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 c2ffi. If not, see <http://www.gnu.org/licenses/>.
*/
#include <clang/AST/DeclObjC.h>
#include <clang/AST/ASTContext.h>
#include "c2ffi.h"
#include "c2ffi/ast.h"
using namespace c2ffi;
Decl::Decl(clang::NamedDecl *d) {
_name = d->getDeclName().getAsString();
}
void Decl::set_location(clang::CompilerInstance &ci, const clang::Decl *d) {
clang::SourceLocation sloc = d->getLocation();
if(sloc.isValid()) {
std::string loc = sloc.printToString(ci.getSourceManager());
set_location(loc);
}
}
FieldsMixin::~FieldsMixin() {
for(NameTypeVector::iterator i = _v.begin(); i != _v.end(); i++)
delete (*i).second;
}
FunctionsMixin::~FunctionsMixin() {
for(FunctionVector::iterator i = _v.begin(); i != _v.end(); i++)
delete (*i);
}
void FieldsMixin::add_field(Name name, Type *t) {
_v.push_back(NameTypePair(name, t));
}
void FieldsMixin::add_field(C2FFIASTConsumer *ast, clang::FieldDecl *f) {
clang::ASTContext &ctx = ast->ci().getASTContext();
std::pair<uint64_t, unsigned> type_info =
ctx.getTypeInfo(f->getTypeSourceInfo()->getType().getTypePtr());
Type *t = NULL;
if(f->isBitField())
t = new BitfieldType(ast->ci(), f->getTypeSourceInfo()->getType().getTypePtr(),
f->getBitWidthValue(ctx), t);
else
t = Type::make_type(ast, f->getTypeSourceInfo()->getType().getTypePtr());
t->set_bit_offset(ctx.getFieldOffset(f));
t->set_bit_size(type_info.first);
t->set_bit_alignment(type_info.second);
add_field(f->getDeclName().getAsString(), t);
}
void FieldsMixin::add_field(C2FFIASTConsumer *ast, clang::ParmVarDecl *p) {
std::string name = p->getDeclName().getAsString();
Type *t = Type::make_type(ast, p->getOriginalType().getTypePtr());
add_field(name, t);
}
void FunctionsMixin::add_function(FunctionDecl *f) {
_v.push_back(f);
}
void FunctionsMixin::add_functions(C2FFIASTConsumer *ast, const clang::ObjCContainerDecl *d) {
for(clang::ObjCContainerDecl::method_iterator m = d->meth_begin();
m != d->meth_end(); m++) {
const clang::Type *return_type = m->getResultType().getTypePtr();
FunctionDecl *fd = new FunctionDecl(m->getDeclName().getAsString(),
Type::make_type(ast, return_type),
m->isVariadic());
fd->set_is_objc_method(true);
fd->set_is_class_method(m->isClassMethod());
fd->set_location(ast->ci(), (*m));
for(clang::FunctionDecl::param_const_iterator i = m->param_begin();
i != m->param_end(); i++) {
fd->add_field(ast, *i);
}
add_function(fd);
}
}
void EnumDecl::add_field(Name name, uint64_t v) {
_v.push_back(NameNumPair(name, v));
}
void ObjCInterfaceDecl::add_protocol(Name name) {
_protocols.push_back(name);
}
<commit_msg>Un-fix 'fix'<commit_after>/*
c2ffi
Copyright (C) 2013 Ryan Pavlik
This file is part of c2ffi.
c2ffi 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.
c2ffi 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 c2ffi. If not, see <http://www.gnu.org/licenses/>.
*/
#include <clang/AST/DeclObjC.h>
#include <clang/AST/ASTContext.h>
#include "c2ffi.h"
#include "c2ffi/ast.h"
using namespace c2ffi;
Decl::Decl(clang::NamedDecl *d) {
_name = d->getDeclName().getAsString();
}
void Decl::set_location(clang::CompilerInstance &ci, const clang::Decl *d) {
clang::SourceLocation sloc = d->getLocation();
if(sloc.isValid()) {
std::string loc = sloc.printToString(ci.getSourceManager());
set_location(loc);
}
}
FieldsMixin::~FieldsMixin() {
for(NameTypeVector::iterator i = _v.begin(); i != _v.end(); i++)
delete (*i).second;
}
FunctionsMixin::~FunctionsMixin() {
for(FunctionVector::iterator i = _v.begin(); i != _v.end(); i++)
delete (*i);
}
void FieldsMixin::add_field(Name name, Type *t) {
_v.push_back(NameTypePair(name, t));
}
void FieldsMixin::add_field(C2FFIASTConsumer *ast, clang::FieldDecl *f) {
clang::ASTContext &ctx = ast->ci().getASTContext();
std::pair<uint64_t, unsigned> type_info =
ctx.getTypeInfo(f->getTypeSourceInfo()->getType().getTypePtr());
Type *t = t = Type::make_type(ast, f->getTypeSourceInfo()->getType().getTypePtr());;
if(f->isBitField())
t = new BitfieldType(ast->ci(), f->getTypeSourceInfo()->getType().getTypePtr(),
f->getBitWidthValue(ctx), t);
t->set_bit_offset(ctx.getFieldOffset(f));
t->set_bit_size(type_info.first);
t->set_bit_alignment(type_info.second);
add_field(f->getDeclName().getAsString(), t);
}
void FieldsMixin::add_field(C2FFIASTConsumer *ast, clang::ParmVarDecl *p) {
std::string name = p->getDeclName().getAsString();
Type *t = Type::make_type(ast, p->getOriginalType().getTypePtr());
add_field(name, t);
}
void FunctionsMixin::add_function(FunctionDecl *f) {
_v.push_back(f);
}
void FunctionsMixin::add_functions(C2FFIASTConsumer *ast, const clang::ObjCContainerDecl *d) {
for(clang::ObjCContainerDecl::method_iterator m = d->meth_begin();
m != d->meth_end(); m++) {
const clang::Type *return_type = m->getResultType().getTypePtr();
FunctionDecl *fd = new FunctionDecl(m->getDeclName().getAsString(),
Type::make_type(ast, return_type),
m->isVariadic());
fd->set_is_objc_method(true);
fd->set_is_class_method(m->isClassMethod());
fd->set_location(ast->ci(), (*m));
for(clang::FunctionDecl::param_const_iterator i = m->param_begin();
i != m->param_end(); i++) {
fd->add_field(ast, *i);
}
add_function(fd);
}
}
void EnumDecl::add_field(Name name, uint64_t v) {
_v.push_back(NameNumPair(name, v));
}
void ObjCInterfaceDecl::add_protocol(Name name) {
_protocols.push_back(name);
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file CollisionPrevention.hpp
* @author Tanja Baumann <tanja@auterion.com>
*
* CollisionPrevention controller.
*
*/
#pragma once
#include <px4_module_params.h>
#include <float.h>
#include <matrix/matrix/math.hpp>
#include <uORB/topics/obstacle_distance.h>
#include <uORB/topics/collision_constraints.h>
#include <mathlib/mathlib.h>
#include <drivers/drv_hrt.h>
#include <uORB/topics/mavlink_log.h>
#include <uORB/uORB.h>
#include <systemlib/mavlink_log.h>
#include <lib/FlightTasks/tasks/FlightTask/SubscriptionArray.hpp>
class CollisionPrevention : public ModuleParams
{
public:
CollisionPrevention(ModuleParams *parent);
~CollisionPrevention();
/**
* Initialize the uORB subscriptions using an array
* @return true on success, false on error
*/
bool initializeSubscriptions(SubscriptionArray &subscription_array);
bool is_active() { return MPC_COL_PREV_D.get() > 0; }
void modifySetpoint(matrix::Vector2f &original_setpoint, const float max_speed);
private:
bool _interfering = false; /**< states if the collision prevention interferes with the user input */
orb_advert_t _constraints_pub{nullptr}; /**< constraints publication */
orb_advert_t _mavlink_log_pub = nullptr; /**< Mavlink log uORB handle */
uORB::Subscription<obstacle_distance_s> *_sub_obstacle_distance{nullptr}; /**< obstacle distances received form a range sensor */
static constexpr uint64_t RANGE_STREAM_TIMEOUT_US = 500000;
static constexpr uint64_t MESSAGE_THROTTLE_US = 5000000;
hrt_abstime _last_message;
matrix::Vector2f _move_constraints_x_normalized;
matrix::Vector2f _move_constraints_y_normalized;
matrix::Vector2f _move_constraints_x;
matrix::Vector2f _move_constraints_y;
DEFINE_PARAMETERS(
(ParamFloat<px4::params::MPC_COL_PREV_D>) MPC_COL_PREV_D /**< collision prevention keep minimum distance */
)
void update();
void update_range_constraints();
void reset_constraints();
void publish_constraints(const matrix::Vector2f &original_setpoint, const matrix::Vector2f &adapted_setpoint);
};
<commit_msg>CollisionPrevention: consistent var init<commit_after>/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file CollisionPrevention.hpp
* @author Tanja Baumann <tanja@auterion.com>
*
* CollisionPrevention controller.
*
*/
#pragma once
#include <px4_module_params.h>
#include <float.h>
#include <matrix/matrix/math.hpp>
#include <uORB/topics/obstacle_distance.h>
#include <uORB/topics/collision_constraints.h>
#include <mathlib/mathlib.h>
#include <drivers/drv_hrt.h>
#include <uORB/topics/mavlink_log.h>
#include <uORB/uORB.h>
#include <systemlib/mavlink_log.h>
#include <lib/FlightTasks/tasks/FlightTask/SubscriptionArray.hpp>
class CollisionPrevention : public ModuleParams
{
public:
CollisionPrevention(ModuleParams *parent);
~CollisionPrevention();
/**
* Initialize the uORB subscriptions using an array
* @return true on success, false on error
*/
bool initializeSubscriptions(SubscriptionArray &subscription_array);
bool is_active() { return MPC_COL_PREV_D.get() > 0; }
void modifySetpoint(matrix::Vector2f &original_setpoint, const float max_speed);
private:
bool _interfering = false; /**< states if the collision prevention interferes with the user input */
orb_advert_t _constraints_pub = nullptr; /**< constraints publication */
orb_advert_t _mavlink_log_pub = nullptr; /**< Mavlink log uORB handle */
uORB::Subscription<obstacle_distance_s> *_sub_obstacle_distance = nullptr; /**< obstacle distances received form a range sensor */
static constexpr uint64_t RANGE_STREAM_TIMEOUT_US = 500000;
static constexpr uint64_t MESSAGE_THROTTLE_US = 5000000;
hrt_abstime _last_message;
matrix::Vector2f _move_constraints_x_normalized;
matrix::Vector2f _move_constraints_y_normalized;
matrix::Vector2f _move_constraints_x;
matrix::Vector2f _move_constraints_y;
DEFINE_PARAMETERS(
(ParamFloat<px4::params::MPC_COL_PREV_D>) MPC_COL_PREV_D /**< collision prevention keep minimum distance */
)
void update();
void update_range_constraints();
void reset_constraints();
void publish_constraints(const matrix::Vector2f &original_setpoint, const matrix::Vector2f &adapted_setpoint);
};
<|endoftext|>
|
<commit_before>//
// This script converts the MNIST dataset to the leveldb format used
// by caffe to train siamese network.
// Usage:
// convert_mnist_data input_image_file input_label_file output_db_file
// The MNIST dataset could be downloaded at
// http://yann.lecun.com/exdb/mnist/
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include "glog/logging.h"
#include "google/protobuf/text_format.h"
#include "leveldb/db.h"
#include "stdint.h"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/math_functions.hpp"
uint32_t swap_endian(uint32_t val) {
val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF);
return (val << 16) | (val >> 16);
}
void read_image(std::ifstream* image_file, std::ifstream* label_file,
uint32_t index, uint32_t rows, uint32_t cols,
char* pixels, char* label) {
image_file->seekg(index * rows * cols + 16);
image_file->read(pixels, rows * cols);
label_file->seekg(index + 8);
label_file->read(label, 1);
}
void convert_dataset(const char* image_filename, const char* label_filename,
const char* db_filename) {
// Open files
std::ifstream image_file(image_filename, std::ios::in | std::ios::binary);
std::ifstream label_file(label_filename, std::ios::in | std::ios::binary);
CHECK(image_file) << "Unable to open file " << image_filename;
CHECK(label_file) << "Unable to open file " << label_file;
// Read the magic and the meta data
uint32_t magic;
uint32_t num_items;
uint32_t num_labels;
uint32_t rows;
uint32_t cols;
image_file.read(reinterpret_cast<char*>(&magic), 4);
magic = swap_endian(magic);
CHECK_EQ(magic, 2051) << "Incorrect image file magic.";
label_file.read(reinterpret_cast<char*>(&magic), 4);
magic = swap_endian(magic);
CHECK_EQ(magic, 2049) << "Incorrect label file magic.";
image_file.read(reinterpret_cast<char*>(&num_items), 4);
num_items = swap_endian(num_items);
label_file.read(reinterpret_cast<char*>(&num_labels), 4);
num_labels = swap_endian(num_labels);
CHECK_EQ(num_items, num_labels);
image_file.read(reinterpret_cast<char*>(&rows), 4);
rows = swap_endian(rows);
image_file.read(reinterpret_cast<char*>(&cols), 4);
cols = swap_endian(cols);
// Open leveldb
leveldb::DB* db;
leveldb::Options options;
options.create_if_missing = true;
options.error_if_exists = true;
leveldb::Status status = leveldb::DB::Open(
options, db_filename, &db);
CHECK(status.ok()) << "Failed to open leveldb " << db_filename
<< ". Is it already existing?";
char label_i;
char label_j;
char* pixels = new char[2 * rows * cols];
const int kMaxKeyLength = 10;
char key[kMaxKeyLength];
std::string value;
caffe::Datum datum;
datum.set_channels(2); // one channel for each image in the pair
datum.set_height(rows);
datum.set_width(cols);
LOG(INFO) << "A total of " << num_items << " items.";
LOG(INFO) << "Rows: " << rows << " Cols: " << cols;
for (int itemid = 0; itemid < num_items; ++itemid) {
int i = caffe::caffe_rng_rand() % num_items; // pick a random pair
int j = caffe::caffe_rng_rand() % num_items;
read_image(&image_file, &label_file, i, rows, cols,
pixels, &label_i);
read_image(&image_file, &label_file, j, rows, cols,
pixels + (rows * cols), &label_j);
datum.set_data(pixels, 2*rows*cols);
if (label_i == label_j) {
datum.set_label(1);
} else {
datum.set_label(0);
}
datum.SerializeToString(&value);
snprintf(key, kMaxKeyLength, "%08d", itemid);
db->Put(leveldb::WriteOptions(), std::string(key), value);
}
delete db;
delete pixels;
}
int main(int argc, char** argv) {
if (argc != 4) {
printf("This script converts the MNIST dataset to the leveldb format used\n"
"by caffe to train a siamese network.\n"
"Usage:\n"
" convert_mnist_data input_image_file input_label_file "
"output_db_file\n"
"The MNIST dataset could be downloaded at\n"
" http://yann.lecun.com/exdb/mnist/\n"
"You should gunzip them after downloading.\n");
} else {
google::InitGoogleLogging(argv[0]);
convert_dataset(argv[1], argv[2], argv[3]);
}
return 0;
}
<commit_msg>fixed small bug: output label_file -> label_filename<commit_after>//
// This script converts the MNIST dataset to the leveldb format used
// by caffe to train siamese network.
// Usage:
// convert_mnist_data input_image_file input_label_file output_db_file
// The MNIST dataset could be downloaded at
// http://yann.lecun.com/exdb/mnist/
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include "glog/logging.h"
#include "google/protobuf/text_format.h"
#include "leveldb/db.h"
#include "stdint.h"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/math_functions.hpp"
uint32_t swap_endian(uint32_t val) {
val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF);
return (val << 16) | (val >> 16);
}
void read_image(std::ifstream* image_file, std::ifstream* label_file,
uint32_t index, uint32_t rows, uint32_t cols,
char* pixels, char* label) {
image_file->seekg(index * rows * cols + 16);
image_file->read(pixels, rows * cols);
label_file->seekg(index + 8);
label_file->read(label, 1);
}
void convert_dataset(const char* image_filename, const char* label_filename,
const char* db_filename) {
// Open files
std::ifstream image_file(image_filename, std::ios::in | std::ios::binary);
std::ifstream label_file(label_filename, std::ios::in | std::ios::binary);
CHECK(image_file) << "Unable to open file " << image_filename;
CHECK(label_file) << "Unable to open file " << label_filename;
// Read the magic and the meta data
uint32_t magic;
uint32_t num_items;
uint32_t num_labels;
uint32_t rows;
uint32_t cols;
image_file.read(reinterpret_cast<char*>(&magic), 4);
magic = swap_endian(magic);
CHECK_EQ(magic, 2051) << "Incorrect image file magic.";
label_file.read(reinterpret_cast<char*>(&magic), 4);
magic = swap_endian(magic);
CHECK_EQ(magic, 2049) << "Incorrect label file magic.";
image_file.read(reinterpret_cast<char*>(&num_items), 4);
num_items = swap_endian(num_items);
label_file.read(reinterpret_cast<char*>(&num_labels), 4);
num_labels = swap_endian(num_labels);
CHECK_EQ(num_items, num_labels);
image_file.read(reinterpret_cast<char*>(&rows), 4);
rows = swap_endian(rows);
image_file.read(reinterpret_cast<char*>(&cols), 4);
cols = swap_endian(cols);
// Open leveldb
leveldb::DB* db;
leveldb::Options options;
options.create_if_missing = true;
options.error_if_exists = true;
leveldb::Status status = leveldb::DB::Open(
options, db_filename, &db);
CHECK(status.ok()) << "Failed to open leveldb " << db_filename
<< ". Is it already existing?";
char label_i;
char label_j;
char* pixels = new char[2 * rows * cols];
const int kMaxKeyLength = 10;
char key[kMaxKeyLength];
std::string value;
caffe::Datum datum;
datum.set_channels(2); // one channel for each image in the pair
datum.set_height(rows);
datum.set_width(cols);
LOG(INFO) << "A total of " << num_items << " items.";
LOG(INFO) << "Rows: " << rows << " Cols: " << cols;
for (int itemid = 0; itemid < num_items; ++itemid) {
int i = caffe::caffe_rng_rand() % num_items; // pick a random pair
int j = caffe::caffe_rng_rand() % num_items;
read_image(&image_file, &label_file, i, rows, cols,
pixels, &label_i);
read_image(&image_file, &label_file, j, rows, cols,
pixels + (rows * cols), &label_j);
datum.set_data(pixels, 2*rows*cols);
if (label_i == label_j) {
datum.set_label(1);
} else {
datum.set_label(0);
}
datum.SerializeToString(&value);
snprintf(key, kMaxKeyLength, "%08d", itemid);
db->Put(leveldb::WriteOptions(), std::string(key), value);
}
delete db;
delete pixels;
}
int main(int argc, char** argv) {
if (argc != 4) {
printf("This script converts the MNIST dataset to the leveldb format used\n"
"by caffe to train a siamese network.\n"
"Usage:\n"
" convert_mnist_data input_image_file input_label_file "
"output_db_file\n"
"The MNIST dataset could be downloaded at\n"
" http://yann.lecun.com/exdb/mnist/\n"
"You should gunzip them after downloading.\n");
} else {
google::InitGoogleLogging(argv[0]);
convert_dataset(argv[1], argv[2], argv[3]);
}
return 0;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "inputartifactscanner.h"
#include "artifact.h"
#include "buildgraph.h"
#include "productbuilddata.h"
#include "projectbuilddata.h"
#include "transformer.h"
#include "depscanner.h"
#include "rulesevaluationcontext.h"
#include <language/language.h>
#include <tools/fileinfo.h>
#include <tools/scannerpluginmanager.h>
#include <tools/qbsassert.h>
#include <tools/error.h>
#include <QDir>
#include <QSet>
#include <QStringList>
#include <QVariantMap>
namespace qbs {
namespace Internal {
InputArtifactScannerContext::InputArtifactScannerContext(ScanResultCache *scanResultCache)
: scanResultCache(scanResultCache)
{
}
InputArtifactScannerContext::~InputArtifactScannerContext()
{
}
static void resolveWithIncludePath(const QString &includePath,
const ScanResultCache::Dependency &dependency, const ResolvedProduct *product,
ResolvedDependency *result)
{
QString absDirPath = dependency.dirPath().isEmpty() ? includePath : FileInfo::resolvePath(includePath, dependency.dirPath());
if (!dependency.isClean())
absDirPath = QDir::cleanPath(absDirPath);
ResolvedProject *project = product->project.data();
FileDependency *fileDependencyArtifact = 0;
Artifact *dependencyInProduct = 0;
Artifact *dependencyInOtherProduct = 0;
foreach (FileResourceBase *lookupResult, project->topLevelProject()
->buildData->lookupFiles(absDirPath, dependency.fileName())) {
if ((fileDependencyArtifact = dynamic_cast<FileDependency *>(lookupResult)))
continue;
Artifact * const foundArtifact = dynamic_cast<Artifact *>(lookupResult);
if (foundArtifact->product == product)
dependencyInProduct = foundArtifact;
else
dependencyInOtherProduct = foundArtifact;
}
// prioritize found artifacts
if ((result->file = dependencyInProduct)
|| (result->file = dependencyInOtherProduct)
|| (result->file = fileDependencyArtifact))
{
result->filePath = result->file->filePath();
return;
}
QString absFilePath = absDirPath + QLatin1Char('/') + dependency.fileName();
// TODO: We probably need a flag that tells us whether directories are allowed.
const FileInfo fi(absFilePath);
if (fi.exists(absFilePath) && !fi.isDir())
result->filePath = absFilePath;
}
static void resolveAbsolutePath(const ScanResultCache::Dependency &dependency,
const ResolvedProduct *product, ResolvedDependency *result)
{
QString absDirPath = dependency.dirPath();
if (!dependency.isClean())
absDirPath = QDir::cleanPath(absDirPath);
ResolvedProject *project = product->project.data();
FileDependency *fileDependencyArtifact = 0;
Artifact *dependencyInProduct = 0;
Artifact *dependencyInOtherProduct = 0;
foreach (FileResourceBase *lookupResult, project->topLevelProject()
->buildData->lookupFiles(absDirPath, dependency.fileName())) {
if ((fileDependencyArtifact = dynamic_cast<FileDependency *>(lookupResult)))
continue;
Artifact * const foundArtifact = dynamic_cast<Artifact *>(lookupResult);
if (foundArtifact->product == product)
dependencyInProduct = foundArtifact;
else
dependencyInOtherProduct = foundArtifact;
}
// prioritize found artifacts
if ((result->file = dependencyInProduct)
|| (result->file = dependencyInOtherProduct)
|| (result->file = fileDependencyArtifact)) {
result->filePath = result->file->filePath();
return;
}
if (FileInfo::exists(dependency.filePath()))
result->filePath = dependency.filePath();
}
static void scanWithScannerPlugin(DependencyScanner *scanner,
FileResourceBase *fileToBeScanned,
ScanResultCache::Result *scanResult)
{
QStringList dependencies = scanner->collectDependencies(fileToBeScanned);
foreach (const QString &s, dependencies)
scanResult->deps += ScanResultCache::Dependency(s);
scanResult->valid = true;
}
InputArtifactScanner::InputArtifactScanner(Artifact *artifact, InputArtifactScannerContext *ctx,
const Logger &logger)
: m_artifact(artifact), m_context(ctx), m_newDependencyAdded(false), m_logger(logger)
{
}
void InputArtifactScanner::scan()
{
if (m_artifact->inputsScanned)
return;
if (m_logger.traceEnabled()) {
m_logger.qbsTrace()
<< QString::fromLatin1("[DEPSCAN] inputs for %1 [%2] in product '%3'")
.arg(m_artifact->filePath(),
m_artifact->fileTags().toStringList().join(QLatin1String(", ")),
m_artifact->product->name);
}
m_artifact->inputsScanned = true;
// clear file dependencies; they will be regenerated
m_artifact->fileDependencies.clear();
// Remove all connections to children that were added by the dependency scanner.
// They will be regenerated.
foreach (Artifact *dependency, m_artifact->childrenAddedByScanner)
disconnect(m_artifact, dependency, m_logger);
ArtifactSet::const_iterator it = m_artifact->transformer->inputs.begin();
for (; it != m_artifact->transformer->inputs.end(); ++it) {
Artifact *inputArtifact = *it;
scanForFileDependencies(inputArtifact);
}
}
void InputArtifactScanner::scanForFileDependencies(Artifact *inputArtifact)
{
if (m_logger.traceEnabled()) {
m_logger.qbsTrace()
<< QString::fromLatin1("[DEPSCAN] input artifact %1 [%2]")
.arg(inputArtifact->filePath(),
inputArtifact->fileTags().toStringList().join(QLatin1String(", ")));
}
InputArtifactScannerContext::CacheItem &cacheItem = m_context->cache[inputArtifact->properties];
QSet<QString> visitedFilePaths;
QList<FileResourceBase *> filesToScan;
filesToScan.append(inputArtifact);
const QSet<DependencyScanner *> scanners = scannersForArtifact(inputArtifact);
while (!filesToScan.isEmpty()) {
FileResourceBase *fileToBeScanned = filesToScan.takeFirst();
const QString &filePathToBeScanned = fileToBeScanned->filePath();
if (visitedFilePaths.contains(filePathToBeScanned))
continue;
visitedFilePaths.insert(filePathToBeScanned);
foreach (DependencyScanner *scanner, scanners) {
scanForScannerFileDependencies(scanner, inputArtifact, fileToBeScanned,
scanner->recursive() ? &filesToScan : 0, cacheItem[scanner->key()]);
}
}
}
QSet<DependencyScanner *> InputArtifactScanner::scannersForArtifact(const Artifact *artifact) const
{
QSet<DependencyScanner *> scanners;
ResolvedProduct *product = artifact->product.data();
QHash<FileTag, InputArtifactScannerContext::DependencyScannerCacheItem> &scannerCache
= m_context->scannersCache[product];
foreach (const FileTag &fileTag, artifact->fileTags()) {
InputArtifactScannerContext::DependencyScannerCacheItem &cache = scannerCache[fileTag];
if (!cache.valid) {
cache.valid = true;
foreach (ScannerPlugin *scanner, ScannerPluginManager::scannersForFileTag(fileTag)) {
PluginDependencyScanner *pluginScanner = new PluginDependencyScanner(scanner);
cache.scanners += DependencyScannerPtr(pluginScanner);
}
foreach (const ResolvedScannerConstPtr &scanner, product->scanners) {
if (scanner->inputs.contains(fileTag)) {
cache.scanners += DependencyScannerPtr(
new UserDependencyScanner(scanner, m_logger));
break;
}
}
}
foreach (const DependencyScannerPtr &scanner, cache.scanners) {
scanners += scanner.data();
}
}
return scanners;
}
void InputArtifactScanner::scanForScannerFileDependencies(DependencyScanner *scanner,
Artifact *inputArtifact, FileResourceBase *fileToBeScanned,
QList<FileResourceBase *> *filesToScan,
InputArtifactScannerContext::ScannerResolvedDependenciesCache &cache)
{
if (m_logger.traceEnabled()) {
m_logger.qbsTrace() << QString::fromLatin1("[DEPSCAN] file %1")
.arg(fileToBeScanned->filePath());
}
const bool cacheHit = cache.valid;
if (!cacheHit) {
cache.valid = true;
cache.searchPaths = scanner->collectSearchPaths(inputArtifact);
}
if (m_logger.traceEnabled()) {
m_logger.qbsTrace()
<< "[DEPSCAN] include paths (cache " << (cacheHit ? "hit)" : "miss)");
foreach (const QString &s, cache.searchPaths)
m_logger.qbsTrace() << " " << s;
}
const QString &filePathToBeScanned = fileToBeScanned->filePath();
ScanResultCache::Result scanResult = m_context->scanResultCache->value(scanner->key(), filePathToBeScanned);
if (!scanResult.valid) {
try {
if (m_logger.traceEnabled())
m_logger.qbsTrace() << "scanning " << FileInfo::fileName(filePathToBeScanned);
scanWithScannerPlugin(scanner, fileToBeScanned, &scanResult);
} catch (const ErrorInfo &error) {
m_logger.printWarning(error);
return;
}
m_context->scanResultCache->insert(scanner->key(), filePathToBeScanned, scanResult);
}
resolveScanResultDependencies(inputArtifact, scanResult, filesToScan, cache);
}
void InputArtifactScanner::resolveScanResultDependencies(const Artifact *inputArtifact,
const ScanResultCache::Result &scanResult, QList<FileResourceBase *> *artifactsToScan,
InputArtifactScannerContext::ScannerResolvedDependenciesCache &cache)
{
foreach (const ScanResultCache::Dependency &dependency, scanResult.deps) {
const QString &dependencyFilePath = dependency.filePath();
InputArtifactScannerContext::ResolvedDependencyCacheItem &cachedResolvedDependencyItem
= cache.resolvedDependenciesCache[dependency.dirPath()][dependency.fileName()];
ResolvedDependency &resolvedDependency = cachedResolvedDependencyItem.resolvedDependency;
if (cachedResolvedDependencyItem.valid) {
if (resolvedDependency.filePath.isEmpty())
goto unresolved;
goto resolved;
}
cachedResolvedDependencyItem.valid = true;
if (FileInfo::isAbsolute(dependencyFilePath)) {
resolveAbsolutePath(dependency, inputArtifact->product.data(),
&resolvedDependency);
goto resolved;
}
// try include paths
foreach (const QString &includePath, cache.searchPaths) {
resolveWithIncludePath(includePath, dependency, inputArtifact->product.data(),
&resolvedDependency);
if (resolvedDependency.isValid())
goto resolved;
}
unresolved:
if (m_logger.traceEnabled())
m_logger.qbsWarning() << "[DEPSCAN] unresolved dependency " << dependencyFilePath;
continue;
resolved:
handleDependency(resolvedDependency);
if (artifactsToScan && resolvedDependency.file) {
if (Artifact *artifactDependency = dynamic_cast<Artifact *>(resolvedDependency.file)) {
// Do not scan artifacts that are being built. Otherwise we might read an incomplete
// file or conflict with the writing process.
if (artifactDependency->buildState != BuildGraphNode::Building)
artifactsToScan->append(artifactDependency);
} else {
// Add file dependency to the next round of scanning.
artifactsToScan->append(resolvedDependency.file);
}
}
}
}
void InputArtifactScanner::handleDependency(ResolvedDependency &dependency)
{
const ResolvedProductPtr product = m_artifact->product;
bool insertIntoProduct = true;
QBS_CHECK(m_artifact->artifactType == Artifact::Generated);
QBS_CHECK(product);
Artifact *artifactDependency = dynamic_cast<Artifact *>(dependency.file);
FileDependency *fileDependency
= artifactDependency ? 0 : dynamic_cast<FileDependency *>(dependency.file);
QBS_CHECK(!dependency.file || artifactDependency || fileDependency);
if (!dependency.file) {
// The dependency is an existing file but does not exist in the build graph.
if (m_logger.traceEnabled())
m_logger.qbsTrace() << "[DEPSCAN] add new file dependency " << dependency.filePath;
fileDependency = new FileDependency();
dependency.file = fileDependency;
fileDependency->setFilePath(dependency.filePath);
product->topLevelProject()->buildData->insertFileDependency(fileDependency);
} else if (fileDependency) {
// The dependency exists in the project's list of file dependencies.
if (m_logger.traceEnabled()) {
m_logger.qbsTrace() << "[DEPSCAN] add existing file dependency "
<< dependency.filePath;
}
} else if (artifactDependency->product == product) {
// The dependency is in our product.
if (m_logger.traceEnabled()) {
m_logger.qbsTrace() << "[DEPSCAN] add artifact dependency " << dependency.filePath
<< " (from this product)";
}
insertIntoProduct = false;
} else {
// The dependency is in some other product.
ResolvedProduct * const otherProduct = artifactDependency->product;
if (m_logger.traceEnabled()) {
m_logger.qbsTrace() << "[DEPSCAN] add artifact dependency " << dependency.filePath
<< " (from product " << otherProduct->uniqueName() << ')';
}
insertIntoProduct = false;
}
if (m_artifact == dependency.file)
return;
if (fileDependency) {
if (!m_artifact->fileDependencies.contains(fileDependency))
m_artifact->fileDependencies << fileDependency;
} else {
if (m_artifact->children.contains(artifactDependency))
return;
if (insertIntoProduct && !product->buildData->nodes.contains(artifactDependency))
insertArtifact(product, artifactDependency, m_logger);
safeConnect(m_artifact, artifactDependency, m_logger);
m_artifact->childrenAddedByScanner += artifactDependency;
m_newDependencyAdded = true;
}
}
InputArtifactScannerContext::DependencyScannerCacheItem::DependencyScannerCacheItem() : valid(false)
{
}
InputArtifactScannerContext::DependencyScannerCacheItem::~DependencyScannerCacheItem()
{
}
} // namespace Internal
} // namespace qbs
<commit_msg>InputArtifactScanner: Remove dead code<commit_after>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "inputartifactscanner.h"
#include "artifact.h"
#include "buildgraph.h"
#include "productbuilddata.h"
#include "projectbuilddata.h"
#include "transformer.h"
#include "depscanner.h"
#include "rulesevaluationcontext.h"
#include <language/language.h>
#include <tools/fileinfo.h>
#include <tools/scannerpluginmanager.h>
#include <tools/qbsassert.h>
#include <tools/error.h>
#include <QDir>
#include <QSet>
#include <QStringList>
#include <QVariantMap>
namespace qbs {
namespace Internal {
InputArtifactScannerContext::InputArtifactScannerContext(ScanResultCache *scanResultCache)
: scanResultCache(scanResultCache)
{
}
InputArtifactScannerContext::~InputArtifactScannerContext()
{
}
static void resolveWithIncludePath(const QString &includePath,
const ScanResultCache::Dependency &dependency, const ResolvedProduct *product,
ResolvedDependency *result)
{
QString absDirPath = dependency.dirPath().isEmpty() ? includePath : FileInfo::resolvePath(includePath, dependency.dirPath());
if (!dependency.isClean())
absDirPath = QDir::cleanPath(absDirPath);
ResolvedProject *project = product->project.data();
FileDependency *fileDependencyArtifact = 0;
Artifact *dependencyInProduct = 0;
Artifact *dependencyInOtherProduct = 0;
foreach (FileResourceBase *lookupResult, project->topLevelProject()
->buildData->lookupFiles(absDirPath, dependency.fileName())) {
if ((fileDependencyArtifact = dynamic_cast<FileDependency *>(lookupResult)))
continue;
Artifact * const foundArtifact = dynamic_cast<Artifact *>(lookupResult);
if (foundArtifact->product == product)
dependencyInProduct = foundArtifact;
else
dependencyInOtherProduct = foundArtifact;
}
// prioritize found artifacts
if ((result->file = dependencyInProduct)
|| (result->file = dependencyInOtherProduct)
|| (result->file = fileDependencyArtifact))
{
result->filePath = result->file->filePath();
return;
}
QString absFilePath = absDirPath + QLatin1Char('/') + dependency.fileName();
// TODO: We probably need a flag that tells us whether directories are allowed.
const FileInfo fi(absFilePath);
if (fi.exists(absFilePath) && !fi.isDir())
result->filePath = absFilePath;
}
static void resolveAbsolutePath(const ScanResultCache::Dependency &dependency,
const ResolvedProduct *product, ResolvedDependency *result)
{
QString absDirPath = dependency.dirPath();
if (!dependency.isClean())
absDirPath = QDir::cleanPath(absDirPath);
ResolvedProject *project = product->project.data();
FileDependency *fileDependencyArtifact = 0;
Artifact *dependencyInProduct = 0;
Artifact *dependencyInOtherProduct = 0;
foreach (FileResourceBase *lookupResult, project->topLevelProject()
->buildData->lookupFiles(absDirPath, dependency.fileName())) {
if ((fileDependencyArtifact = dynamic_cast<FileDependency *>(lookupResult)))
continue;
Artifact * const foundArtifact = dynamic_cast<Artifact *>(lookupResult);
if (foundArtifact->product == product)
dependencyInProduct = foundArtifact;
else
dependencyInOtherProduct = foundArtifact;
}
// prioritize found artifacts
if ((result->file = dependencyInProduct)
|| (result->file = dependencyInOtherProduct)
|| (result->file = fileDependencyArtifact)) {
result->filePath = result->file->filePath();
return;
}
if (FileInfo::exists(dependency.filePath()))
result->filePath = dependency.filePath();
}
static void scanWithScannerPlugin(DependencyScanner *scanner,
FileResourceBase *fileToBeScanned,
ScanResultCache::Result *scanResult)
{
QStringList dependencies = scanner->collectDependencies(fileToBeScanned);
foreach (const QString &s, dependencies)
scanResult->deps += ScanResultCache::Dependency(s);
scanResult->valid = true;
}
InputArtifactScanner::InputArtifactScanner(Artifact *artifact, InputArtifactScannerContext *ctx,
const Logger &logger)
: m_artifact(artifact), m_context(ctx), m_newDependencyAdded(false), m_logger(logger)
{
}
void InputArtifactScanner::scan()
{
if (m_artifact->inputsScanned)
return;
if (m_logger.traceEnabled()) {
m_logger.qbsTrace()
<< QString::fromLatin1("[DEPSCAN] inputs for %1 [%2] in product '%3'")
.arg(m_artifact->filePath(),
m_artifact->fileTags().toStringList().join(QLatin1String(", ")),
m_artifact->product->name);
}
m_artifact->inputsScanned = true;
// clear file dependencies; they will be regenerated
m_artifact->fileDependencies.clear();
// Remove all connections to children that were added by the dependency scanner.
// They will be regenerated.
foreach (Artifact *dependency, m_artifact->childrenAddedByScanner)
disconnect(m_artifact, dependency, m_logger);
ArtifactSet::const_iterator it = m_artifact->transformer->inputs.begin();
for (; it != m_artifact->transformer->inputs.end(); ++it) {
Artifact *inputArtifact = *it;
scanForFileDependencies(inputArtifact);
}
}
void InputArtifactScanner::scanForFileDependencies(Artifact *inputArtifact)
{
if (m_logger.traceEnabled()) {
m_logger.qbsTrace()
<< QString::fromLatin1("[DEPSCAN] input artifact %1 [%2]")
.arg(inputArtifact->filePath(),
inputArtifact->fileTags().toStringList().join(QLatin1String(", ")));
}
InputArtifactScannerContext::CacheItem &cacheItem = m_context->cache[inputArtifact->properties];
QSet<QString> visitedFilePaths;
QList<FileResourceBase *> filesToScan;
filesToScan.append(inputArtifact);
const QSet<DependencyScanner *> scanners = scannersForArtifact(inputArtifact);
while (!filesToScan.isEmpty()) {
FileResourceBase *fileToBeScanned = filesToScan.takeFirst();
const QString &filePathToBeScanned = fileToBeScanned->filePath();
if (visitedFilePaths.contains(filePathToBeScanned))
continue;
visitedFilePaths.insert(filePathToBeScanned);
foreach (DependencyScanner *scanner, scanners) {
scanForScannerFileDependencies(scanner, inputArtifact, fileToBeScanned,
scanner->recursive() ? &filesToScan : 0, cacheItem[scanner->key()]);
}
}
}
QSet<DependencyScanner *> InputArtifactScanner::scannersForArtifact(const Artifact *artifact) const
{
QSet<DependencyScanner *> scanners;
ResolvedProduct *product = artifact->product.data();
QHash<FileTag, InputArtifactScannerContext::DependencyScannerCacheItem> &scannerCache
= m_context->scannersCache[product];
foreach (const FileTag &fileTag, artifact->fileTags()) {
InputArtifactScannerContext::DependencyScannerCacheItem &cache = scannerCache[fileTag];
if (!cache.valid) {
cache.valid = true;
foreach (ScannerPlugin *scanner, ScannerPluginManager::scannersForFileTag(fileTag)) {
PluginDependencyScanner *pluginScanner = new PluginDependencyScanner(scanner);
cache.scanners += DependencyScannerPtr(pluginScanner);
}
foreach (const ResolvedScannerConstPtr &scanner, product->scanners) {
if (scanner->inputs.contains(fileTag)) {
cache.scanners += DependencyScannerPtr(
new UserDependencyScanner(scanner, m_logger));
break;
}
}
}
foreach (const DependencyScannerPtr &scanner, cache.scanners) {
scanners += scanner.data();
}
}
return scanners;
}
void InputArtifactScanner::scanForScannerFileDependencies(DependencyScanner *scanner,
Artifact *inputArtifact, FileResourceBase *fileToBeScanned,
QList<FileResourceBase *> *filesToScan,
InputArtifactScannerContext::ScannerResolvedDependenciesCache &cache)
{
if (m_logger.traceEnabled()) {
m_logger.qbsTrace() << QString::fromLatin1("[DEPSCAN] file %1")
.arg(fileToBeScanned->filePath());
}
const bool cacheHit = cache.valid;
if (!cacheHit) {
cache.valid = true;
cache.searchPaths = scanner->collectSearchPaths(inputArtifact);
}
if (m_logger.traceEnabled()) {
m_logger.qbsTrace()
<< "[DEPSCAN] include paths (cache " << (cacheHit ? "hit)" : "miss)");
foreach (const QString &s, cache.searchPaths)
m_logger.qbsTrace() << " " << s;
}
const QString &filePathToBeScanned = fileToBeScanned->filePath();
ScanResultCache::Result scanResult = m_context->scanResultCache->value(scanner->key(), filePathToBeScanned);
if (!scanResult.valid) {
try {
if (m_logger.traceEnabled())
m_logger.qbsTrace() << "scanning " << FileInfo::fileName(filePathToBeScanned);
scanWithScannerPlugin(scanner, fileToBeScanned, &scanResult);
} catch (const ErrorInfo &error) {
m_logger.printWarning(error);
return;
}
m_context->scanResultCache->insert(scanner->key(), filePathToBeScanned, scanResult);
}
resolveScanResultDependencies(inputArtifact, scanResult, filesToScan, cache);
}
void InputArtifactScanner::resolveScanResultDependencies(const Artifact *inputArtifact,
const ScanResultCache::Result &scanResult, QList<FileResourceBase *> *artifactsToScan,
InputArtifactScannerContext::ScannerResolvedDependenciesCache &cache)
{
foreach (const ScanResultCache::Dependency &dependency, scanResult.deps) {
const QString &dependencyFilePath = dependency.filePath();
InputArtifactScannerContext::ResolvedDependencyCacheItem &cachedResolvedDependencyItem
= cache.resolvedDependenciesCache[dependency.dirPath()][dependency.fileName()];
ResolvedDependency &resolvedDependency = cachedResolvedDependencyItem.resolvedDependency;
if (cachedResolvedDependencyItem.valid) {
if (resolvedDependency.filePath.isEmpty())
goto unresolved;
goto resolved;
}
cachedResolvedDependencyItem.valid = true;
if (FileInfo::isAbsolute(dependencyFilePath)) {
resolveAbsolutePath(dependency, inputArtifact->product.data(),
&resolvedDependency);
goto resolved;
}
// try include paths
foreach (const QString &includePath, cache.searchPaths) {
resolveWithIncludePath(includePath, dependency, inputArtifact->product.data(),
&resolvedDependency);
if (resolvedDependency.isValid())
goto resolved;
}
unresolved:
if (m_logger.traceEnabled())
m_logger.qbsWarning() << "[DEPSCAN] unresolved dependency " << dependencyFilePath;
continue;
resolved:
handleDependency(resolvedDependency);
if (artifactsToScan && resolvedDependency.file) {
if (Artifact *artifactDependency = dynamic_cast<Artifact *>(resolvedDependency.file)) {
// Do not scan artifacts that are being built. Otherwise we might read an incomplete
// file or conflict with the writing process.
if (artifactDependency->buildState != BuildGraphNode::Building)
artifactsToScan->append(artifactDependency);
} else {
// Add file dependency to the next round of scanning.
artifactsToScan->append(resolvedDependency.file);
}
}
}
}
void InputArtifactScanner::handleDependency(ResolvedDependency &dependency)
{
const ResolvedProductPtr product = m_artifact->product;
QBS_CHECK(m_artifact->artifactType == Artifact::Generated);
QBS_CHECK(product);
Artifact *artifactDependency = dynamic_cast<Artifact *>(dependency.file);
FileDependency *fileDependency
= artifactDependency ? 0 : dynamic_cast<FileDependency *>(dependency.file);
QBS_CHECK(!dependency.file || artifactDependency || fileDependency);
if (!dependency.file) {
// The dependency is an existing file but does not exist in the build graph.
if (m_logger.traceEnabled())
m_logger.qbsTrace() << "[DEPSCAN] add new file dependency " << dependency.filePath;
fileDependency = new FileDependency();
dependency.file = fileDependency;
fileDependency->setFilePath(dependency.filePath);
product->topLevelProject()->buildData->insertFileDependency(fileDependency);
} else if (fileDependency) {
// The dependency exists in the project's list of file dependencies.
if (m_logger.traceEnabled()) {
m_logger.qbsTrace() << "[DEPSCAN] add existing file dependency "
<< dependency.filePath;
}
} else if (artifactDependency->product == product) {
// The dependency is in our product.
if (m_logger.traceEnabled()) {
m_logger.qbsTrace() << "[DEPSCAN] add artifact dependency " << dependency.filePath
<< " (from this product)";
}
} else {
// The dependency is in some other product.
ResolvedProduct * const otherProduct = artifactDependency->product;
if (m_logger.traceEnabled()) {
m_logger.qbsTrace() << "[DEPSCAN] add artifact dependency " << dependency.filePath
<< " (from product " << otherProduct->uniqueName() << ')';
}
}
if (m_artifact == dependency.file)
return;
if (fileDependency) {
if (!m_artifact->fileDependencies.contains(fileDependency))
m_artifact->fileDependencies << fileDependency;
} else {
if (m_artifact->children.contains(artifactDependency))
return;
safeConnect(m_artifact, artifactDependency, m_logger);
m_artifact->childrenAddedByScanner += artifactDependency;
m_newDependencyAdded = true;
}
}
InputArtifactScannerContext::DependencyScannerCacheItem::DependencyScannerCacheItem() : valid(false)
{
}
InputArtifactScannerContext::DependencyScannerCacheItem::~DependencyScannerCacheItem()
{
}
} // namespace Internal
} // namespace qbs
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.