text stringlengths 54 60.6k |
|---|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2Support.h"
#include "OgreLogManager.h"
namespace Ogre {
void GLES2Support::initialiseExtensions(void)
{
String tmpStr;
#if 1
// Set version string
const GLubyte* pcVer = glGetString(GL_VERSION);
assert(pcVer && "Problems getting GL version string using glGetString");
tmpStr = (const char*)pcVer;
// format explained here:
// https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGetString.xml
size_t offset = sizeof("OpenGL ES ") - 1;
if(tmpStr.length() > offset) {
mVersion.fromString(tmpStr.substr(offset, tmpStr.find(" ", offset)));
}
#else
// GLES3 way, but should work with ES2 as well, so disabled for now
glGetIntegerv(GL_MAJOR_VERSION, &mVersion.major);
glGetIntegerv(GL_MINOR_VERSION, &mVersion.minor);
#endif
LogManager::getSingleton().logMessage("GL_VERSION = " + mVersion.toString());
// Get vendor
const GLubyte* pcVendor = glGetString(GL_VENDOR);
tmpStr = (const char*)pcVendor;
LogManager::getSingleton().logMessage("GL_VENDOR = " + tmpStr);
mVendor = tmpStr.substr(0, tmpStr.find(" "));
// Get renderer
const GLubyte* pcRenderer = glGetString(GL_RENDERER);
tmpStr = (const char*)pcRenderer;
LogManager::getSingleton().logMessage("GL_RENDERER = " + tmpStr);
// Set extension list
StringStream ext;
String str;
const GLubyte* pcExt = glGetString(GL_EXTENSIONS);
OgreAssert(pcExt, "Problems getting GL extension string using glGetString");
ext << pcExt;
LogManager::getSingleton().logMessage("GL_EXTENSIONS = " + String((const char*)pcExt));
while (ext >> str)
{
extensionList.insert(str);
}
}
bool GLES2Support::hasMinGLVersion(int major, int minor) const
{
if (mVersion.major == major) {
return mVersion.minor >= minor;
}
return mVersion.major > major;
}
bool GLES2Support::checkExtension(const String& ext) const
{
return extensionList.find(ext) != extensionList.end() || mNative->checkExtension(ext);
}
}
<commit_msg>GLES2: skip unprefixed extensions on emscripten for consistency<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2Support.h"
#include "OgreLogManager.h"
namespace Ogre {
void GLES2Support::initialiseExtensions(void)
{
String tmpStr;
#if 1
// Set version string
const GLubyte* pcVer = glGetString(GL_VERSION);
assert(pcVer && "Problems getting GL version string using glGetString");
tmpStr = (const char*)pcVer;
// format explained here:
// https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGetString.xml
size_t offset = sizeof("OpenGL ES ") - 1;
if(tmpStr.length() > offset) {
mVersion.fromString(tmpStr.substr(offset, tmpStr.find(" ", offset)));
}
#else
// GLES3 way, but should work with ES2 as well, so disabled for now
glGetIntegerv(GL_MAJOR_VERSION, &mVersion.major);
glGetIntegerv(GL_MINOR_VERSION, &mVersion.minor);
#endif
LogManager::getSingleton().logMessage("GL_VERSION = " + mVersion.toString());
// Get vendor
const GLubyte* pcVendor = glGetString(GL_VENDOR);
tmpStr = (const char*)pcVendor;
LogManager::getSingleton().logMessage("GL_VENDOR = " + tmpStr);
mVendor = tmpStr.substr(0, tmpStr.find(" "));
// Get renderer
const GLubyte* pcRenderer = glGetString(GL_RENDERER);
tmpStr = (const char*)pcRenderer;
LogManager::getSingleton().logMessage("GL_RENDERER = " + tmpStr);
// Set extension list
StringStream ext;
String str;
const GLubyte* pcExt = glGetString(GL_EXTENSIONS);
OgreAssert(pcExt, "Problems getting GL extension string using glGetString");
ext << pcExt;
Log::Stream log = LogManager::getSingleton().stream();
log << "GL_EXTENSIONS = ";
while (ext >> str)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN
if (str.substr(0, 3) != "GL_") // emscripten gives us both prefixed and unprefixed forms
continue;
#endif
log << str << " ";
extensionList.insert(str);
}
}
bool GLES2Support::hasMinGLVersion(int major, int minor) const
{
if (mVersion.major == major) {
return mVersion.minor >= minor;
}
return mVersion.major > major;
}
bool GLES2Support::checkExtension(const String& ext) const
{
return extensionList.find(ext) != extensionList.end() || mNative->checkExtension(ext);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/GrTextureMaker.h"
#include "include/private/GrRecordingContext.h"
#include "src/gpu/GrColorSpaceXform.h"
#include "src/gpu/GrGpu.h"
#include "src/gpu/GrProxyProvider.h"
#include "src/gpu/GrRecordingContextPriv.h"
#include "src/gpu/SkGr.h"
GrSurfaceProxyView GrTextureMaker::onRefTextureProxyViewForParams(GrSamplerState params,
bool willBeMipped) {
if (this->width() > this->context()->priv().caps()->maxTextureSize() ||
this->height() > this->context()->priv().caps()->maxTextureSize()) {
return {};
}
GrSurfaceProxyView original = this->refOriginalTextureProxyView(willBeMipped);
if (!original) {
return {};
}
SkASSERT(original.asTextureProxy());
GrTextureProxy* texProxy = original.asTextureProxy();
if (!GrGpu::IsACopyNeededForMips(this->context()->priv().caps(), texProxy, params.filter())) {
return original;
}
GrProxyProvider* proxyProvider = this->context()->priv().proxyProvider();
GrSurfaceOrigin origOrigin = original.proxy() ? original.origin() : kTopLeft_GrSurfaceOrigin;
GrUniqueKey mipMappedKey;
this->makeMipMappedKey(&mipMappedKey);
if (mipMappedKey.isValid()) {
auto cachedProxy =
proxyProvider->findOrCreateProxyByUniqueKey(mipMappedKey, this->colorType());
if (cachedProxy) {
SkASSERT(cachedProxy->mipMapped() == GrMipMapped::kYes);
return GrSurfaceProxyView(std::move(cachedProxy), origOrigin, original.swizzle());
}
}
GrSurfaceProxyView result = GrCopyBaseMipMapToTextureProxy(
this->context(), original.proxy(), original.origin(), this->colorType());
if (!result) {
// If we were unable to make a copy and we only needed a copy for mips, then we will return
// the source texture here and require that the GPU backend is able to fall back to using
// bilerp if mips are required.
return original;
}
// We believe all Makers already have tried to add MIP maps in refOriginalTextureProxyView()
// if willBeMipped was true and therefore we should never get here.
SkASSERT(false);
if (mipMappedKey.isValid()) {
SkASSERT(result.origin() == origOrigin);
proxyProvider->assignUniqueKeyToProxy(mipMappedKey, result.asTextureProxy());
this->didCacheMipMappedCopy(mipMappedKey, proxyProvider->contextID());
}
return result;
}
std::unique_ptr<GrFragmentProcessor> GrTextureMaker::createFragmentProcessor(
const SkMatrix& textureMatrix,
const SkRect& constraintRect,
FilterConstraint filterConstraint,
bool coordsLimitedToConstraintRect,
const GrSamplerState::Filter* filterOrNullForBicubic) {
const GrSamplerState::Filter* fmForDetermineDomain = filterOrNullForBicubic;
if (filterOrNullForBicubic && GrSamplerState::Filter::kMipMap == *filterOrNullForBicubic &&
kYes_FilterConstraint == filterConstraint) {
// TODO: Here we should force a copy restricted to the constraintRect since MIP maps will
// read outside the constraint rect. However, as in the adjuster case, we aren't currently
// doing that.
// We instead we compute the domain as though were bilerping which is only correct if we
// only sample level 0.
static const GrSamplerState::Filter kBilerp = GrSamplerState::Filter::kBilerp;
fmForDetermineDomain = &kBilerp;
}
GrSurfaceProxyView view = this->viewForParams(filterOrNullForBicubic);
if (!view) {
return nullptr;
}
SkRect domain;
DomainMode domainMode =
DetermineDomainMode(constraintRect, filterConstraint, coordsLimitedToConstraintRect,
view.proxy(), fmForDetermineDomain, &domain);
SkASSERT(kTightCopy_DomainMode != domainMode);
return this->createFragmentProcessorForDomainAndFilter(
std::move(view), textureMatrix, domainMode, domain, filterOrNullForBicubic);
}
<commit_msg>Remove code from GrTextureMaker that tries to make a MIP map copy.<commit_after>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/GrTextureMaker.h"
#include "include/private/GrRecordingContext.h"
#include "src/gpu/GrColorSpaceXform.h"
#include "src/gpu/GrGpu.h"
#include "src/gpu/GrProxyProvider.h"
#include "src/gpu/GrRecordingContextPriv.h"
#include "src/gpu/SkGr.h"
GrSurfaceProxyView GrTextureMaker::onRefTextureProxyViewForParams(GrSamplerState params,
bool willBeMipped) {
if (this->width() > this->context()->priv().caps()->maxTextureSize() ||
this->height() > this->context()->priv().caps()->maxTextureSize()) {
return {};
}
return this->refOriginalTextureProxyView(willBeMipped);
}
std::unique_ptr<GrFragmentProcessor> GrTextureMaker::createFragmentProcessor(
const SkMatrix& textureMatrix,
const SkRect& constraintRect,
FilterConstraint filterConstraint,
bool coordsLimitedToConstraintRect,
const GrSamplerState::Filter* filterOrNullForBicubic) {
const GrSamplerState::Filter* fmForDetermineDomain = filterOrNullForBicubic;
if (filterOrNullForBicubic && GrSamplerState::Filter::kMipMap == *filterOrNullForBicubic &&
kYes_FilterConstraint == filterConstraint) {
// TODO: Here we should force a copy restricted to the constraintRect since MIP maps will
// read outside the constraint rect. However, as in the adjuster case, we aren't currently
// doing that.
// We instead we compute the domain as though were bilerping which is only correct if we
// only sample level 0.
static const GrSamplerState::Filter kBilerp = GrSamplerState::Filter::kBilerp;
fmForDetermineDomain = &kBilerp;
}
GrSurfaceProxyView view = this->viewForParams(filterOrNullForBicubic);
if (!view) {
return nullptr;
}
SkRect domain;
DomainMode domainMode =
DetermineDomainMode(constraintRect, filterConstraint, coordsLimitedToConstraintRect,
view.proxy(), fmForDetermineDomain, &domain);
SkASSERT(kTightCopy_DomainMode != domainMode);
return this->createFragmentProcessorForDomainAndFilter(
std::move(view), textureMatrix, domainMode, domain, filterOrNullForBicubic);
}
<|endoftext|> |
<commit_before>// @(#)root/krb5auth:$Id$
// Author: Maarten Ballintijn 27/10/2003
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#ifndef WIN32
# include <unistd.h>
#endif
#include "TKSocket.h"
#include "TSocket.h"
#include "TError.h"
extern "C" {
// missing from "krb5.h"
extern int krb5_net_read(/*IN*/ krb5_context context, int fd,
/*OUT*/ char *buf,/*IN*/ int len);
extern int krb5_net_write(/*IN*/ krb5_context context, int fd,
const char *buf, int len);
}
#ifdef __APPLE__
#define SOCKET int
#define SOCKET_ERRNO errno
#define SOCKET_EINTR EINTR
#define SOCKET_READ(a,b,c) read(a,b,c)
#define SOCKET_WRITE(a,b,c) write(a,b,c)
/*
* lib/krb5/os/net_read.c
*
* Copyright 1987, 1988, 1990 by the Massachusetts Institute of Technology.
* All Rights Reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*
*/
/*
* krb5_net_read() reads from the file descriptor "fd" to the buffer
* "buf", until either 1) "len" bytes have been read or 2) cannot
* read anymore from "fd". It returns the number of bytes read
* or a read() error. (The calling interface is identical to
* read(2).)
*
* XXX must not use non-blocking I/O
*/
int krb5_net_read(krb5_context /*context*/, int fd, register char *buf, register int len)
{
int cc, len2 = 0;
do {
cc = SOCKET_READ((SOCKET)fd, buf, len);
if (cc < 0) {
if (SOCKET_ERRNO == SOCKET_EINTR)
continue;
/* XXX this interface sucks! */
errno = SOCKET_ERRNO;
return(cc); /* errno is already set */
} else if (cc == 0) {
return(len2);
} else {
buf += cc;
len2 += cc;
len -= cc;
}
} while (len > 0);
return(len2);
}
/*
* lib/krb5/os/net_write.c
*
* Copyright 1987, 1988, 1990 by the Massachusetts Institute of Technology.
* All Rights Reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*
*/
/*
* krb5_net_write() writes "len" bytes from "buf" to the file
* descriptor "fd". It returns the number of bytes written or
* a write() error. (The calling interface is identical to
* write(2).)
*
* XXX must not use non-blocking I/O
*/
int krb5_net_write(krb5_context /*context*/, int fd, register const char *buf, int len)
{
int cc;
int wrlen = len;
do {
cc = SOCKET_WRITE((SOCKET)fd, buf, wrlen);
if (cc < 0) {
if (SOCKET_ERRNO == SOCKET_EINTR)
continue;
/* XXX this interface sucks! */
errno = SOCKET_ERRNO;
return(cc);
} else {
buf += cc;
wrlen -= cc;
}
} while (wrlen > 0);
return(len);
}
#endif
ClassImp(TKSocket);
krb5_context TKSocket::fgContext = 0;
krb5_ccache TKSocket::fgCCDef = 0;
krb5_principal TKSocket::fgClient = 0;
////////////////////////////////////////////////////////////////////////////////
/// Constructor
TKSocket::TKSocket(TSocket *s)
: fSocket(s), fServer(0), fAuthContext(0)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Destructor
TKSocket::~TKSocket()
{
krb5_free_principal(fgContext, fServer);
krb5_auth_con_free(fgContext, fAuthContext);
delete fSocket;
}
////////////////////////////////////////////////////////////////////////////////
/// Connect to 'server' on 'port'
TKSocket *TKSocket::Connect(const char *server, Int_t port)
{
Int_t rc;
if (fgContext == 0) {
rc = krb5_init_context(&fgContext);
if (rc != 0) {
::Error("TKSocket::Connect","while initializing krb5 (%d), %s",
rc, error_message(rc));
return 0;
}
rc = krb5_cc_default(fgContext, &fgCCDef);
if (rc != 0) {
::Error("TKSocket::Connect","while getting default credential cache (%d), %s",
rc, error_message(rc));
krb5_free_context(fgContext); fgContext = 0;
return 0;
}
rc = krb5_cc_get_principal(fgContext, fgCCDef, &fgClient);
if (rc != 0) {
::Error("TKSocket::Connect","while getting client principal from %s (%d), %s",
krb5_cc_get_name(fgContext,fgCCDef), rc, error_message(rc));
krb5_cc_close(fgContext,fgCCDef); fgCCDef = 0;
krb5_free_context(fgContext); fgContext = 0;
return 0;
}
}
TSocket *s = new TSocket(server, port);
if (!s->IsValid()) {
::SysError("TKSocket::Connect","Cannot connect to %s:%d", server, port);
delete s;
return 0;
}
TKSocket *ks = new TKSocket(s);
rc = krb5_sname_to_principal(fgContext, server, "host", KRB5_NT_SRV_HST, &ks->fServer);
if (rc != 0) {
::Error("TKSocket::Connect","while getting server principal (%d), %s",
rc, error_message(rc));
delete ks;
return 0;
}
krb5_data cksum_data;
cksum_data.data = StrDup(server);
cksum_data.length = strlen(server);
krb5_error *err_ret;
krb5_ap_rep_enc_part *rep_ret;
int sock = ks->fSocket->GetDescriptor();
rc = krb5_sendauth(fgContext, &ks->fAuthContext, (krb5_pointer) &sock,
(char *)"KRB5_TCP_Python_v1.0", fgClient, ks->fServer,
AP_OPTS_MUTUAL_REQUIRED,
&cksum_data,
0, /* no creds, use ccache instead */
fgCCDef, &err_ret, &rep_ret, 0);
delete [] cksum_data.data;
if (rc != 0) {
::Error("TKSocket::Connect","while sendauth (%d), %s",
rc, error_message(rc));
delete ks;
return 0;
}
return ks;
}
////////////////////////////////////////////////////////////////////////////////
/// Read block on information from server. The result is stored in buf.
/// The number of read bytes is returned; -1 is returned in case of error.
Int_t TKSocket::BlockRead(char *&buf, EEncoding &type)
{
Int_t rc;
Desc_t desc;
Int_t fd = fSocket->GetDescriptor();
rc = krb5_net_read(fgContext, fd, (char *)&desc, sizeof(desc));
if (rc == 0) errno = ECONNABORTED;
if (rc <= 0) {
SysError("BlockRead","reading descriptor (%d), %s",
rc, error_message(rc));
return -1;
}
type = static_cast<EEncoding>(ntohs(desc.fType));
krb5_data enc;
enc.length = ntohs(desc.fLength);
enc.data = new char[enc.length+1];
rc = krb5_net_read(fgContext, fd, enc.data, enc.length);
enc.data[enc.length] = 0;
if (rc == 0) errno = ECONNABORTED;
if (rc <= 0) {
SysError("BlockRead","reading data (%d), %s",
rc, error_message(rc));
delete [] enc.data;
return -1;
}
krb5_data out;
switch (type) {
case kNone:
buf = enc.data;
rc = enc.length;
break;
case kSafe:
rc = krb5_rd_safe(fgContext, fAuthContext, &enc, &out, 0);
break;
case kPriv:
rc = krb5_rd_priv(fgContext, fAuthContext, &enc, &out, 0);
break;
default:
Error("BlockWrite","unknown encoding type (%d)", type);
return -1;
}
if (type != kNone) {
// copy data to buffer that is new'ed
buf = new char[out.length+1];
memcpy(buf, out.data, out.length);
buf[out.length] = 0;
free(out.data);
delete [] enc.data;
rc = out.length;
}
return rc;
}
////////////////////////////////////////////////////////////////////////////////
/// Block-send 'length' bytes to server from 'buf'.
Int_t TKSocket::BlockWrite(const char *buf, Int_t length, EEncoding type)
{
Desc_t desc;
krb5_data in;
krb5_data enc;
Int_t rc;
in.data = const_cast<char*>(buf);
in.length = length;
switch (type) {
case kNone:
enc.data = in.data;
enc.length = in.length;
break;
case kSafe:
rc = krb5_mk_safe(fgContext, fAuthContext, &in, &enc, 0);
break;
case kPriv:
rc = krb5_mk_priv(fgContext, fAuthContext, &in, &enc, 0);
break;
default:
Error("BlockWrite","unknown encoding type (%d)", type);
return -1;
}
desc.fLength = htons(enc.length);
desc.fType = htons(type);
Int_t fd = fSocket->GetDescriptor();
rc = krb5_net_write(fgContext, fd, (char *)&desc, sizeof(desc));
if (rc <= 0) {
Error("BlockWrite","writing descriptor (%d), %s",
rc, error_message(rc));
return -1;
}
rc = krb5_net_write(fgContext, fd, (char *)enc.data, enc.length);
if (rc <= 0) {
Error("BlockWrite","writing data (%d), %s",
rc, error_message(rc));
return -1;
}
if (type != kNone) free(enc.data);
return rc;
}
<commit_msg>[krb] Remove "register" warning.<commit_after>// @(#)root/krb5auth:$Id$
// Author: Maarten Ballintijn 27/10/2003
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#ifndef WIN32
# include <unistd.h>
#endif
#include "TKSocket.h"
#include "TSocket.h"
#include "TError.h"
extern "C" {
// missing from "krb5.h"
extern int krb5_net_read(/*IN*/ krb5_context context, int fd,
/*OUT*/ char *buf,/*IN*/ int len);
extern int krb5_net_write(/*IN*/ krb5_context context, int fd,
const char *buf, int len);
}
#ifdef __APPLE__
#define SOCKET int
#define SOCKET_ERRNO errno
#define SOCKET_EINTR EINTR
#define SOCKET_READ(a,b,c) read(a,b,c)
#define SOCKET_WRITE(a,b,c) write(a,b,c)
/*
* lib/krb5/os/net_read.c
*
* Copyright 1987, 1988, 1990 by the Massachusetts Institute of Technology.
* All Rights Reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*
*/
/*
* krb5_net_read() reads from the file descriptor "fd" to the buffer
* "buf", until either 1) "len" bytes have been read or 2) cannot
* read anymore from "fd". It returns the number of bytes read
* or a read() error. (The calling interface is identical to
* read(2).)
*
* XXX must not use non-blocking I/O
*/
int krb5_net_read(krb5_context /*context*/, int fd, char *buf, int len)
{
int cc, len2 = 0;
do {
cc = SOCKET_READ((SOCKET)fd, buf, len);
if (cc < 0) {
if (SOCKET_ERRNO == SOCKET_EINTR)
continue;
/* XXX this interface sucks! */
errno = SOCKET_ERRNO;
return(cc); /* errno is already set */
} else if (cc == 0) {
return(len2);
} else {
buf += cc;
len2 += cc;
len -= cc;
}
} while (len > 0);
return(len2);
}
/*
* lib/krb5/os/net_write.c
*
* Copyright 1987, 1988, 1990 by the Massachusetts Institute of Technology.
* All Rights Reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*
*/
/*
* krb5_net_write() writes "len" bytes from "buf" to the file
* descriptor "fd". It returns the number of bytes written or
* a write() error. (The calling interface is identical to
* write(2).)
*
* XXX must not use non-blocking I/O
*/
int krb5_net_write(krb5_context /*context*/, int fd, const char *buf, int len)
{
int cc;
int wrlen = len;
do {
cc = SOCKET_WRITE((SOCKET)fd, buf, wrlen);
if (cc < 0) {
if (SOCKET_ERRNO == SOCKET_EINTR)
continue;
/* XXX this interface sucks! */
errno = SOCKET_ERRNO;
return(cc);
} else {
buf += cc;
wrlen -= cc;
}
} while (wrlen > 0);
return(len);
}
#endif
ClassImp(TKSocket);
krb5_context TKSocket::fgContext = 0;
krb5_ccache TKSocket::fgCCDef = 0;
krb5_principal TKSocket::fgClient = 0;
////////////////////////////////////////////////////////////////////////////////
/// Constructor
TKSocket::TKSocket(TSocket *s)
: fSocket(s), fServer(0), fAuthContext(0)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Destructor
TKSocket::~TKSocket()
{
krb5_free_principal(fgContext, fServer);
krb5_auth_con_free(fgContext, fAuthContext);
delete fSocket;
}
////////////////////////////////////////////////////////////////////////////////
/// Connect to 'server' on 'port'
TKSocket *TKSocket::Connect(const char *server, Int_t port)
{
Int_t rc;
if (fgContext == 0) {
rc = krb5_init_context(&fgContext);
if (rc != 0) {
::Error("TKSocket::Connect","while initializing krb5 (%d), %s",
rc, error_message(rc));
return 0;
}
rc = krb5_cc_default(fgContext, &fgCCDef);
if (rc != 0) {
::Error("TKSocket::Connect","while getting default credential cache (%d), %s",
rc, error_message(rc));
krb5_free_context(fgContext); fgContext = 0;
return 0;
}
rc = krb5_cc_get_principal(fgContext, fgCCDef, &fgClient);
if (rc != 0) {
::Error("TKSocket::Connect","while getting client principal from %s (%d), %s",
krb5_cc_get_name(fgContext,fgCCDef), rc, error_message(rc));
krb5_cc_close(fgContext,fgCCDef); fgCCDef = 0;
krb5_free_context(fgContext); fgContext = 0;
return 0;
}
}
TSocket *s = new TSocket(server, port);
if (!s->IsValid()) {
::SysError("TKSocket::Connect","Cannot connect to %s:%d", server, port);
delete s;
return 0;
}
TKSocket *ks = new TKSocket(s);
rc = krb5_sname_to_principal(fgContext, server, "host", KRB5_NT_SRV_HST, &ks->fServer);
if (rc != 0) {
::Error("TKSocket::Connect","while getting server principal (%d), %s",
rc, error_message(rc));
delete ks;
return 0;
}
krb5_data cksum_data;
cksum_data.data = StrDup(server);
cksum_data.length = strlen(server);
krb5_error *err_ret;
krb5_ap_rep_enc_part *rep_ret;
int sock = ks->fSocket->GetDescriptor();
rc = krb5_sendauth(fgContext, &ks->fAuthContext, (krb5_pointer) &sock,
(char *)"KRB5_TCP_Python_v1.0", fgClient, ks->fServer,
AP_OPTS_MUTUAL_REQUIRED,
&cksum_data,
0, /* no creds, use ccache instead */
fgCCDef, &err_ret, &rep_ret, 0);
delete [] cksum_data.data;
if (rc != 0) {
::Error("TKSocket::Connect","while sendauth (%d), %s",
rc, error_message(rc));
delete ks;
return 0;
}
return ks;
}
////////////////////////////////////////////////////////////////////////////////
/// Read block on information from server. The result is stored in buf.
/// The number of read bytes is returned; -1 is returned in case of error.
Int_t TKSocket::BlockRead(char *&buf, EEncoding &type)
{
Int_t rc;
Desc_t desc;
Int_t fd = fSocket->GetDescriptor();
rc = krb5_net_read(fgContext, fd, (char *)&desc, sizeof(desc));
if (rc == 0) errno = ECONNABORTED;
if (rc <= 0) {
SysError("BlockRead","reading descriptor (%d), %s",
rc, error_message(rc));
return -1;
}
type = static_cast<EEncoding>(ntohs(desc.fType));
krb5_data enc;
enc.length = ntohs(desc.fLength);
enc.data = new char[enc.length+1];
rc = krb5_net_read(fgContext, fd, enc.data, enc.length);
enc.data[enc.length] = 0;
if (rc == 0) errno = ECONNABORTED;
if (rc <= 0) {
SysError("BlockRead","reading data (%d), %s",
rc, error_message(rc));
delete [] enc.data;
return -1;
}
krb5_data out;
switch (type) {
case kNone:
buf = enc.data;
rc = enc.length;
break;
case kSafe:
rc = krb5_rd_safe(fgContext, fAuthContext, &enc, &out, 0);
break;
case kPriv:
rc = krb5_rd_priv(fgContext, fAuthContext, &enc, &out, 0);
break;
default:
Error("BlockWrite","unknown encoding type (%d)", type);
return -1;
}
if (type != kNone) {
// copy data to buffer that is new'ed
buf = new char[out.length+1];
memcpy(buf, out.data, out.length);
buf[out.length] = 0;
free(out.data);
delete [] enc.data;
rc = out.length;
}
return rc;
}
////////////////////////////////////////////////////////////////////////////////
/// Block-send 'length' bytes to server from 'buf'.
Int_t TKSocket::BlockWrite(const char *buf, Int_t length, EEncoding type)
{
Desc_t desc;
krb5_data in;
krb5_data enc;
Int_t rc;
in.data = const_cast<char*>(buf);
in.length = length;
switch (type) {
case kNone:
enc.data = in.data;
enc.length = in.length;
break;
case kSafe:
rc = krb5_mk_safe(fgContext, fAuthContext, &in, &enc, 0);
break;
case kPriv:
rc = krb5_mk_priv(fgContext, fAuthContext, &in, &enc, 0);
break;
default:
Error("BlockWrite","unknown encoding type (%d)", type);
return -1;
}
desc.fLength = htons(enc.length);
desc.fType = htons(type);
Int_t fd = fSocket->GetDescriptor();
rc = krb5_net_write(fgContext, fd, (char *)&desc, sizeof(desc));
if (rc <= 0) {
Error("BlockWrite","writing descriptor (%d), %s",
rc, error_message(rc));
return -1;
}
rc = krb5_net_write(fgContext, fd, (char *)enc.data, enc.length);
if (rc <= 0) {
Error("BlockWrite","writing data (%d), %s",
rc, error_message(rc));
return -1;
}
if (type != kNone) free(enc.data);
return rc;
}
<|endoftext|> |
<commit_before>/*
Copyright 2015-2020 Igor Petrovic
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 <string.h>
#include <stdio.h>
#include "Display.h"
#include "core/src/general/Timing.h"
#include "core/src/general/Helpers.h"
using namespace IO;
///
/// \brief Initialize display driver and variables.
///
bool Display::init(bool startupInfo)
{
if (initDone)
U8X8::clearDisplay();
if (database.read(Database::Section::display_t::features, static_cast<size_t>(feature_t::enable)))
{
auto controller = static_cast<U8X8::displayController_t>(database.read(Database::Section::display_t::setting, static_cast<size_t>(setting_t::controller)));
auto resolution = static_cast<U8X8::displayResolution_t>(database.read(Database::Section::display_t::setting, static_cast<size_t>(setting_t::resolution)));
if (U8X8::initDisplay(controller, resolution))
{
U8X8::setPowerSave(0);
U8X8::setFlipMode(0);
this->resolution = resolution;
U8X8::setFont(u8x8_font_pxplustandynewtv_r);
U8X8::clearDisplay();
//init char arrays
for (int i = 0; i < LCD_HEIGHT_MAX; i++)
{
for (int j = 0; j < LCD_STRING_BUFFER_SIZE - 2; j++)
{
lcdRowStillText[i][j] = ' ';
lcdRowTempText[i][j] = ' ';
}
lcdRowStillText[i][LCD_STRING_BUFFER_SIZE - 1] = '\0';
lcdRowTempText[i][LCD_STRING_BUFFER_SIZE - 1] = '\0';
scrollEvent[i].size = 0;
scrollEvent[i].startIndex = 0;
scrollEvent[i].currentIndex = 0;
scrollEvent[i].direction = scrollDirection_t::leftToRight;
}
initDone = true;
displayHome();
if (startupInfo)
{
setDirectWriteState(true);
if (database.read(Database::Section::display_t::features, static_cast<size_t>(feature_t::welcomeMsg)))
displayWelcomeMessage();
if (database.read(Database::Section::display_t::features, static_cast<size_t>(feature_t::vInfoMsg)))
displayVinfo(false);
setDirectWriteState(false);
}
setAlternateNoteDisplay(database.read(Database::Section::display_t::features, static_cast<size_t>(feature_t::MIDInotesAlternate)));
setRetentionTime(database.read(Database::Section::display_t::setting, static_cast<size_t>(setting_t::MIDIeventTime)) * 1000);
return true;
}
}
return false;
}
///
/// \brief Checks if LCD requires updating continuously.
///
bool Display::update()
{
if (!initDone)
return false;
if ((core::timing::currentRunTimeMs() - lastLCDupdateTime) < LCD_REFRESH_TIME)
return false; //we don't need to update lcd in real time
//use char pointer to point to line we're going to print
char* charPointer;
updateTempTextStatus();
for (int i = 0; i < LCD_HEIGHT_MAX; i++)
{
if (activeTextType == lcdTextType_t::still)
{
//scrolling is possible only with still text
updateScrollStatus(i);
charPointer = lcdRowStillText[i];
}
else
{
charPointer = lcdRowTempText[i];
}
if (!charChange[i])
continue;
int8_t string_len = strlen(charPointer) > LCD_WIDTH_MAX ? LCD_WIDTH_MAX : strlen(charPointer);
for (int j = 0; j < string_len; j++)
{
if (BIT_READ(charChange[i], j))
U8X8::drawGlyph(j, rowMap[resolution][i], charPointer[j + scrollEvent[i].currentIndex]);
}
//now fill remaining columns with spaces
for (int j = string_len; j < LCD_WIDTH_MAX; j++)
U8X8::drawGlyph(j, rowMap[resolution][i], ' ');
charChange[i] = 0;
}
lastLCDupdateTime = core::timing::currentRunTimeMs();
//check if midi in/out messages need to be cleared
if (MIDImessageRetentionTime)
{
for (int i = 0; i < 2; i++)
{
//0 = in, 1 = out
if ((core::timing::currentRunTimeMs() - lastMIDIMessageDisplayTime[i] > MIDImessageRetentionTime) && midiMessageDisplayed[i])
clearMIDIevent(static_cast<eventType_t>(i));
}
}
return true;
}
///
/// \brief Updates text to be shown on display.
/// This function only updates internal buffers with received text, actual updating is done in update() function.
/// Text isn't passed directly, instead, value from string builder is used.
/// @param [in] row Row which is being updated.
/// @param [in] textType Type of text to be shown on display (enumerated type). See lcdTextType_t enumeration.
/// @param [in] startIndex Index on which received text should on specified row.
///
void Display::updateText(uint8_t row, lcdTextType_t textType, uint8_t startIndex)
{
if (!initDone)
return;
const char* string = stringBuilder.string();
uint8_t size = strlen(string);
uint8_t scrollSize = 0;
if (size + startIndex >= LCD_STRING_BUFFER_SIZE - 2)
size = LCD_STRING_BUFFER_SIZE - 2 - startIndex; //trim string
if (directWriteState)
{
for (int j = 0; j < size; j++)
U8X8::drawGlyph(j + startIndex, rowMap[resolution][row], string[j]);
}
else
{
bool scrollingEnabled = false;
switch (textType)
{
case lcdTextType_t::still:
for (int i = 0; i < size; i++)
{
lcdRowStillText[row][startIndex + i] = string[i];
BIT_WRITE(charChange[row], startIndex + i, 1);
}
//scrolling is enabled only if some characters are found after LCD_WIDTH_MAX-1 index
for (int i = LCD_WIDTH_MAX; i < LCD_STRING_BUFFER_SIZE - 1; i++)
{
if ((lcdRowStillText[row][i] != ' ') && (lcdRowStillText[row][i] != '\0'))
{
scrollingEnabled = true;
scrollSize++;
}
}
if (scrollingEnabled && !scrollEvent[row].size)
{
//enable scrolling
scrollEvent[row].size = scrollSize;
scrollEvent[row].startIndex = startIndex;
scrollEvent[row].currentIndex = 0;
scrollEvent[row].direction = scrollDirection_t::leftToRight;
lastScrollTime = core::timing::currentRunTimeMs();
}
else if (!scrollingEnabled && scrollEvent[row].size)
{
scrollEvent[row].size = 0;
scrollEvent[row].startIndex = 0;
scrollEvent[row].currentIndex = 0;
scrollEvent[row].direction = scrollDirection_t::leftToRight;
}
break;
case lcdTextType_t::temp:
//clear entire message first
for (int j = 0; j < LCD_WIDTH_MAX - 2; j++)
lcdRowTempText[row][j] = ' ';
lcdRowTempText[row][LCD_WIDTH_MAX - 1] = '\0';
for (int i = 0; i < size; i++)
lcdRowTempText[row][startIndex + i] = string[i];
//make sure message is properly EOL'ed
lcdRowTempText[row][startIndex + size] = '\0';
activeTextType = lcdTextType_t::temp;
messageDisplayTime = core::timing::currentRunTimeMs();
//update all characters on display
for (int i = 0; i < LCD_HEIGHT_MAX; i++)
charChange[i] = static_cast<uint32_t>(0xFFFFFFFF);
break;
default:
return;
}
}
}
///
/// \brief Enables or disables direct writing to LCD.
/// When enabled, low-level APIs are used to write text to LCD directly.
/// Otherwise, update() function takes care of updating LCD.
/// @param [in] state New direct write state.
///
void Display::setDirectWriteState(bool state)
{
directWriteState = state;
}
///
/// \brief Calculates position on which text needs to be set on display to be in center of display row.
/// @param [in] textSize Size of text for which center position on display is being calculated.
/// \returns Center position of text on display.
///
uint8_t Display::getTextCenter(uint8_t textSize)
{
return U8X8::getColumns() / 2 - (textSize / 2);
}
///
/// \brief Updates status of temp text on display.
///
void Display::updateTempTextStatus()
{
if (activeTextType == lcdTextType_t::temp)
{
//temp text - check if temp text should be removed
if ((core::timing::currentRunTimeMs() - messageDisplayTime) > LCD_MESSAGE_DURATION)
{
activeTextType = lcdTextType_t::still;
//make sure all characters are updated once temp text is removed
for (int j = 0; j < LCD_HEIGHT_MAX; j++)
charChange[j] = static_cast<uint32_t>(0xFFFFFFFF);
}
}
}
///
/// \brief Updates status of scrolling text on display.
/// @param [in] row Row which is being checked.
///
void Display::updateScrollStatus(uint8_t row)
{
if (!scrollEvent[row].size)
return;
if ((core::timing::currentRunTimeMs() - lastScrollTime) < LCD_SCROLL_TIME)
return;
switch (scrollEvent[row].direction)
{
case scrollDirection_t::leftToRight:
//left to right
scrollEvent[row].currentIndex++;
if (scrollEvent[row].currentIndex == scrollEvent[row].size)
{
//switch direction
scrollEvent[row].direction = scrollDirection_t::rightToLeft;
}
break;
case scrollDirection_t::rightToLeft:
//right to left
scrollEvent[row].currentIndex--;
if (scrollEvent[row].currentIndex == 0)
{
//switch direction
scrollEvent[row].direction = scrollDirection_t::leftToRight;
}
break;
}
for (int i = scrollEvent[row].startIndex; i < LCD_WIDTH_MAX; i++)
BIT_WRITE(charChange[row], i, 1);
lastScrollTime = core::timing::currentRunTimeMs();
}
///
/// \brief Checks for currently active text type on display.
/// \returns Active text type (enumerated type). See lcdTextType_t enumeration.
///
Display::lcdTextType_t Display::getActiveTextType()
{
return activeTextType;
}
///
/// \brief Sets new message retention time.
/// @param [in] retentionTime New retention time in milliseconds.
///
void Display::setRetentionTime(uint32_t retentionTime)
{
if (retentionTime < MIDImessageRetentionTime)
{
for (int i = 0; i < 2; i++)
{
//0 = in, 1 = out
//make sure events are cleared immediately in next call of update()
lastMIDIMessageDisplayTime[i] = 0;
}
}
MIDImessageRetentionTime = retentionTime;
//reset last update time
lastMIDIMessageDisplayTime[eventType_t::in] = core::timing::currentRunTimeMs();
lastMIDIMessageDisplayTime[eventType_t::out] = core::timing::currentRunTimeMs();
}
///
/// \brief Adds normalization to a given octave.
///
int8_t Display::normalizeOctave(uint8_t octave, int8_t normalization)
{
return static_cast<int8_t>(octave) + normalization;
}<commit_msg>display: show home after initialization<commit_after>/*
Copyright 2015-2020 Igor Petrovic
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 <string.h>
#include <stdio.h>
#include "Display.h"
#include "core/src/general/Timing.h"
#include "core/src/general/Helpers.h"
using namespace IO;
///
/// \brief Initialize display driver and variables.
///
bool Display::init(bool startupInfo)
{
if (initDone)
U8X8::clearDisplay();
if (database.read(Database::Section::display_t::features, static_cast<size_t>(feature_t::enable)))
{
auto controller = static_cast<U8X8::displayController_t>(database.read(Database::Section::display_t::setting, static_cast<size_t>(setting_t::controller)));
auto resolution = static_cast<U8X8::displayResolution_t>(database.read(Database::Section::display_t::setting, static_cast<size_t>(setting_t::resolution)));
if (U8X8::initDisplay(controller, resolution))
{
U8X8::setPowerSave(0);
U8X8::setFlipMode(0);
this->resolution = resolution;
U8X8::setFont(u8x8_font_pxplustandynewtv_r);
U8X8::clearDisplay();
//init char arrays
for (int i = 0; i < LCD_HEIGHT_MAX; i++)
{
for (int j = 0; j < LCD_STRING_BUFFER_SIZE - 2; j++)
{
lcdRowStillText[i][j] = ' ';
lcdRowTempText[i][j] = ' ';
}
lcdRowStillText[i][LCD_STRING_BUFFER_SIZE - 1] = '\0';
lcdRowTempText[i][LCD_STRING_BUFFER_SIZE - 1] = '\0';
scrollEvent[i].size = 0;
scrollEvent[i].startIndex = 0;
scrollEvent[i].currentIndex = 0;
scrollEvent[i].direction = scrollDirection_t::leftToRight;
}
initDone = true;
if (startupInfo)
{
setDirectWriteState(true);
if (database.read(Database::Section::display_t::features, static_cast<size_t>(feature_t::welcomeMsg)))
displayWelcomeMessage();
if (database.read(Database::Section::display_t::features, static_cast<size_t>(feature_t::vInfoMsg)))
displayVinfo(false);
setDirectWriteState(false);
}
setAlternateNoteDisplay(database.read(Database::Section::display_t::features, static_cast<size_t>(feature_t::MIDInotesAlternate)));
setRetentionTime(database.read(Database::Section::display_t::setting, static_cast<size_t>(setting_t::MIDIeventTime)) * 1000);
displayHome();
return true;
}
}
return false;
}
///
/// \brief Checks if LCD requires updating continuously.
///
bool Display::update()
{
if (!initDone)
return false;
if ((core::timing::currentRunTimeMs() - lastLCDupdateTime) < LCD_REFRESH_TIME)
return false; //we don't need to update lcd in real time
//use char pointer to point to line we're going to print
char* charPointer;
updateTempTextStatus();
for (int i = 0; i < LCD_HEIGHT_MAX; i++)
{
if (activeTextType == lcdTextType_t::still)
{
//scrolling is possible only with still text
updateScrollStatus(i);
charPointer = lcdRowStillText[i];
}
else
{
charPointer = lcdRowTempText[i];
}
if (!charChange[i])
continue;
int8_t string_len = strlen(charPointer) > LCD_WIDTH_MAX ? LCD_WIDTH_MAX : strlen(charPointer);
for (int j = 0; j < string_len; j++)
{
if (BIT_READ(charChange[i], j))
U8X8::drawGlyph(j, rowMap[resolution][i], charPointer[j + scrollEvent[i].currentIndex]);
}
//now fill remaining columns with spaces
for (int j = string_len; j < LCD_WIDTH_MAX; j++)
U8X8::drawGlyph(j, rowMap[resolution][i], ' ');
charChange[i] = 0;
}
lastLCDupdateTime = core::timing::currentRunTimeMs();
//check if midi in/out messages need to be cleared
if (MIDImessageRetentionTime)
{
for (int i = 0; i < 2; i++)
{
//0 = in, 1 = out
if ((core::timing::currentRunTimeMs() - lastMIDIMessageDisplayTime[i] > MIDImessageRetentionTime) && midiMessageDisplayed[i])
clearMIDIevent(static_cast<eventType_t>(i));
}
}
return true;
}
///
/// \brief Updates text to be shown on display.
/// This function only updates internal buffers with received text, actual updating is done in update() function.
/// Text isn't passed directly, instead, value from string builder is used.
/// @param [in] row Row which is being updated.
/// @param [in] textType Type of text to be shown on display (enumerated type). See lcdTextType_t enumeration.
/// @param [in] startIndex Index on which received text should on specified row.
///
void Display::updateText(uint8_t row, lcdTextType_t textType, uint8_t startIndex)
{
if (!initDone)
return;
const char* string = stringBuilder.string();
uint8_t size = strlen(string);
uint8_t scrollSize = 0;
if (size + startIndex >= LCD_STRING_BUFFER_SIZE - 2)
size = LCD_STRING_BUFFER_SIZE - 2 - startIndex; //trim string
if (directWriteState)
{
for (int j = 0; j < size; j++)
U8X8::drawGlyph(j + startIndex, rowMap[resolution][row], string[j]);
}
else
{
bool scrollingEnabled = false;
switch (textType)
{
case lcdTextType_t::still:
for (int i = 0; i < size; i++)
{
lcdRowStillText[row][startIndex + i] = string[i];
BIT_WRITE(charChange[row], startIndex + i, 1);
}
//scrolling is enabled only if some characters are found after LCD_WIDTH_MAX-1 index
for (int i = LCD_WIDTH_MAX; i < LCD_STRING_BUFFER_SIZE - 1; i++)
{
if ((lcdRowStillText[row][i] != ' ') && (lcdRowStillText[row][i] != '\0'))
{
scrollingEnabled = true;
scrollSize++;
}
}
if (scrollingEnabled && !scrollEvent[row].size)
{
//enable scrolling
scrollEvent[row].size = scrollSize;
scrollEvent[row].startIndex = startIndex;
scrollEvent[row].currentIndex = 0;
scrollEvent[row].direction = scrollDirection_t::leftToRight;
lastScrollTime = core::timing::currentRunTimeMs();
}
else if (!scrollingEnabled && scrollEvent[row].size)
{
scrollEvent[row].size = 0;
scrollEvent[row].startIndex = 0;
scrollEvent[row].currentIndex = 0;
scrollEvent[row].direction = scrollDirection_t::leftToRight;
}
break;
case lcdTextType_t::temp:
//clear entire message first
for (int j = 0; j < LCD_WIDTH_MAX - 2; j++)
lcdRowTempText[row][j] = ' ';
lcdRowTempText[row][LCD_WIDTH_MAX - 1] = '\0';
for (int i = 0; i < size; i++)
lcdRowTempText[row][startIndex + i] = string[i];
//make sure message is properly EOL'ed
lcdRowTempText[row][startIndex + size] = '\0';
activeTextType = lcdTextType_t::temp;
messageDisplayTime = core::timing::currentRunTimeMs();
//update all characters on display
for (int i = 0; i < LCD_HEIGHT_MAX; i++)
charChange[i] = static_cast<uint32_t>(0xFFFFFFFF);
break;
default:
return;
}
}
}
///
/// \brief Enables or disables direct writing to LCD.
/// When enabled, low-level APIs are used to write text to LCD directly.
/// Otherwise, update() function takes care of updating LCD.
/// @param [in] state New direct write state.
///
void Display::setDirectWriteState(bool state)
{
directWriteState = state;
}
///
/// \brief Calculates position on which text needs to be set on display to be in center of display row.
/// @param [in] textSize Size of text for which center position on display is being calculated.
/// \returns Center position of text on display.
///
uint8_t Display::getTextCenter(uint8_t textSize)
{
return U8X8::getColumns() / 2 - (textSize / 2);
}
///
/// \brief Updates status of temp text on display.
///
void Display::updateTempTextStatus()
{
if (activeTextType == lcdTextType_t::temp)
{
//temp text - check if temp text should be removed
if ((core::timing::currentRunTimeMs() - messageDisplayTime) > LCD_MESSAGE_DURATION)
{
activeTextType = lcdTextType_t::still;
//make sure all characters are updated once temp text is removed
for (int j = 0; j < LCD_HEIGHT_MAX; j++)
charChange[j] = static_cast<uint32_t>(0xFFFFFFFF);
}
}
}
///
/// \brief Updates status of scrolling text on display.
/// @param [in] row Row which is being checked.
///
void Display::updateScrollStatus(uint8_t row)
{
if (!scrollEvent[row].size)
return;
if ((core::timing::currentRunTimeMs() - lastScrollTime) < LCD_SCROLL_TIME)
return;
switch (scrollEvent[row].direction)
{
case scrollDirection_t::leftToRight:
//left to right
scrollEvent[row].currentIndex++;
if (scrollEvent[row].currentIndex == scrollEvent[row].size)
{
//switch direction
scrollEvent[row].direction = scrollDirection_t::rightToLeft;
}
break;
case scrollDirection_t::rightToLeft:
//right to left
scrollEvent[row].currentIndex--;
if (scrollEvent[row].currentIndex == 0)
{
//switch direction
scrollEvent[row].direction = scrollDirection_t::leftToRight;
}
break;
}
for (int i = scrollEvent[row].startIndex; i < LCD_WIDTH_MAX; i++)
BIT_WRITE(charChange[row], i, 1);
lastScrollTime = core::timing::currentRunTimeMs();
}
///
/// \brief Checks for currently active text type on display.
/// \returns Active text type (enumerated type). See lcdTextType_t enumeration.
///
Display::lcdTextType_t Display::getActiveTextType()
{
return activeTextType;
}
///
/// \brief Sets new message retention time.
/// @param [in] retentionTime New retention time in milliseconds.
///
void Display::setRetentionTime(uint32_t retentionTime)
{
if (retentionTime < MIDImessageRetentionTime)
{
for (int i = 0; i < 2; i++)
{
//0 = in, 1 = out
//make sure events are cleared immediately in next call of update()
lastMIDIMessageDisplayTime[i] = 0;
}
}
MIDImessageRetentionTime = retentionTime;
//reset last update time
lastMIDIMessageDisplayTime[eventType_t::in] = core::timing::currentRunTimeMs();
lastMIDIMessageDisplayTime[eventType_t::out] = core::timing::currentRunTimeMs();
}
///
/// \brief Adds normalization to a given octave.
///
int8_t Display::normalizeOctave(uint8_t octave, int8_t normalization)
{
return static_cast<int8_t>(octave) + normalization;
}<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
int main() {
int x, y, z;
cin >> x >> y >> z;
if (x > y) {
if (x > z) {
cout << x;
}
} else {
if (y > z) {
cout << y;
} else { cout << z; }
}
return 0;
}
<commit_msg>fixed<commit_after>#include <iostream>
using namespace std;
int main() {
int x, y, z;
cin >> x >> y >> z;
if (x > y) {
if (x > z) {
cout << x;
}
} else {
if (y > z) {
cout << y;
} else {
cout << z;
}
}
return 0;
}
<|endoftext|> |
<commit_before>// Time: O(k)
// Space: O(1)
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
/*
* @param k: The number k.
* @return: The kth prime number as description.
*/
long long kthPrimeNumber(int k) {
long long ugly_number = 0;
priority_queue<long long , vector<long long >, greater<long long >> heap;
heap.emplace(3);
heap.emplace(5);
heap.emplace(7);
for (int i = 0; i < k; ++i) {
if (heap.top() % 3 == 0) {
ugly_number = heap.top();
heap.pop();
heap.emplace(ugly_number * 3);
}
else if (heap.top() % 5 == 0) {
ugly_number = heap.top();
heap.pop();
heap.emplace(ugly_number * 3);
heap.emplace(ugly_number * 5);
}
else {
ugly_number = heap.top();
heap.pop();
heap.emplace(ugly_number * 3);
heap.emplace(ugly_number * 5);
heap.emplace(ugly_number * 7);
}
}
return ugly_number;
}
};
<commit_msg>Update ugly-number.cpp<commit_after>// Time: O(k)
// Space: O(1)
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
/*
* @param k: The number k.
* @return: The kth prime number as description.
*/
long long kthPrimeNumber(int k) {
long long ugly_number = 0;
priority_queue<long long, vector<long long>, greater<long long>> heap;
heap.emplace(3);
heap.emplace(5);
heap.emplace(7);
for (int i = 0; i < k; ++i) {
if (heap.top() % 3 == 0) {
ugly_number = heap.top();
heap.pop();
heap.emplace(ugly_number * 3);
}
else if (heap.top() % 5 == 0) {
ugly_number = heap.top();
heap.pop();
heap.emplace(ugly_number * 3);
heap.emplace(ugly_number * 5);
}
else {
ugly_number = heap.top();
heap.pop();
heap.emplace(ugly_number * 3);
heap.emplace(ugly_number * 5);
heap.emplace(ugly_number * 7);
}
}
return ugly_number;
}
};
<|endoftext|> |
<commit_before>// Time: O(k)
// Space: O(1)
// Heap solution.
class Solution {
public:
/*
* @param k: The number k.
* @return: The kth prime number as description.
*/
long long kthPrimeNumber(int k) {
long long ugly_number = 0;
priority_queue<long long, vector<long long>, greater<long long>> heap;
heap.emplace(1);
for (int i = 0; i <= k; ++i) {
ugly_number = heap.top();
heap.pop();
if (ugly_number % 3 == 0) {
heap.emplace(ugly_number * 3);
} else if (ugly_number % 5 == 0) {
heap.emplace(ugly_number * 3);
heap.emplace(ugly_number * 5);
} else {
heap.emplace(ugly_number * 3);
heap.emplace(ugly_number * 5);
heap.emplace(ugly_number * 7);
}
}
return ugly_number;
}
};
// BST solution.
class Solution2 {
public:
/*
* @param k: The number k.
* @return: The kth prime number as description.
*/
long long kthPrimeNumber(int k) {
long long ugly_number = 0;
set<long long> bst;
bst.emplace(1);
for (int i = 0; i <= k; ++i) {
ugly_number = *bst.cbegin();
bst.erase(bst.cbegin());
if (ugly_number % 3 == 0) {
bst.emplace(ugly_number * 3);
} else if (ugly_number % 5 == 0) {
bst.emplace(ugly_number * 3);
bst.emplace(ugly_number * 5);
} else {
bst.emplace(ugly_number * 3);
bst.emplace(ugly_number * 5);
bst.emplace(ugly_number * 7);
}
}
return ugly_number;
}
};
// Time: O(k)
// Space: O(k)
// DP solution.
class Solution3 {
public:
/*
* @param k: The number k.
* @return: The kth prime number as description.
*/
long long kthPrimeNumber(int k) {
vector<long long> uglies{1};
long long f3 = 3, f5 = 5, f7 = 7;
int idx3 = 0, idx5 = 0, idx7 = 0;
while (uglies.size() <= k) {
long long min_val = min(min(f3, f5), f7);
uglies.emplace_back(min_val);
if (min_val == f3) {
f3 = 3 * uglies[++idx3];
}
if (min_val == f5) {
f5 = 5 * uglies[++idx5];
}
if (min_val == f7) {
f7 = 7 * uglies[++idx7];
}
}
return uglies[k];
}
};
<commit_msg>Update ugly-number.cpp<commit_after>// Time: O(k)
// Space: O(1)
// Heap solution.
class Solution {
public:
/*
* @param k: The number k.
* @return: The kth prime number as description.
*/
long long kthPrimeNumber(int k) {
long long ugly_number = 0;
priority_queue<long long, vector<long long>, greater<long long>> heap;
heap.emplace(1);
for (int i = 0; i <= k; ++i) {
ugly_number = heap.top();
heap.pop();
if (ugly_number % 3 == 0) {
heap.emplace(ugly_number * 3);
} else if (ugly_number % 5 == 0) {
heap.emplace(ugly_number * 3);
heap.emplace(ugly_number * 5);
} else {
heap.emplace(ugly_number * 3);
heap.emplace(ugly_number * 5);
heap.emplace(ugly_number * 7);
}
}
return ugly_number;
}
};
// BST solution.
class Solution2 {
public:
/*
* @param k: The number k.
* @return: The kth prime number as description.
*/
long long kthPrimeNumber(int k) {
long long ugly_number = 0;
set<long long> bst;
bst.emplace(1);
for (int i = 0; i <= k; ++i) {
ugly_number = *bst.cbegin();
bst.erase(bst.cbegin());
if (ugly_number % 3 == 0) {
bst.emplace(ugly_number * 3);
} else if (ugly_number % 5 == 0) {
bst.emplace(ugly_number * 3);
bst.emplace(ugly_number * 5);
} else {
bst.emplace(ugly_number * 3);
bst.emplace(ugly_number * 5);
bst.emplace(ugly_number * 7);
}
}
return ugly_number;
}
};
// Time: O(k)
// Space: O(k)
// DP solution.
class Solution3 {
public:
/*
* @param k: The number k.
* @return: The kth prime number as description.
*/
long long kthPrimeNumber(int k) {
vector<long long> uglies(k + 1);
uglies[0] = 1;
long long f3 = 3, f5 = 5, f7 = 7;
int idx3 = 0, idx5 = 0, idx7 = 0;
for (int i = 1; i < k; ++i) {
long long min_val = min(min(f3, f5), f7);
uglies[i] = min_val;
if (min_val == f3) {
f3 = 3 * uglies[++idx3];
}
if (min_val == f5) {
f5 = 5 * uglies[++idx5];
}
if (min_val == f7) {
f7 = 7 * uglies[++idx7];
}
}
return uglies[k];
}
};
<|endoftext|> |
<commit_before>/**
* \file
*/
#pragma once
#include "detail/socket.hpp"
#include <boost/asio/io_service.hpp>
#include <boost/optional.hpp>
#include <boost/system/error_code.hpp>
#include <libpq-fe.h>
#include <mpark/variant.hpp>
#include <cassert>
namespace asio_pq {
/**
* An RAII wrapper for a pointer to a
* `PGconn`.
*/
class connection {
private:
PGconn * conn_;
boost::asio::io_service * ios_;
boost::optional<detail::socket_variant_type> socket_;
void destroy () noexcept;
void check () const;
public:
connection () = delete;
connection (const connection &) = delete;
connection (connection &&) noexcept;
connection & operator = (const connection &) = delete;
connection & operator = (connection &&) noexcept;
/**
* Creates a new connection which manages a
* particular pointer.
*
* \param [in] ios
* The `boost::asio::io_service` which shall be
* used to dispatch asynchronous operations for
* the associated connection.
* \param [in] conn
* The connection handle to manage.
*/
connection (boost::asio::io_service & ios, PGconn * conn) noexcept;
/**
* Creates a new connection which manages a
* libpq connection handle created by calling
* `PGconnectStart`.
*
* \param [in] ios
* The `boost::asio::io_service` which shall be
* used to dispatch asynchronous operations for
* the associated connection.
* \param [in] conninfo
* See the libpq manual entry for `PGconnectStart`.
*/
explicit connection (boost::asio::io_service & ios, const char * conninfo);
/**
* Creates a new connection which manages a
* libpq connection handle created by calling
* `PGconnectStartParams`.
*
* \param [in] ios
* The `boost::asio::io_service` which shall be
* used to dispatch asynchronous operations for
* the associated connection.
* \param [in] keywords
* See the libpq manual entry for `PQconnectStartParams`.
* \param [in] values
* See the libpq manual entry for `PQconnectStartParams`.
* \param [in] expand_dbname
* See the libpq manual entry for `PQconnectStartParams`.
*/
connection (boost::asio::io_service & ios, const char * const * keywords, const char * const * values, bool expand_dbname);
/**
* Destroys the managed handle (if any).
*/
~connection () noexcept;
/**
* Retrieves the managed handle and surrenders
* ownership thereof (i.e. if the destructor of
* this object is later called the once-managed
* handle will not be destroyed).
*
* \return
* The managed handle (if any).
*/
PGconn * release () noexcept;
/**
* Retrieves the managed handle.
*
* \return
* The managed handle (if any).
*/
PGconn * get () const noexcept;
/**
* Retrieves the managed handle.
*
* \return
* The managed handle (if any).
*/
operator PGconn * () const noexcept;
/**
* Retrieves the `boost::asio::io_service` associated
* with this object.
*
* \return
* A reference to a `boost::asio::io_service`.
*/
boost::asio::io_service & get_io_service () const noexcept;
boost::system::error_code duplicate_socket ();
template <typename Handler>
decltype(auto) socket (Handler h) {
assert(socket_);
return mpark::visit(h, *socket_);
}
bool has_socket () const noexcept;
void cancel (boost::system::error_code &) noexcept;
};
}
<commit_msg>asio_pq::connection - Hide Detail Methods from Documentation<commit_after>/**
* \file
*/
#pragma once
#include "detail/socket.hpp"
#include <boost/asio/io_service.hpp>
#include <boost/optional.hpp>
#include <boost/system/error_code.hpp>
#include <libpq-fe.h>
#include <mpark/variant.hpp>
#include <cassert>
namespace asio_pq {
/**
* An RAII wrapper for a pointer to a
* `PGconn`.
*/
class connection {
private:
PGconn * conn_;
boost::asio::io_service * ios_;
boost::optional<detail::socket_variant_type> socket_;
void destroy () noexcept;
void check () const;
public:
connection () = delete;
connection (const connection &) = delete;
connection (connection &&) noexcept;
connection & operator = (const connection &) = delete;
connection & operator = (connection &&) noexcept;
/**
* Creates a new connection which manages a
* particular pointer.
*
* \param [in] ios
* The `boost::asio::io_service` which shall be
* used to dispatch asynchronous operations for
* the associated connection.
* \param [in] conn
* The connection handle to manage.
*/
connection (boost::asio::io_service & ios, PGconn * conn) noexcept;
/**
* Creates a new connection which manages a
* libpq connection handle created by calling
* `PGconnectStart`.
*
* \param [in] ios
* The `boost::asio::io_service` which shall be
* used to dispatch asynchronous operations for
* the associated connection.
* \param [in] conninfo
* See the libpq manual entry for `PGconnectStart`.
*/
explicit connection (boost::asio::io_service & ios, const char * conninfo);
/**
* Creates a new connection which manages a
* libpq connection handle created by calling
* `PGconnectStartParams`.
*
* \param [in] ios
* The `boost::asio::io_service` which shall be
* used to dispatch asynchronous operations for
* the associated connection.
* \param [in] keywords
* See the libpq manual entry for `PQconnectStartParams`.
* \param [in] values
* See the libpq manual entry for `PQconnectStartParams`.
* \param [in] expand_dbname
* See the libpq manual entry for `PQconnectStartParams`.
*/
connection (boost::asio::io_service & ios, const char * const * keywords, const char * const * values, bool expand_dbname);
/**
* Destroys the managed handle (if any).
*/
~connection () noexcept;
/**
* Retrieves the managed handle and surrenders
* ownership thereof (i.e. if the destructor of
* this object is later called the once-managed
* handle will not be destroyed).
*
* \return
* The managed handle (if any).
*/
PGconn * release () noexcept;
/**
* Retrieves the managed handle.
*
* \return
* The managed handle (if any).
*/
PGconn * get () const noexcept;
/**
* Retrieves the managed handle.
*
* \return
* The managed handle (if any).
*/
operator PGconn * () const noexcept;
/**
* Retrieves the `boost::asio::io_service` associated
* with this object.
*
* \return
* A reference to a `boost::asio::io_service`.
*/
boost::asio::io_service & get_io_service () const noexcept;
/**
* \cond
*/
boost::system::error_code duplicate_socket ();
template <typename Handler>
decltype(auto) socket (Handler h) {
assert(socket_);
return mpark::visit(h, *socket_);
}
bool has_socket () const noexcept;
void cancel (boost::system::error_code &) noexcept;
/**
* \endcond
*/
};
}
<|endoftext|> |
<commit_before><commit_msg>Fix an elusive crash in LLDBMemoryReader::readBytes().<commit_after><|endoftext|> |
<commit_before>/* Copyright © 2001-2017, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "line_reports_api.h"
#include "utils/paginate.h"
namespace bt = boost::posix_time;
namespace nt = navitia::type;
namespace navitia {
namespace disruption {
struct LineReport {
const nt::Line* line;
std::vector<const nt::Network*> networks;
std::vector<const nt::Route*> routes;
std::vector<const nt::StopArea*> stop_areas;
std::vector<const nt::StopPoint*> stop_points;
LineReport(const nt::Line* line,
const std::string& filter,
const std::vector<std::string>& forbidden_uris,
const type::Data& d,
const boost::posix_time::ptime now,
const boost::posix_time::time_period& filter_period)
: line(line) {
add_objects(filter, forbidden_uris, d, now, filter_period, networks);
add_objects(filter, forbidden_uris, d, now, filter_period, routes);
add_objects(filter, forbidden_uris, d, now, filter_period, stop_areas);
add_objects(filter, forbidden_uris, d, now, filter_period, stop_points);
}
template <typename T>
void add_objects(const std::string& filter,
const std::vector<std::string>& forbidden_uris,
const type::Data& d,
const boost::posix_time::ptime now,
const boost::posix_time::time_period& filter_period,
std::vector<const T*>& objects) {
std::string new_filter = "line.uri=" + line->uri;
if (!filter.empty()) {
new_filter += " and " + filter;
}
type::Indexes indices;
try {
indices = ptref::make_query(nt::get_type_e<T>(), new_filter, forbidden_uris, d);
} catch (const std::exception&) {
}
for (const auto& idx : indices) {
const auto* obj = d.pt_data->collection<T>()[idx];
if (obj->has_applicable_message(now, filter_period, line)) {
objects.push_back(obj);
}
}
}
bool has_disruption(const boost::posix_time::ptime& current_time,
const boost::posix_time::time_period& filter_peiod) const {
return line->has_applicable_message(current_time, filter_peiod) || !networks.empty() || !routes.empty()
|| !stop_areas.empty() || !stop_points.empty();
}
void to_pb(navitia::PbCreator& pb_creator, const size_t depth) const {
const auto with_line_sections = DumpMessageOptions{DumpMessage::Yes, DumpLineSectionMessage::Yes};
auto* report = pb_creator.add_line_reports();
pb_creator.fill(line, report->mutable_line(), depth - 1, with_line_sections);
if (line->has_applicable_message(pb_creator.now, pb_creator.action_period)) {
pb_creator.fill(line, report->add_pt_objects(), 0);
}
pb_creator.fill(networks, report->mutable_pt_objects(), 0);
pb_creator.fill(routes, report->mutable_pt_objects(), 0);
pb_creator.fill(stop_areas, report->mutable_pt_objects(), 0);
pb_creator.fill(stop_points, report->mutable_pt_objects(), 0, with_line_sections);
}
nt::UrisList all_uris() const {
nt::UrisList uris;
uris.insert(line->uri);
for (auto& network : networks) {
uris.insert(network->uri);
}
for (auto& route : routes) {
uris.insert(route->uri);
}
for (auto& stop_area : stop_areas) {
uris.insert(stop_area->uri);
}
for (auto& stop_point : stop_points) {
uris.insert(stop_point->uri);
}
return uris;
}
};
void filter_excess_impacts_in_uri_filtering_mode(const std::string& filter,
navitia::PbCreator& pb_creator,
const std::vector<LineReport>& line_reports) {
if (!filter.empty()) {
nt::UrisList line_report_uris;
for (auto& line_report : line_reports) {
auto uris = line_report.all_uris();
line_report_uris.insert(uris.cbegin(), uris.cend());
}
auto erase_allowed = [](const nt::UrisList& uris, const nt::UrisList& impacted_uris) -> bool {
for (const auto& impacted_uri : impacted_uris) {
if (std::find(uris.cbegin(), uris.cend(), impacted_uri) == uris.cend()) {
return true;
}
}
return false;
};
// Clean impacts if needed
for (auto it = pb_creator.impacts.begin(); it != pb_creator.impacts.end();) {
if (erase_allowed(line_report_uris, (*it).get()->informed_entities_uris())) {
it = pb_creator.impacts.erase(it);
} else {
++it;
}
}
}
}
void line_reports(navitia::PbCreator& pb_creator,
const navitia::type::Data& d,
const size_t depth,
size_t count,
size_t start_page,
const std::string& filter,
const std::vector<std::string>& forbidden_uris,
const boost::optional<boost::posix_time::ptime>& since,
const boost::optional<boost::posix_time::ptime>& until) {
const auto start = get_optional_value_or(since, bt::ptime(bt::neg_infin));
const auto end = get_optional_value_or(until, bt::ptime(bt::pos_infin));
pb_creator.action_period = bt::time_period(start, end);
if (end < start) {
pb_creator.fill_pb_error(pbnavitia::Error::unable_to_parse, "invalid filtering period (since > until)");
return;
}
type::Indexes line_indices;
try {
line_indices = ptref::make_query(type::Type_e::Line, filter, forbidden_uris, d);
} catch (const ptref::parsing_error& parse_error) {
pb_creator.fill_pb_error(pbnavitia::Error::unable_to_parse, "Unable to parse filter" + parse_error.more);
return;
} catch (const ptref::ptref_error& ptref_error) {
pb_creator.fill_pb_error(pbnavitia::Error::bad_filter, "ptref : " + ptref_error.more);
return;
}
std::vector<LineReport> line_reports;
for (auto idx : line_indices) {
auto line_report =
LineReport(d.pt_data->lines[idx], filter, forbidden_uris, d, pb_creator.now, pb_creator.action_period);
if (line_report.has_disruption(pb_creator.now, pb_creator.action_period)) {
line_reports.push_back(line_report);
}
}
const auto total_results = line_reports.size();
std::vector<LineReport> paged_line_reports = paginate(line_reports, count, start_page);
for (const auto& line_report : paged_line_reports) {
line_report.to_pb(pb_creator, depth);
}
filter_excess_impacts_in_uri_filtering_mode(filter, pb_creator, line_reports);
pb_creator.make_paginate(total_results, start_page, count, pb_creator.line_reports_size());
if (pb_creator.line_reports_size() == 0) {
pb_creator.fill_pb_error(pbnavitia::Error::no_solution, pbnavitia::NO_SOLUTION, "no result for this request");
}
}
} // namespace disruption
} // namespace navitia
<commit_msg>use set_intersection<commit_after>/* Copyright © 2001-2017, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "line_reports_api.h"
#include "utils/paginate.h"
#include <boost/range/algorithm.hpp>
#include <iterator>
namespace bt = boost::posix_time;
namespace nt = navitia::type;
namespace navitia {
namespace disruption {
struct LineReport {
const nt::Line* line;
std::vector<const nt::Network*> networks;
std::vector<const nt::Route*> routes;
std::vector<const nt::StopArea*> stop_areas;
std::vector<const nt::StopPoint*> stop_points;
LineReport(const nt::Line* line,
const std::string& filter,
const std::vector<std::string>& forbidden_uris,
const type::Data& d,
const boost::posix_time::ptime now,
const boost::posix_time::time_period& filter_period)
: line(line) {
add_objects(filter, forbidden_uris, d, now, filter_period, networks);
add_objects(filter, forbidden_uris, d, now, filter_period, routes);
add_objects(filter, forbidden_uris, d, now, filter_period, stop_areas);
add_objects(filter, forbidden_uris, d, now, filter_period, stop_points);
}
template <typename T>
void add_objects(const std::string& filter,
const std::vector<std::string>& forbidden_uris,
const type::Data& d,
const boost::posix_time::ptime now,
const boost::posix_time::time_period& filter_period,
std::vector<const T*>& objects) {
std::string new_filter = "line.uri=" + line->uri;
if (!filter.empty()) {
new_filter += " and " + filter;
}
type::Indexes indices;
try {
indices = ptref::make_query(nt::get_type_e<T>(), new_filter, forbidden_uris, d);
} catch (const std::exception&) {
}
for (const auto& idx : indices) {
const auto* obj = d.pt_data->collection<T>()[idx];
if (obj->has_applicable_message(now, filter_period, line)) {
objects.push_back(obj);
}
}
}
bool has_disruption(const boost::posix_time::ptime& current_time,
const boost::posix_time::time_period& filter_peiod) const {
return line->has_applicable_message(current_time, filter_peiod) || !networks.empty() || !routes.empty()
|| !stop_areas.empty() || !stop_points.empty();
}
void to_pb(navitia::PbCreator& pb_creator, const size_t depth) const {
const auto with_line_sections = DumpMessageOptions{DumpMessage::Yes, DumpLineSectionMessage::Yes};
auto* report = pb_creator.add_line_reports();
pb_creator.fill(line, report->mutable_line(), depth - 1, with_line_sections);
if (line->has_applicable_message(pb_creator.now, pb_creator.action_period)) {
pb_creator.fill(line, report->add_pt_objects(), 0);
}
pb_creator.fill(networks, report->mutable_pt_objects(), 0);
pb_creator.fill(routes, report->mutable_pt_objects(), 0);
pb_creator.fill(stop_areas, report->mutable_pt_objects(), 0);
pb_creator.fill(stop_points, report->mutable_pt_objects(), 0, with_line_sections);
}
nt::UrisList all_uris() const {
nt::UrisList uris;
uris.insert(line->uri);
for (auto& network : networks) {
uris.insert(network->uri);
}
for (auto& route : routes) {
uris.insert(route->uri);
}
for (auto& stop_area : stop_areas) {
uris.insert(stop_area->uri);
}
for (auto& stop_point : stop_points) {
uris.insert(stop_point->uri);
}
return uris;
}
};
void filter_excess_impacts_in_uri_filtering_mode(const std::string& filter,
navitia::PbCreator& pb_creator,
const std::vector<LineReport>& line_reports) {
if (!filter.empty()) {
nt::UrisList line_report_uris;
for (auto& line_report : line_reports) {
auto uris = line_report.all_uris();
line_report_uris.insert(uris.cbegin(), uris.cend());
}
auto erase_allowed = [](const nt::UrisList& uris, const nt::UrisList& impacted_uris) -> bool {
std::vector<std::string> intersect;
boost::range::set_intersection(uris, impacted_uris, std::back_inserter(intersect));
return intersect.size() == 0;
};
// Clean impacts if needed
for (auto it = pb_creator.impacts.begin(); it != pb_creator.impacts.end();) {
if (erase_allowed(line_report_uris, (*it).get()->informed_entities_uris())) {
it = pb_creator.impacts.erase(it);
} else {
++it;
}
}
}
}
void line_reports(navitia::PbCreator& pb_creator,
const navitia::type::Data& d,
const size_t depth,
size_t count,
size_t start_page,
const std::string& filter,
const std::vector<std::string>& forbidden_uris,
const boost::optional<boost::posix_time::ptime>& since,
const boost::optional<boost::posix_time::ptime>& until) {
const auto start = get_optional_value_or(since, bt::ptime(bt::neg_infin));
const auto end = get_optional_value_or(until, bt::ptime(bt::pos_infin));
pb_creator.action_period = bt::time_period(start, end);
if (end < start) {
pb_creator.fill_pb_error(pbnavitia::Error::unable_to_parse, "invalid filtering period (since > until)");
return;
}
type::Indexes line_indices;
try {
line_indices = ptref::make_query(type::Type_e::Line, filter, forbidden_uris, d);
} catch (const ptref::parsing_error& parse_error) {
pb_creator.fill_pb_error(pbnavitia::Error::unable_to_parse, "Unable to parse filter" + parse_error.more);
return;
} catch (const ptref::ptref_error& ptref_error) {
pb_creator.fill_pb_error(pbnavitia::Error::bad_filter, "ptref : " + ptref_error.more);
return;
}
std::vector<LineReport> line_reports;
for (auto idx : line_indices) {
auto line_report =
LineReport(d.pt_data->lines[idx], filter, forbidden_uris, d, pb_creator.now, pb_creator.action_period);
if (line_report.has_disruption(pb_creator.now, pb_creator.action_period)) {
line_reports.push_back(line_report);
}
}
const auto total_results = line_reports.size();
std::vector<LineReport> paged_line_reports = paginate(line_reports, count, start_page);
for (const auto& line_report : paged_line_reports) {
line_report.to_pb(pb_creator, depth);
}
filter_excess_impacts_in_uri_filtering_mode(filter, pb_creator, line_reports);
pb_creator.make_paginate(total_results, start_page, count, pb_creator.line_reports_size());
if (pb_creator.line_reports_size() == 0) {
pb_creator.fill_pb_error(pbnavitia::Error::no_solution, pbnavitia::NO_SOLUTION, "no result for this request");
}
}
} // namespace disruption
} // namespace navitia
<|endoftext|> |
<commit_before>/*
This file is part of Magnum.
Original authors — credit is appreciated but not required:
2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 —
Vladimír Vondruš <mosra@centrum.cz>
2018 — ShaddyAQN <ShaddyAQN@gmail.com>
2018 — Jonathan Hale <squareys@googlemail.com>
2018 — Tomáš Skřivan <skrivantomas@seznam.cz>
2018 — Natesh Narain <nnaraindev@gmail.com>
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute
this software, either in source code form or as a compiled binary, for any
purpose, commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of
this software dedicate any and all copyright interest in the software to
the public domain. We make this dedication for the benefit of the public
at large and to the detriment of our heirs and successors. We intend this
dedication to be an overt act of relinquishment in perpetuity of all
present and future rights to this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <imgui.h>
#include <Magnum/Math/Color.h>
#include <Magnum/GL/DefaultFramebuffer.h>
#include <Magnum/GL/Renderer.h>
#include <Magnum/ImGuiIntegration/Context.hpp>
#ifdef CORRADE_TARGET_ANDROID
#include <Magnum/Platform/AndroidApplication.h>
#elif defined(CORRADE_TARGET_EMSCRIPTEN)
#include <Magnum/Platform/EmscriptenApplication.h>
#else
#include <Magnum/Platform/Sdl2Application.h>
#endif
namespace Magnum { namespace Examples {
using namespace Math::Literals;
class ImGuiExample: public Platform::Application {
public:
explicit ImGuiExample(const Arguments& arguments);
void drawEvent() override;
void viewportEvent(ViewportEvent& event) override;
void keyPressEvent(KeyEvent& event) override;
void keyReleaseEvent(KeyEvent& event) override;
void mousePressEvent(MouseEvent& event) override;
void mouseReleaseEvent(MouseEvent& event) override;
void mouseMoveEvent(MouseMoveEvent& event) override;
void mouseScrollEvent(MouseScrollEvent& event) override;
void textInputEvent(TextInputEvent& event) override;
private:
ImGuiIntegration::Context _imgui{NoCreate};
bool _showTestWindow = true;
bool _showAnotherWindow = false;
Color4 _clearColor = 0x72909aff_rgbaf;
Float _floatValue = 0.0f;
};
ImGuiExample::ImGuiExample(const Arguments& arguments): Platform::Application{arguments,
Configuration{}.setTitle("Magnum ImGui Example")
.setWindowFlags(Configuration::WindowFlag::Resizable)}
{
_imgui = ImGuiIntegration::Context(Vector2{windowSize()}/dpiScaling(),
windowSize(), framebufferSize());
/* Set up proper blending to be used by ImGui. There's a great chance
you'll need this exact behavior for the rest of your scene. If not, set
this only for the drawFrame() call. */
GL::Renderer::setBlendEquation(GL::Renderer::BlendEquation::Add,
GL::Renderer::BlendEquation::Add);
GL::Renderer::setBlendFunction(GL::Renderer::BlendFunction::SourceAlpha,
GL::Renderer::BlendFunction::OneMinusSourceAlpha);
#if !defined(MAGNUM_TARGET_WEBGL) && !defined(CORRADE_TARGET_ANDROID)
/* Have some sane speed, please */
setMinimalLoopPeriod(16);
#endif
}
void ImGuiExample::drawEvent() {
GL::defaultFramebuffer.clear(GL::FramebufferClear::Color);
_imgui.newFrame();
/* Enable text input, if needed */
if(ImGui::GetIO().WantTextInput && !isTextInputActive())
startTextInput();
else if(!ImGui::GetIO().WantTextInput && isTextInputActive())
stopTextInput();
/* 1. Show a simple window.
Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appear in
a window called "Debug" automatically */
{
ImGui::Text("Hello, world!");
ImGui::SliderFloat("Float", &_floatValue, 0.0f, 1.0f);
if(ImGui::ColorEdit3("Clear Color", _clearColor.data()))
GL::Renderer::setClearColor(_clearColor);
if(ImGui::Button("Test Window"))
_showTestWindow ^= true;
if(ImGui::Button("Another Window"))
_showAnotherWindow ^= true;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)",
1000.0/Double(ImGui::GetIO().Framerate), Double(ImGui::GetIO().Framerate));
}
/* 2. Show another simple window, now using an explicit Begin/End pair */
if(_showAnotherWindow) {
ImGui::SetNextWindowSize(ImVec2(500, 100), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Another Window", &_showAnotherWindow);
ImGui::Text("Hello");
ImGui::End();
}
/* 3. Show the ImGui test window. Most of the sample code is in
ImGui::ShowTestWindow() */
if(_showTestWindow) {
ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
ImGui::ShowTestWindow();
}
/* Set appropriate states. If you only draw imgui UI, it is sufficient to
do this once in the constructor. */
GL::Renderer::enable(GL::Renderer::Feature::Blending);
GL::Renderer::disable(GL::Renderer::Feature::FaceCulling);
GL::Renderer::disable(GL::Renderer::Feature::DepthTest);
GL::Renderer::enable(GL::Renderer::Feature::ScissorTest);
_imgui.drawFrame();
/* Reset state. Only needed if you want to draw something else with
different state next frame. */
GL::Renderer::disable(GL::Renderer::Feature::ScissorTest);
GL::Renderer::enable(GL::Renderer::Feature::DepthTest);
GL::Renderer::enable(GL::Renderer::Feature::FaceCulling);
GL::Renderer::disable(GL::Renderer::Feature::Blending);
swapBuffers();
redraw();
}
void ImGuiExample::viewportEvent(ViewportEvent& event) {
GL::defaultFramebuffer.setViewport({{}, event.framebufferSize()});
_imgui.relayout(Vector2{event.windowSize()}/event.dpiScaling(),
event.windowSize(), event.framebufferSize());
}
void ImGuiExample::keyPressEvent(KeyEvent& event) {
if(_imgui.handleKeyPressEvent(event)) return;
}
void ImGuiExample::keyReleaseEvent(KeyEvent& event) {
if(_imgui.handleKeyReleaseEvent(event)) return;
}
void ImGuiExample::mousePressEvent(MouseEvent& event) {
if(_imgui.handleMousePressEvent(event)) return;
}
void ImGuiExample::mouseReleaseEvent(MouseEvent& event) {
if(_imgui.handleMouseReleaseEvent(event)) return;
}
void ImGuiExample::mouseMoveEvent(MouseMoveEvent& event) {
if(_imgui.handleMouseMoveEvent(event)) return;
}
void ImGuiExample::mouseScrollEvent(MouseScrollEvent& event) {
if(_imgui.handleMouseScrollEvent(event)) {
/* Prevent scrolling the page */
event.setAccepted();
return;
}
}
void ImGuiExample::textInputEvent(TextInputEvent& event) {
if(_imgui.handleTextInputEvent(event)) return;
}
}}
MAGNUM_APPLICATION_MAIN(Magnum::Examples::ImGuiExample)
<commit_msg>imgui: avoid using obsolete APIs.<commit_after>/*
This file is part of Magnum.
Original authors — credit is appreciated but not required:
2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 —
Vladimír Vondruš <mosra@centrum.cz>
2018 — ShaddyAQN <ShaddyAQN@gmail.com>
2018 — Jonathan Hale <squareys@googlemail.com>
2018 — Tomáš Skřivan <skrivantomas@seznam.cz>
2018 — Natesh Narain <nnaraindev@gmail.com>
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute
this software, either in source code form or as a compiled binary, for any
purpose, commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of
this software dedicate any and all copyright interest in the software to
the public domain. We make this dedication for the benefit of the public
at large and to the detriment of our heirs and successors. We intend this
dedication to be an overt act of relinquishment in perpetuity of all
present and future rights to this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <imgui.h>
#include <Magnum/Math/Color.h>
#include <Magnum/GL/DefaultFramebuffer.h>
#include <Magnum/GL/Renderer.h>
#include <Magnum/ImGuiIntegration/Context.hpp>
#ifdef CORRADE_TARGET_ANDROID
#include <Magnum/Platform/AndroidApplication.h>
#elif defined(CORRADE_TARGET_EMSCRIPTEN)
#include <Magnum/Platform/EmscriptenApplication.h>
#else
#include <Magnum/Platform/Sdl2Application.h>
#endif
namespace Magnum { namespace Examples {
using namespace Math::Literals;
class ImGuiExample: public Platform::Application {
public:
explicit ImGuiExample(const Arguments& arguments);
void drawEvent() override;
void viewportEvent(ViewportEvent& event) override;
void keyPressEvent(KeyEvent& event) override;
void keyReleaseEvent(KeyEvent& event) override;
void mousePressEvent(MouseEvent& event) override;
void mouseReleaseEvent(MouseEvent& event) override;
void mouseMoveEvent(MouseMoveEvent& event) override;
void mouseScrollEvent(MouseScrollEvent& event) override;
void textInputEvent(TextInputEvent& event) override;
private:
ImGuiIntegration::Context _imgui{NoCreate};
bool _showTestWindow = true;
bool _showAnotherWindow = false;
Color4 _clearColor = 0x72909aff_rgbaf;
Float _floatValue = 0.0f;
};
ImGuiExample::ImGuiExample(const Arguments& arguments): Platform::Application{arguments,
Configuration{}.setTitle("Magnum ImGui Example")
.setWindowFlags(Configuration::WindowFlag::Resizable)}
{
_imgui = ImGuiIntegration::Context(Vector2{windowSize()}/dpiScaling(),
windowSize(), framebufferSize());
/* Set up proper blending to be used by ImGui. There's a great chance
you'll need this exact behavior for the rest of your scene. If not, set
this only for the drawFrame() call. */
GL::Renderer::setBlendEquation(GL::Renderer::BlendEquation::Add,
GL::Renderer::BlendEquation::Add);
GL::Renderer::setBlendFunction(GL::Renderer::BlendFunction::SourceAlpha,
GL::Renderer::BlendFunction::OneMinusSourceAlpha);
#if !defined(MAGNUM_TARGET_WEBGL) && !defined(CORRADE_TARGET_ANDROID)
/* Have some sane speed, please */
setMinimalLoopPeriod(16);
#endif
}
void ImGuiExample::drawEvent() {
GL::defaultFramebuffer.clear(GL::FramebufferClear::Color);
_imgui.newFrame();
/* Enable text input, if needed */
if(ImGui::GetIO().WantTextInput && !isTextInputActive())
startTextInput();
else if(!ImGui::GetIO().WantTextInput && isTextInputActive())
stopTextInput();
/* 1. Show a simple window.
Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appear in
a window called "Debug" automatically */
{
ImGui::Text("Hello, world!");
ImGui::SliderFloat("Float", &_floatValue, 0.0f, 1.0f);
if(ImGui::ColorEdit3("Clear Color", _clearColor.data()))
GL::Renderer::setClearColor(_clearColor);
if(ImGui::Button("Test Window"))
_showTestWindow ^= true;
if(ImGui::Button("Another Window"))
_showAnotherWindow ^= true;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)",
1000.0/Double(ImGui::GetIO().Framerate), Double(ImGui::GetIO().Framerate));
}
/* 2. Show another simple window, now using an explicit Begin/End pair */
if(_showAnotherWindow) {
ImGui::SetNextWindowSize(ImVec2(500, 100), ImGuiCond_FirstUseEver);
ImGui::Begin("Another Window", &_showAnotherWindow);
ImGui::Text("Hello");
ImGui::End();
}
/* 3. Show the ImGui test window. Most of the sample code is in
ImGui::ShowTestWindow() */
if(_showTestWindow) {
ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver);
ImGui::ShowTestWindow();
}
/* Set appropriate states. If you only draw imgui UI, it is sufficient to
do this once in the constructor. */
GL::Renderer::enable(GL::Renderer::Feature::Blending);
GL::Renderer::disable(GL::Renderer::Feature::FaceCulling);
GL::Renderer::disable(GL::Renderer::Feature::DepthTest);
GL::Renderer::enable(GL::Renderer::Feature::ScissorTest);
_imgui.drawFrame();
/* Reset state. Only needed if you want to draw something else with
different state next frame. */
GL::Renderer::disable(GL::Renderer::Feature::ScissorTest);
GL::Renderer::enable(GL::Renderer::Feature::DepthTest);
GL::Renderer::enable(GL::Renderer::Feature::FaceCulling);
GL::Renderer::disable(GL::Renderer::Feature::Blending);
swapBuffers();
redraw();
}
void ImGuiExample::viewportEvent(ViewportEvent& event) {
GL::defaultFramebuffer.setViewport({{}, event.framebufferSize()});
_imgui.relayout(Vector2{event.windowSize()}/event.dpiScaling(),
event.windowSize(), event.framebufferSize());
}
void ImGuiExample::keyPressEvent(KeyEvent& event) {
if(_imgui.handleKeyPressEvent(event)) return;
}
void ImGuiExample::keyReleaseEvent(KeyEvent& event) {
if(_imgui.handleKeyReleaseEvent(event)) return;
}
void ImGuiExample::mousePressEvent(MouseEvent& event) {
if(_imgui.handleMousePressEvent(event)) return;
}
void ImGuiExample::mouseReleaseEvent(MouseEvent& event) {
if(_imgui.handleMouseReleaseEvent(event)) return;
}
void ImGuiExample::mouseMoveEvent(MouseMoveEvent& event) {
if(_imgui.handleMouseMoveEvent(event)) return;
}
void ImGuiExample::mouseScrollEvent(MouseScrollEvent& event) {
if(_imgui.handleMouseScrollEvent(event)) {
/* Prevent scrolling the page */
event.setAccepted();
return;
}
}
void ImGuiExample::textInputEvent(TextInputEvent& event) {
if(_imgui.handleTextInputEvent(event)) return;
}
}}
MAGNUM_APPLICATION_MAIN(Magnum::Examples::ImGuiExample)
<|endoftext|> |
<commit_before><commit_msg>QGCMapTileSet: Add new errorOccurred for Qt 5.15 builds<commit_after><|endoftext|> |
<commit_before>/*
* Software License Agreement (Apache License)
*
* Copyright (c) 2014, Southwest Research Institute
*
* 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 "yaml-cpp/yaml.h"
#include <industrial_extrinsic_cal/yaml_utils.h>
#include <industrial_extrinsic_cal/mutable_joint_state_publisher.h>
#include <iostream>
#include <fstream>
namespace industrial_extrinsic_cal
{
using std::string;
using std::vector;
MutableJointStatePublisher::MutableJointStatePublisher(ros::NodeHandle nh) : nh_(nh)
{
ros::NodeHandle pnh("~");
// get the name of the yaml file containing the mutable joints
if (!pnh.getParam("mutable_joint_state_yaml_file", yaml_file_name_))
{
ROS_ERROR("MutableJointStatePublisher, must set mutable_joint_state_yaml_file parameter for this node");
yaml_file_name_ = "default_mutable_joint_states.yaml";
}
// load the joint names and values from the yaml file
if (!loadFromYamlFile())
{
ROS_ERROR("MutableJointStatePublisher constructor can't read yaml file %s", yaml_file_name_.c_str());
}
// advertise the services for getting, setting, and storing the mutable joint values
set_server_ = nh_.advertiseService("set_mutable_joint_states", &MutableJointStatePublisher::setCallBack, this);
get_server_ = nh_.advertiseService("get_mutable_joint_states", &MutableJointStatePublisher::getCallBack, this);
store_server_ = nh_.advertiseService("store_mutable_joint_states", &MutableJointStatePublisher::storeCallBack, this);
// advertise the topic for continious publication of all the mutable joint states
int queue_size = 10;
joint_state_pub_ = nh_.advertise<sensor_msgs::JointState>("mutable_joint_states", queue_size);
if (!joint_state_pub_)
{
ROS_ERROR("ADVERTISE DID NOT RETURN A VALID PUBLISHER");
}
}
bool MutableJointStatePublisher::setCallBack(industrial_extrinsic_cal::set_mutable_joint_states::Request& req,
industrial_extrinsic_cal::set_mutable_joint_states::Response& res)
{
bool return_val = true;
for (int i = 0; i < (int)req.joint_names.size(); i++)
{
if (joints_.find(req.joint_names[i]) != joints_.end())
{
joints_[req.joint_names[i]] = req.joint_values[i];
ROS_INFO("setting %s to %lf", req.joint_names[i].c_str(), req.joint_values[i]);
}
else
{
ROS_ERROR("%s does not have joint named %s", node_name_.c_str(), req.joint_names[i].c_str());
return_val = false;
}
}
return (return_val);
}
bool MutableJointStatePublisher::getCallBack(industrial_extrinsic_cal::get_mutable_joint_states::Request& req,
industrial_extrinsic_cal::get_mutable_joint_states::Response& res)
{
bool return_val = true;
res.joint_names.clear();
res.joint_values.clear();
for (int i = 0; i < (int)req.joint_names.size(); i++)
{ // for each name asked for
if (joints_.find(req.joint_names[i]) != joints_.end())
{ // see if it can be found
res.joint_names.push_back(req.joint_names[i]); // use the asked for name in resposne
res.joint_values.push_back(joints_[req.joint_names[i]]); // use the value in the response
}
else
{ // can't be found
ROS_ERROR("%s does not have joint named %s", node_name_.c_str(), req.joint_names[i].c_str());
return_val = false;
}
}
return (return_val);
}
bool MutableJointStatePublisher::storeCallBack(industrial_extrinsic_cal::store_mutable_joint_states::Request& req,
industrial_extrinsic_cal::store_mutable_joint_states::Response& res)
{
std::string new_file_name = yaml_file_name_;
ros::NodeHandle pnh("~");
bool overwrite = false;
pnh.getParam("overwrite_mutable_values", overwrite);
if (!overwrite) new_file_name = yaml_file_name_ + "new";
std::ofstream fout(new_file_name.c_str());
YAML::Emitter yaml_emitter;
yaml_emitter << YAML::BeginMap;
for (std::map<std::string, double>::iterator it = joints_.begin(); it != joints_.end(); ++it)
{
yaml_emitter << YAML::Key << it->first.c_str() << YAML::Value << it->second;
ROS_INFO("mutable joint %s has value %lf", it->first.c_str(), it->second);
}
yaml_emitter << YAML::EndMap;
fout << yaml_emitter.c_str();
fout.close();
return (true);
}
bool MutableJointStatePublisher::loadFromYamlFile()
{
ROS_INFO_STREAM(yaml_file_name_);
// yaml file should have the followng format:
// joint0_name: <float_value0>
// joint1_name: <float_value1>
// joint2_name: <float_value2>
try
{
YAML::Node doc;
if (!yamlNodeFromFileName(yaml_file_name_, doc))
{
ROS_ERROR("Can't read yaml file %s", yaml_file_name_.c_str());
}
for (YAML_ITERATOR it = doc.begin(); it != doc.end(); ++it)
{
std::string key;
double value;
parseKeyDValue(it, key, value);
joints_[key.c_str()] = value;
}
} // end try
catch (YAML::ParserException& e)
{
ROS_ERROR("mutableJointStatePublisher: parsing joint states file");
ROS_ERROR_STREAM("Failed with exception " << e.what());
return (false);
}
if (joints_.size() == 0) ROS_ERROR("mutable_joint_state_publisher has no joints");
// output so we know they have been read in correctly
for (std::map<std::string, double>::iterator it = joints_.begin(); it != joints_.end(); ++it)
{
ROS_INFO("mutable joint %s has value %lf", it->first.c_str(), it->second);
}
return (true);
}
bool MutableJointStatePublisher::publishJointStates()
{
sensor_msgs::JointState joint_states;
joint_states.header.stamp = ros::Time::now();
joint_states.name.clear();
joint_states.position.clear();
joint_states.velocity.clear();
joint_states.effort.clear();
for (std::map<string, double>::iterator it = joints_.begin(); it != joints_.end(); ++it)
{
joint_states.name.push_back(it->first);
joint_states.position.push_back(it->second);
joint_states.velocity.push_back(0.0);
joint_states.effort.push_back(0.0);
}
joint_state_pub_.publish(joint_states);
}
} // end namespace mutable_joint_state_publisher
int main(int argc, char** argv)
{
ros::init(argc, argv, "mutable_joint_state_publisher");
ros::NodeHandle nh;
industrial_extrinsic_cal::MutableJointStatePublisher MJSP(nh);
ros::Rate loop_rate(1);
while (ros::ok())
{
MJSP.publishJointStates();
ros::spinOnce();
loop_rate.sleep();
}
}
<commit_msg>increased the publish frequency of mutable joint states to get better performance on kinfu/yak<commit_after>/*
* Software License Agreement (Apache License)
*
* Copyright (c) 2014, Southwest Research Institute
*
* 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 "yaml-cpp/yaml.h"
#include <industrial_extrinsic_cal/yaml_utils.h>
#include <industrial_extrinsic_cal/mutable_joint_state_publisher.h>
#include <iostream>
#include <fstream>
namespace industrial_extrinsic_cal
{
using std::string;
using std::vector;
MutableJointStatePublisher::MutableJointStatePublisher(ros::NodeHandle nh) : nh_(nh)
{
ros::NodeHandle pnh("~");
// get the name of the yaml file containing the mutable joints
if (!pnh.getParam("mutable_joint_state_yaml_file", yaml_file_name_))
{
ROS_ERROR("MutableJointStatePublisher, must set mutable_joint_state_yaml_file parameter for this node");
yaml_file_name_ = "default_mutable_joint_states.yaml";
}
// load the joint names and values from the yaml file
if (!loadFromYamlFile())
{
ROS_ERROR("MutableJointStatePublisher constructor can't read yaml file %s", yaml_file_name_.c_str());
}
// advertise the services for getting, setting, and storing the mutable joint values
set_server_ = nh_.advertiseService("set_mutable_joint_states", &MutableJointStatePublisher::setCallBack, this);
get_server_ = nh_.advertiseService("get_mutable_joint_states", &MutableJointStatePublisher::getCallBack, this);
store_server_ = nh_.advertiseService("store_mutable_joint_states", &MutableJointStatePublisher::storeCallBack, this);
// advertise the topic for continious publication of all the mutable joint states
int queue_size = 10;
joint_state_pub_ = nh_.advertise<sensor_msgs::JointState>("mutable_joint_states", queue_size);
if (!joint_state_pub_)
{
ROS_ERROR("ADVERTISE DID NOT RETURN A VALID PUBLISHER");
}
}
bool MutableJointStatePublisher::setCallBack(industrial_extrinsic_cal::set_mutable_joint_states::Request& req,
industrial_extrinsic_cal::set_mutable_joint_states::Response& res)
{
bool return_val = true;
for (int i = 0; i < (int)req.joint_names.size(); i++)
{
if (joints_.find(req.joint_names[i]) != joints_.end())
{
joints_[req.joint_names[i]] = req.joint_values[i];
ROS_INFO("setting %s to %lf", req.joint_names[i].c_str(), req.joint_values[i]);
}
else
{
ROS_ERROR("%s does not have joint named %s", node_name_.c_str(), req.joint_names[i].c_str());
return_val = false;
}
}
return (return_val);
}
bool MutableJointStatePublisher::getCallBack(industrial_extrinsic_cal::get_mutable_joint_states::Request& req,
industrial_extrinsic_cal::get_mutable_joint_states::Response& res)
{
bool return_val = true;
res.joint_names.clear();
res.joint_values.clear();
for (int i = 0; i < (int)req.joint_names.size(); i++)
{ // for each name asked for
if (joints_.find(req.joint_names[i]) != joints_.end())
{ // see if it can be found
res.joint_names.push_back(req.joint_names[i]); // use the asked for name in resposne
res.joint_values.push_back(joints_[req.joint_names[i]]); // use the value in the response
}
else
{ // can't be found
ROS_ERROR("%s does not have joint named %s", node_name_.c_str(), req.joint_names[i].c_str());
return_val = false;
}
}
return (return_val);
}
bool MutableJointStatePublisher::storeCallBack(industrial_extrinsic_cal::store_mutable_joint_states::Request& req,
industrial_extrinsic_cal::store_mutable_joint_states::Response& res)
{
std::string new_file_name = yaml_file_name_;
ros::NodeHandle pnh("~");
bool overwrite = false;
pnh.getParam("overwrite_mutable_values", overwrite);
if (!overwrite) new_file_name = yaml_file_name_ + "new";
std::ofstream fout(new_file_name.c_str());
YAML::Emitter yaml_emitter;
yaml_emitter << YAML::BeginMap;
for (std::map<std::string, double>::iterator it = joints_.begin(); it != joints_.end(); ++it)
{
yaml_emitter << YAML::Key << it->first.c_str() << YAML::Value << it->second;
ROS_INFO("mutable joint %s has value %lf", it->first.c_str(), it->second);
}
yaml_emitter << YAML::EndMap;
fout << yaml_emitter.c_str();
fout.close();
return (true);
}
bool MutableJointStatePublisher::loadFromYamlFile()
{
ROS_INFO_STREAM(yaml_file_name_);
// yaml file should have the followng format:
// joint0_name: <float_value0>
// joint1_name: <float_value1>
// joint2_name: <float_value2>
try
{
YAML::Node doc;
if (!yamlNodeFromFileName(yaml_file_name_, doc))
{
ROS_ERROR("Can't read yaml file %s", yaml_file_name_.c_str());
}
for (YAML_ITERATOR it = doc.begin(); it != doc.end(); ++it)
{
std::string key;
double value;
parseKeyDValue(it, key, value);
joints_[key.c_str()] = value;
}
} // end try
catch (YAML::ParserException& e)
{
ROS_ERROR("mutableJointStatePublisher: parsing joint states file");
ROS_ERROR_STREAM("Failed with exception " << e.what());
return (false);
}
if (joints_.size() == 0) ROS_ERROR("mutable_joint_state_publisher has no joints");
// output so we know they have been read in correctly
for (std::map<std::string, double>::iterator it = joints_.begin(); it != joints_.end(); ++it)
{
ROS_INFO("mutable joint %s has value %lf", it->first.c_str(), it->second);
}
return (true);
}
bool MutableJointStatePublisher::publishJointStates()
{
sensor_msgs::JointState joint_states;
joint_states.header.stamp = ros::Time::now();
joint_states.name.clear();
joint_states.position.clear();
joint_states.velocity.clear();
joint_states.effort.clear();
for (std::map<string, double>::iterator it = joints_.begin(); it != joints_.end(); ++it)
{
joint_states.name.push_back(it->first);
joint_states.position.push_back(it->second);
joint_states.velocity.push_back(0.0);
joint_states.effort.push_back(0.0);
}
joint_state_pub_.publish(joint_states);
}
} // end namespace mutable_joint_state_publisher
int main(int argc, char** argv)
{
ros::init(argc, argv, "mutable_joint_state_publisher");
ros::NodeHandle nh;
industrial_extrinsic_cal::MutableJointStatePublisher MJSP(nh);
ros::Rate loop_rate(5);
while (ros::ok())
{
MJSP.publishJointStates();
ros::spinOnce();
loop_rate.sleep();
}
}
<|endoftext|> |
<commit_before>#include "fft.h"
#include <stddef.h>
#include <complex>
#include <vector>
namespace pfi {
namespace math {
template void fft<std::complex<double>*>(std::complex<double>*, std::complex<double>*);
template void ifft<std::complex<double>*>(std::complex<double>*, std::complex<double>*);
template void fft2d<std::complex<double>*>(std::complex<double>*, std::complex<double>*, size_t);
template void ifft2d<std::complex<double>*>(std::complex<double>*, std::complex<double>*, size_t);
template void fft2d<std::vector<std::vector<std::complex<double> > > >(std::vector<std::vector<std::complex<double> > >&);
template void ifft2d<std::vector<std::vector<std::complex<double> > > >(std::vector<std::vector<std::complex<double> > >&);
} // namespace math
} // namespace pfi
<commit_msg>Added instantiation test for math/vector.h.<commit_after>#include "fft.h"
#include "vector.h"
#include <stddef.h>
#include <complex>
#include <vector>
namespace pfi {
namespace math {
template void fft<std::complex<double>*>(std::complex<double>*, std::complex<double>*);
template void ifft<std::complex<double>*>(std::complex<double>*, std::complex<double>*);
template void fft2d<std::complex<double>*>(std::complex<double>*, std::complex<double>*, size_t);
template void ifft2d<std::complex<double>*>(std::complex<double>*, std::complex<double>*, size_t);
template void fft2d<std::vector<std::vector<std::complex<double> > > >(std::vector<std::vector<std::complex<double> > >&);
template void ifft2d<std::vector<std::vector<std::complex<double> > > >(std::vector<std::vector<std::complex<double> > >&);
namespace vector {
namespace component_by_name {
template class vector2<double>;
template vector2<double> operator+<double>(const vector2<double>&, const vector2<double>&);
template vector2<double> operator-<double>(const vector2<double>&, const vector2<double>&);
template vector2<double> operator-<double>(const vector2<double>&);
template vector2<double> operator*<double>(const double&, const vector2<double>&);
template vector2<double> operator*<double>(const vector2<double>&, const double&);
template vector2<double> operator/<double>(const vector2<double>&, const double&);
template double operator*<double>(const vector2<double>&, const vector2<double>&);
template double operator%<double>(const vector2<double>&, const vector2<double>&);
template vector2<double>& operator+=<double>(vector2<double>&, const vector2<double>&);
template vector2<double>& operator-=<double>(vector2<double>&, const vector2<double>&);
template vector2<double>& operator*=<double>(vector2<double>&, const double&);
template vector2<double>& operator/=<double>(vector2<double>&, const double&);
template bool operator==<double>(const vector2<double>&, const vector2<double>&);
template bool operator< <double>(const vector2<double>&, const vector2<double>&);
template double norm<double>(const vector2<double>&);
template double abs<double>(const vector2<double>&);
template vector2<double> normalize<double>(const vector2<double>&, double);
template double operator/<double>(const vector2<double>&, const vector2<double>&);
template std::istream& operator>><double>(std::istream&, vector2<double>&);
template std::ostream& operator<<<double>(std::ostream&, const vector2<double>&);
} // namespace component_by_name
namespace component_by_array {
template class vector2<double>;
template vector2<double> operator+<double>(const vector2<double>&, const vector2<double>&);
template vector2<double> operator-<double>(const vector2<double>&, const vector2<double>&);
template vector2<double> operator-<double>(const vector2<double>&);
template vector2<double> operator*<double>(const double&, const vector2<double>&);
template vector2<double> operator*<double>(const vector2<double>&, const double&);
template vector2<double> operator/<double>(const vector2<double>&, const double&);
template double operator*<double>(const vector2<double>&, const vector2<double>&);
// template double operator%<double>(const vector2<double>&, const vector2<double>&);
template vector2<double>& operator+=<double>(vector2<double>&, const vector2<double>&);
template vector2<double>& operator-=<double>(vector2<double>&, const vector2<double>&);
template vector2<double>& operator*=<double>(vector2<double>&, const double&);
template vector2<double>& operator/=<double>(vector2<double>&, const double&);
template bool operator==<double>(const vector2<double>&, const vector2<double>&);
template bool operator< <double>(const vector2<double>&, const vector2<double>&);
template double norm<double>(const vector2<double>&);
template double abs<double>(const vector2<double>&);
template vector2<double> normalize<double>(const vector2<double>&, double);
template double operator/<double>(const vector2<double>&, const vector2<double>&);
template std::istream& operator>><double>(std::istream&, vector2<double>&);
template std::ostream& operator<<<double>(std::ostream&, const vector2<double>&);
} // namespace component_by_array
} // namespace vector
} // namespace math
} // namespace pfi
<|endoftext|> |
<commit_before>/**
* @file hash_test.cpp
* @ingroup algo
* @brief Simple Hash functions.
*
* Copyright (c) 2013 Sebastien Rombauts (sebastien.rombauts@gmail.com)
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#include "algo/hash.h"
#include <limits>
#include "gtest/gtest.h"
#include "base/random.h"
#include "base/utils.h"
// Test that hashsum of strings does change for any bit change
TEST(Hash, sdbm) {
EXPECT_NE(Hash::sdbm("abcd"), Hash::sdbm("abce"));
#define NB_CHAR 10
char str1[NB_CHAR+1];
char str2[NB_CHAR+1];
// Get 1000 random strings
for (int i = 0; i < 1000; ++i) {
Random::GenString(str1, NB_CHAR);
const unsigned int hash1 = Hash::sdbm(str1);
// Change only one bit of the string
for (int j = 0; j < NB_CHAR*7; ++j) {
snprintf(str2, NB_CHAR, "%s", str1);
str2[j/7] ^= static_cast<char>(0x01 << (j%7));
// Hashsum should never be equal when only one bit of the string change
const unsigned int hash2 = Hash::sdbm(str2);
EXPECT_NE(hash1, hash2);
}
}
}
// Test that hashsum of strings does change for any bit change
TEST(Hash, djb2) {
EXPECT_NE(Hash::djb2("abcd"), Hash::djb2("abce"));
#define NB_CHAR 10
char str1[NB_CHAR+1];
char str2[NB_CHAR+1];
// Get 1000 random strings
for (int i = 0; i < 1000; ++i) {
Random::GenString(str1, NB_CHAR);
const unsigned int hash1 = Hash::djb2(str1);
// Change only one bit of the string
for (int j = 0; j < NB_CHAR*7; ++j) {
snprintf(str2, NB_CHAR, "%s", str1);
str2[j/7] ^= static_cast<char>(0x01 << (j%7));
// Hashsum should never be equal when only one bit of the string change
const unsigned int hash2 = Hash::djb2(str2);
EXPECT_NE(hash1, hash2);
}
}
}
// Test that hashsum of strings does change for any bit change
TEST(Hash, fnv1a32) {
EXPECT_NE(Hash::fnv1a32("abcd"), Hash::fnv1a32("abce"));
#define NB_CHAR 10
char str1[NB_CHAR+1];
char str2[NB_CHAR+1];
// Get 1000 random strings
for (unsigned int i = 0; i < 1000; ++i) {
Random::GenString(str1, NB_CHAR);
const unsigned int hash1 = Hash::fnv1a32(str1);
// Change only one bit of the string
for (unsigned int j = 0; j < NB_CHAR*7; ++j) {
snprintf(str2, NB_CHAR, "%s", str1);
str2[j/7] ^= static_cast<char>(0x01 << (j%7));
// Hashsum should never be equal when only one bit of the string change
const unsigned int hash2 = Hash::fnv1a32(str2);
EXPECT_NE(hash1, hash2);
}
}
}
<commit_msg>Add FNV1a unit tests to compare against reference hash values<commit_after>/**
* @file hash_test.cpp
* @ingroup algo
* @brief Simple Hash functions.
*
* Copyright (c) 2013 Sebastien Rombauts (sebastien.rombauts@gmail.com)
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#include "algo/hash.h"
#include <limits>
#include "gtest/gtest.h"
#include "base/random.h"
#include "base/utils.h"
// Test that hashsum of strings does change for any bit change
TEST(Hash, sdbm) {
EXPECT_NE(Hash::sdbm("abcd"), Hash::sdbm("abce"));
#define NB_CHAR 10
char str1[NB_CHAR+1];
char str2[NB_CHAR+1];
// Get 1000 random strings
for (int i = 0; i < 1000; ++i) {
Random::GenString(str1, NB_CHAR);
const unsigned int hash1 = Hash::sdbm(str1);
// Change only one bit of the string
for (int j = 0; j < NB_CHAR*7; ++j) {
snprintf(str2, NB_CHAR, "%s", str1);
str2[j/7] ^= static_cast<char>(0x01 << (j%7));
// Hashsum should never be equal when only one bit of the string change
const unsigned int hash2 = Hash::sdbm(str2);
EXPECT_NE(hash1, hash2);
}
}
}
// Test that hashsum of strings does change for any bit change
TEST(Hash, djb2) {
EXPECT_NE(Hash::djb2("abcd"), Hash::djb2("abce"));
#define NB_CHAR 10
char str1[NB_CHAR+1];
char str2[NB_CHAR+1];
// Get 1000 random strings
for (int i = 0; i < 1000; ++i) {
Random::GenString(str1, NB_CHAR);
const unsigned int hash1 = Hash::djb2(str1);
// Change only one bit of the string
for (int j = 0; j < NB_CHAR*7; ++j) {
snprintf(str2, NB_CHAR, "%s", str1);
str2[j/7] ^= static_cast<char>(0x01 << (j%7));
// Hashsum should never be equal when only one bit of the string change
const unsigned int hash2 = Hash::djb2(str2);
EXPECT_NE(hash1, hash2);
}
}
}
// Test that hashsum of strings does change for any bit change
TEST(Hash, fnv1a32) {
EXPECT_NE(Hash::fnv1a32("abcd"), Hash::fnv1a32("abce"));
#define NB_CHAR 10
char str1[NB_CHAR+1];
char str2[NB_CHAR+1];
// Get 1000 random strings
for (unsigned int i = 0; i < 1000; ++i) {
Random::GenString(str1, NB_CHAR);
const unsigned int hash1 = Hash::fnv1a32(str1);
// Change only one bit of the string
for (unsigned int j = 0; j < NB_CHAR*7; ++j) {
snprintf(str2, NB_CHAR, "%s", str1);
str2[j/7] ^= static_cast<char>(0x01 << (j%7));
// Hashsum should never be equal when only one bit of the string change
const unsigned int hash2 = Hash::fnv1a32(str2);
EXPECT_NE(hash1, hash2);
}
}
}
// Test against reference implementation for a few text values (empty string, "test" string", etc)
TEST(Hash, fnv1a32_reference) {
EXPECT_EQ(Hash::fnv1a32(""), 0x811c9dc5);
EXPECT_EQ(Hash::fnv1a32("a"), 0xe40c292c);
EXPECT_EQ(Hash::fnv1a32("test"), 0xafd071e5);
// failure
EXPECT_NE(Hash::fnv1a32("nope"), 0xafd071e5);
}<|endoftext|> |
<commit_before>#include "p1Scene.h"
#include "p2Scene.h"
//puzzle classes
#include "puzzle.h"
#include "partner.h"
#include "gameController.h"
#include "DataSetting.h"
USING_NS_CC;
using namespace ui;
Scene* firstPuzzle::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = firstPuzzle::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool firstPuzzle::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
goalCount = 6;
gameController::getInstance()->initPuzzleCount();
schedule(schedule_selector(firstPuzzle::checkEnding),0.5f);
/*background image*/
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
Sprite* backgroundSprite = Sprite::create("p1/background.jpg");
// position the sprite on the center of the screen
backgroundSprite->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
// add the sprite as a child to this layer
this->addChild(backgroundSprite, BACKGROUND_Z);
//left leg puzzle
{
puzzle* pz1 = new puzzle(100.0f, 150.0f, 420.0f, 480.0f, "p1/left_leg.png");
pz1->addEvent();
Sprite* spz1 = pz1->getPuzzle();
Sprite* ppz1 = pz1->getPartnerPuzzle();
this->addChild(spz1);
this->addChild(ppz1);
}
//right leg puzzle
{
puzzle* pz2 = new puzzle(250.0f, 150.0f, 668.0f, 486.0f, "p1/right_leg.png");
pz2->addEvent();
Sprite* spz2 = pz2->getPuzzle();
Sprite* ppz2 = pz2->getPartnerPuzzle();
this->addChild(spz2);
this->addChild(ppz2);
}
//middle leg puzzle
{
puzzle* pz3 = new puzzle(420.0f, 150.0f, 540.0f, 630.0f, "p1/middle_leg.png");
pz3->addEvent();
Sprite* spz3 = pz3->getPuzzle();
Sprite* ppz3 = pz3->getPartnerPuzzle();
this->addChild(spz3);
this->addChild(ppz3);
}
//backbone puzzle
{
puzzle* pz3 = new puzzle(545.0f, 170.0f, 545.0f, 867.0f, "p1/backbone.png");
pz3->addEvent();
Sprite* spz3 = pz3->getPuzzle();
Sprite* ppz3 = pz3->getPartnerPuzzle();
this->addChild(spz3);
this->addChild(ppz3);
}
//left arm puzzle
{
puzzle* pz3 = new puzzle(700.0f, 150.0f, 378.0f, 810.0f, "p1/left_arm.png");
pz3->addEvent();
Sprite* spz3 = pz3->getPuzzle();
Sprite* ppz3 = pz3->getPartnerPuzzle();
this->addChild(spz3);
this->addChild(ppz3);
}
//right arm puzzle
{
puzzle* pz3 = new puzzle(935.0f, 150.0f, 707.0f, 810.0f, "p1/right_arm.png");
pz3->addEvent();
Sprite* spz3 = pz3->getPuzzle();
Sprite* ppz3 = pz3->getPartnerPuzzle();
this->addChild(spz3);
this->addChild(ppz3);
}
this->setKeypadEnabled(true);
return true;
}
void firstPuzzle::checkEnding(float t){
int curCount = gameController::getInstance()->getPuzzleCount();
if(goalCount == curCount){
CCLOG("Ending!");
//unschedule check puzzle count
this->unschedule(schedule_selector(firstPuzzle::checkEnding));
//ending effect
this->scheduleOnce(schedule_selector(firstPuzzle::showCompleteSprite), SHOWCLEARIMAGE_DELAYTIME);
//show ending popup
this->scheduleOnce(schedule_selector(firstPuzzle::showEndingPopUp), SHOWPOPUPREWARD_DELAYTIME);
}
}
//ending effect
void firstPuzzle::showCompleteSprite(float dt){
Sprite* spriteComplete = Sprite::create("p1/result.png");
spriteComplete->setPosition(Vec2(540.0f, 718.0f));
spriteComplete->setZOrder(PARTNER_Z+1);
this->addChild(spriteComplete);
}
void firstPuzzle::showEndingPopUp(float dt){
Size visibleSize = Director::getInstance()->getVisibleSize();
//ui test
Layout* popLayout = Layout::create();
popLayout->setSize(visibleSize);
popLayout->setPosition(Vec2());
popLayout->setAnchorPoint(Vec2());
popLayout->setBackGroundColorType(LayoutBackGroundColorType::SOLID);
popLayout->setBackGroundColor(Color3B::BLACK);
popLayout->setBackGroundColorOpacity(255 * POPUPLAYOUT_OPACITY_PERCENT);
this->addChild(popLayout, POPUPLAYOUT_Z);
Button* replayBtn = Button::create("replay.png", "replay_s.png");
replayBtn->setPosition(Vec2(visibleSize.width / 2 - 200, visibleSize.height / 2 - 600));
replayBtn->addTouchEventListener(CC_CALLBACK_2(firstPuzzle::endingPopupBtns, this));
replayBtn->setTag(1);
popLayout->addChild(replayBtn, 1);
Button* nextBtn = Button::create("next.png", "next_s.png");
nextBtn->setPosition(Vec2(visibleSize.width / 2 + 200, visibleSize.height / 2 - 600));
nextBtn->addTouchEventListener(CC_CALLBACK_2(firstPuzzle::endingPopupBtns, this));
nextBtn->setTag(2);
popLayout->addChild(nextBtn, 1);
Sprite* resultSpr = Sprite::create("reward.png");
resultSpr->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2 + 100));
popLayout->addChild(resultSpr, 1);
}
void firstPuzzle::endingPopupBtns(Ref* pSender, Widget::TouchEventType type){
if (Widget::TouchEventType::ENDED == type){
Button* b = (Button*)pSender;
int tag = b->getTag();
switch (tag)
{
case 1:
reGame();
break;
case 2:
nextGame();
break;
default:
break;
}
}
}
void firstPuzzle::reGame(){
Scene* s = firstPuzzle::createScene();
Director::getInstance()->replaceScene(s);
}
void firstPuzzle::nextGame(){
//go nextScene
Scene* s = secondPuzzle::createScene();
Director::getInstance()->replaceScene(s);
}
void firstPuzzle::onKeyReleased(cocos2d::EventKeyboard::KeyCode keycode, cocos2d::Event* e)
{
if (EventKeyboard::KeyCode::KEY_MENU == keycode ||
EventKeyboard::KeyCode::KEY_RIGHT_ARROW == keycode)
{
nextGame();
}
}
<commit_msg>add comment and back key event added to p1<commit_after>#include "p1Scene.h"
#include "p2Scene.h"
//puzzle classes
#include "puzzle.h"
#include "partner.h"
#include "gameController.h"
#include "DataSetting.h"
USING_NS_CC;
using namespace ui;
Scene* firstPuzzle::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = firstPuzzle::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool firstPuzzle::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
goalCount = 6;
gameController::getInstance()->initPuzzleCount();
schedule(schedule_selector(firstPuzzle::checkEnding),0.5f);
/*background image*/
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
Sprite* backgroundSprite = Sprite::create("p1/background.jpg");
// position the sprite on the center of the screen
backgroundSprite->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
// add the sprite as a child to this layer
this->addChild(backgroundSprite, BACKGROUND_Z);
//left leg puzzle
{
puzzle* pz1 = new puzzle(100.0f, 150.0f, 420.0f, 480.0f, "p1/left_leg.png");
pz1->addEvent();
Sprite* spz1 = pz1->getPuzzle();
Sprite* ppz1 = pz1->getPartnerPuzzle();
this->addChild(spz1);
this->addChild(ppz1);
}
//right leg puzzle
{
puzzle* pz2 = new puzzle(250.0f, 150.0f, 668.0f, 486.0f, "p1/right_leg.png");
pz2->addEvent();
Sprite* spz2 = pz2->getPuzzle();
Sprite* ppz2 = pz2->getPartnerPuzzle();
this->addChild(spz2);
this->addChild(ppz2);
}
//middle leg puzzle
{
puzzle* pz3 = new puzzle(420.0f, 150.0f, 540.0f, 630.0f, "p1/middle_leg.png");
pz3->addEvent();
Sprite* spz3 = pz3->getPuzzle();
Sprite* ppz3 = pz3->getPartnerPuzzle();
this->addChild(spz3);
this->addChild(ppz3);
}
//backbone puzzle
{
puzzle* pz3 = new puzzle(545.0f, 170.0f, 545.0f, 867.0f, "p1/backbone.png");
pz3->addEvent();
Sprite* spz3 = pz3->getPuzzle();
Sprite* ppz3 = pz3->getPartnerPuzzle();
this->addChild(spz3);
this->addChild(ppz3);
}
//left arm puzzle
{
puzzle* pz3 = new puzzle(700.0f, 150.0f, 378.0f, 810.0f, "p1/left_arm.png");
pz3->addEvent();
Sprite* spz3 = pz3->getPuzzle();
Sprite* ppz3 = pz3->getPartnerPuzzle();
this->addChild(spz3);
this->addChild(ppz3);
}
//right arm puzzle
{
puzzle* pz3 = new puzzle(935.0f, 150.0f, 707.0f, 810.0f, "p1/right_arm.png");
pz3->addEvent();
Sprite* spz3 = pz3->getPuzzle();
Sprite* ppz3 = pz3->getPartnerPuzzle();
this->addChild(spz3);
this->addChild(ppz3);
}
//set key event enable
this->setKeypadEnabled(true);
return true;
}
void firstPuzzle::checkEnding(float t){
int curCount = gameController::getInstance()->getPuzzleCount();
if(goalCount == curCount){
CCLOG("Ending!");
//unschedule check puzzle count
this->unschedule(schedule_selector(firstPuzzle::checkEnding));
//ending effect
this->scheduleOnce(schedule_selector(firstPuzzle::showCompleteSprite), SHOWCLEARIMAGE_DELAYTIME);
//show ending popup
this->scheduleOnce(schedule_selector(firstPuzzle::showEndingPopUp), SHOWPOPUPREWARD_DELAYTIME);
}
}
//ending effect
void firstPuzzle::showCompleteSprite(float dt){
Sprite* spriteComplete = Sprite::create("p1/result.png");
spriteComplete->setPosition(Vec2(540.0f, 718.0f));
spriteComplete->setZOrder(PARTNER_Z+1);
this->addChild(spriteComplete);
}
void firstPuzzle::showEndingPopUp(float dt){
//visible size value
Size visibleSize = Director::getInstance()->getVisibleSize();
//layout for popup
Layout* popLayout = Layout::create();
popLayout->setSize(visibleSize);
popLayout->setPosition(Vec2());
popLayout->setAnchorPoint(Vec2());
popLayout->setBackGroundColorType(LayoutBackGroundColorType::SOLID);
popLayout->setBackGroundColor(Color3B::BLACK);
popLayout->setBackGroundColorOpacity(255 * POPUPLAYOUT_OPACITY_PERCENT);
this->addChild(popLayout, POPUPLAYOUT_Z);
//replay button
Button* replayBtn = Button::create("replay.png", "replay_s.png");
replayBtn->setPosition(Vec2(visibleSize.width / 2 - 200, visibleSize.height / 2 - 600));
replayBtn->addTouchEventListener(CC_CALLBACK_2(firstPuzzle::endingPopupBtns, this));
replayBtn->setTag(1);
popLayout->addChild(replayBtn, 1);
//next button
Button* nextBtn = Button::create("next.png", "next_s.png");
nextBtn->setPosition(Vec2(visibleSize.width / 2 + 200, visibleSize.height / 2 - 600));
nextBtn->addTouchEventListener(CC_CALLBACK_2(firstPuzzle::endingPopupBtns, this));
nextBtn->setTag(2);
popLayout->addChild(nextBtn, 1);
//result sprite of goodjob
Sprite* resultSpr = Sprite::create("reward.png");
resultSpr->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2 + 100));
popLayout->addChild(resultSpr, 1);
}
void firstPuzzle::endingPopupBtns(Ref* pSender, Widget::TouchEventType type){
if (Widget::TouchEventType::ENDED == type){
Button* b = (Button*)pSender;
int tag = b->getTag();
switch (tag)
{
case 1:
reGame();
break;
case 2:
nextGame();
break;
default:
break;
}
}
}
void firstPuzzle::reGame(){
Scene* s = firstPuzzle::createScene();
Director::getInstance()->replaceScene(s);
}
void firstPuzzle::nextGame(){
//go nextScene
Scene* s = secondPuzzle::createScene();
Director::getInstance()->replaceScene(s);
}
void firstPuzzle::onKeyReleased(cocos2d::EventKeyboard::KeyCode keycode, cocos2d::Event* e)
{
if (EventKeyboard::KeyCode::KEY_MENU == keycode ||
EventKeyboard::KeyCode::KEY_RIGHT_ARROW == keycode)
{//menu button
nextGame();
}
if (EventKeyboard::KeyCode::KEY_BACK == keycode)
{//back button
Director::getInstance()->end();
}
}
<|endoftext|> |
<commit_before>#include "ultrasonic_sensors_controller.h"
//---------------------------------------------------------------------
t_ultrasonic_sensors_controller::t_ultrasonic_sensors_controller (void)
{
num_sensors = 0;
sensors = NULL;
}
//---------------------------------------------------------------------
void echoCheck(void)
{
for (int i = 0; i < ultrasonic_sensors_controller.num_sensors; i++)
if (ultrasonic_sensors_controller.sensors[i].sonar->check_timer()) { // This is how you check to see if the ping was received.
// Here's where you can add code.
Serial.write('U');
Serial.print(i);
Serial.write(' ');
Serial.print(ultrasonic_sensors_controller.sensors[i].sonar->ping_result / US_ROUNDTRIP_CM);
Serial.write('#');
}
}
//---------------------------------------------------------------------
void t_ultrasonic_sensors_controller::trigger (byte sensor_index)
{
if (sensor_index < num_sensors){
sensors[sensor_index].sonar->ping_timer(echoCheck);
}
}
//---------------------------------------------------------------------
void t_ultrasonic_sensors_controller::set_sensor_pins(byte sensor_index, byte trig_pin, byte echo_pin)
{
if (sensor_index < num_sensors)
sensors[sensor_index].create_init(trig_pin, echo_pin);
}
//---------------------------------------------------------------------
void t_ultrasonic_sensors_controller::set_num_sensors(byte new_num_sensors)
{
if (new_num_sensors != num_sensors){
num_sensors = new_num_sensors;
if (sensors)
delete[] sensors;
if (num_sensors > 0){
byte trig_pins[4];
trig_pins[0] = 8;
trig_pins[1] = 5;
trig_pins[2] = 8;
trig_pins[3] = 11;
byte echo_pins[4];
echo_pins[0] = 9;
echo_pins[1] = 6;
echo_pins[2] = 9;
echo_pins[3] = 12;
sensors = new t_ultrasonic[num_sensors];
for (byte m = 0; m < num_sensors; m++)
sensors[m].create_init(trig_pins[m], echo_pins[m]);
}
else
sensors = NULL;
}
}
//---------------------------------------------------------------------
byte t_ultrasonic_sensors_controller::get_num_sensors(void)
{
return num_sensors;
}
//---------------------------------------------------------------------
void t_ultrasonic_sensors_controller::get_sensor_pins(byte sensor_index, byte *trig_pins, byte *echo_pins)
{
sensors[sensor_index].get_sensor_pins(trig_pins, echo_pins);
}
//---------------------------------------------------------------------
<commit_msg>send (to Serial) the output of sonar by 1 call<commit_after>#include "ultrasonic_sensors_controller.h"
//---------------------------------------------------------------------
t_ultrasonic_sensors_controller::t_ultrasonic_sensors_controller (void)
{
num_sensors = 0;
sensors = NULL;
}
//---------------------------------------------------------------------
void echoCheck(void)
{
for (int i = 0; i < ultrasonic_sensors_controller.num_sensors; i++)
if (ultrasonic_sensors_controller.sensors[i].sonar->check_timer()) { // This is how you check to see if the ping was received.
int distance = ultrasonic_sensors_controller.sensors[i].sonar->ping_result / US_ROUNDTRIP_CM;
char tmp_str[30];
sprintf(tmp_str, "U%d %d#", i, distance);
Serial.write(tmp_str);
}
}
//---------------------------------------------------------------------
void t_ultrasonic_sensors_controller::trigger (byte sensor_index)
{
if (sensor_index < num_sensors){
sensors[sensor_index].sonar->ping_timer(echoCheck);
}
}
//---------------------------------------------------------------------
void t_ultrasonic_sensors_controller::set_sensor_pins(byte sensor_index, byte trig_pin, byte echo_pin)
{
if (sensor_index < num_sensors)
sensors[sensor_index].create_init(trig_pin, echo_pin);
}
//---------------------------------------------------------------------
void t_ultrasonic_sensors_controller::set_num_sensors(byte new_num_sensors)
{
if (new_num_sensors != num_sensors){
num_sensors = new_num_sensors;
if (sensors)
delete[] sensors;
if (num_sensors > 0){
byte trig_pins[4];
trig_pins[0] = 8;
trig_pins[1] = 5;
trig_pins[2] = 8;
trig_pins[3] = 11;
byte echo_pins[4];
echo_pins[0] = 9;
echo_pins[1] = 6;
echo_pins[2] = 9;
echo_pins[3] = 12;
sensors = new t_ultrasonic[num_sensors];
for (byte m = 0; m < num_sensors; m++)
sensors[m].create_init(trig_pins[m], echo_pins[m]);
}
else
sensors = NULL;
}
}
//---------------------------------------------------------------------
byte t_ultrasonic_sensors_controller::get_num_sensors(void)
{
return num_sensors;
}
//---------------------------------------------------------------------
void t_ultrasonic_sensors_controller::get_sensor_pins(byte sensor_index, byte *trig_pins, byte *echo_pins)
{
sensors[sensor_index].get_sensor_pins(trig_pins, echo_pins);
}
//---------------------------------------------------------------------
<|endoftext|> |
<commit_before>/*************************************************************************
*
* 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: moduldlg.hxx,v $
* $Revision: 1.24 $
*
* 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 _MODULDLG_HXX
#define _MODULDLG_HXX
#include <svheader.hxx>
#include <bastype2.hxx>
#include <vcl/dialog.hxx>
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#include <vcl/fixed.hxx>
#include <svtools/svtabbx.hxx>
#include <vcl/tabdlg.hxx>
#include <vcl/tabpage.hxx>
#include "com/sun/star/task/XInteractionHandler.hpp"
#include <vcl/tabctrl.hxx>
#include <vcl/lstbox.hxx>
class StarBASIC;
#define NEWOBJECTMODE_LIB 1
#define NEWOBJECTMODE_MOD 2
#define NEWOBJECTMODE_DLG 3
#define NEWOBJECTMODE_METH 4
class NewObjectDialog : public ModalDialog
{
private:
FixedText aText;
Edit aEdit;
OKButton aOKButton;
CancelButton aCancelButton;
DECL_LINK(OkButtonHandler, Button *);
public:
NewObjectDialog(Window * pParent, USHORT nMode, bool bCheckName = false);
~NewObjectDialog();
String GetObjectName() const { return aEdit.GetText(); }
void SetObjectName( const String& rName ) { aEdit.SetText( rName ); aEdit.SetSelection( Selection( 0, rName.Len() ) );}
};
class ExportDialog : public ModalDialog
{
private:
RadioButton maExportAsPackageButton;
RadioButton maExportAsBasicButton;
OKButton maOKButton;
CancelButton maCancelButton;
sal_Bool mbExportAsPackage;
DECL_LINK(OkButtonHandler, Button *);
public:
ExportDialog( Window * pParent );
~ExportDialog();
sal_Bool isExportAsPackage( void ) { return mbExportAsPackage; }
};
class ExtBasicTreeListBox : public BasicTreeListBox
{
protected:
virtual BOOL EditingEntry( SvLBoxEntry* pEntry, Selection& rSel );
virtual BOOL EditedEntry( SvLBoxEntry* pEntry, const String& rNewText );
virtual DragDropMode NotifyStartDrag( TransferDataContainer& rData, SvLBoxEntry* pEntry );
virtual BOOL NotifyAcceptDrop( SvLBoxEntry* pEntry );
virtual BOOL NotifyMoving( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry,
SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos );
virtual BOOL NotifyCopying( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry,
SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos );
BOOL NotifyCopyingMoving( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry,
SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos, BOOL bMove );
public:
ExtBasicTreeListBox( Window* pParent, const ResId& rRes );
~ExtBasicTreeListBox();
};
#define LIBMODE_CHOOSER 1
#define LIBMODE_MANAGER 2
class BasicCheckBox : public SvTabListBox
{
private:
USHORT nMode;
SvLBoxButtonData* pCheckButton;
ScriptDocument m_aDocument;
void Init();
public:
BasicCheckBox( Window* pParent, const ResId& rResId );
~BasicCheckBox();
SvLBoxEntry* DoInsertEntry( const String& rStr, ULONG nPos = LISTBOX_APPEND );
void RemoveEntry( ULONG nPos );
SvLBoxEntry* FindEntry( const String& rName );
void SelectEntryPos( ULONG nPos, BOOL bSelect = TRUE );
ULONG GetSelectEntryPos() const;
ULONG GetCheckedEntryCount() const;
void CheckEntryPos( ULONG nPos, BOOL bCheck = TRUE );
BOOL IsChecked( ULONG nPos ) const;
virtual void InitEntry( SvLBoxEntry*, const XubString&, const Image&, const Image&, SvLBoxButtonKind eButtonKind );
virtual BOOL EditingEntry( SvLBoxEntry* pEntry, Selection& rSel );
virtual BOOL EditedEntry( SvLBoxEntry* pEntry, const String& rNewText );
void SetDocument( const ScriptDocument& rDocument ) { m_aDocument = rDocument; }
void SetMode( USHORT n );
USHORT GetMode() const { return nMode; }
};
class LibDialog: public ModalDialog
{
private:
OKButton aOKButton;
CancelButton aCancelButton;
FixedText aStorageName;
BasicCheckBox aLibBox;
FixedLine aFixedLine;
CheckBox aReferenceBox;
CheckBox aReplaceBox;
public:
LibDialog( Window* pParent );
~LibDialog();
void SetStorageName( const String& rName );
BasicCheckBox& GetLibBox() { return aLibBox; }
BOOL IsReference() const { return aReferenceBox.IsChecked(); }
BOOL IsReplace() const { return aReplaceBox.IsChecked(); }
void EnableReference( BOOL b ) { aReferenceBox.Enable( b ); }
void EnableReplace( BOOL b ) { aReplaceBox.Enable( b ); }
};
class OrganizeDialog : public TabDialog
{
private:
TabControl aTabCtrl;
BasicEntryDescriptor m_aCurEntry;
public:
OrganizeDialog( Window* pParent, INT16 tabId, BasicEntryDescriptor& rDesc );
~OrganizeDialog();
virtual short Execute();
DECL_LINK( ActivatePageHdl, TabControl * );
};
class ObjectPage: public TabPage
{
protected:
FixedText aLibText;
ExtBasicTreeListBox aBasicBox;
PushButton aEditButton;
CancelButton aCloseButton;
PushButton aNewModButton;
PushButton aNewDlgButton;
PushButton aDelButton;
DECL_LINK( BasicBoxHighlightHdl, BasicTreeListBox * );
DECL_LINK( ButtonHdl, Button * );
void CheckButtons();
bool GetSelection( ScriptDocument& rDocument, String& rLibName );
void DeleteCurrent();
void NewModule();
void NewDialog();
void EndTabDialog( USHORT nRet );
TabDialog* pTabDlg;
virtual void ActivatePage();
virtual void DeactivatePage();
public:
ObjectPage( Window* pParent, const ResId& rResId, USHORT nMode );
void SetCurrentEntry( BasicEntryDescriptor& rDesc );
void SetTabDlg( TabDialog* p ) { pTabDlg = p;}
};
class SvxPasswordDialog;
class LibPage: public TabPage
{
protected:
FixedText aBasicsText;
ListBox aBasicsBox;
FixedText aLibText;
BasicCheckBox aLibBox;
PushButton aEditButton;
CancelButton aCloseButton;
PushButton aPasswordButton;
PushButton aExportButton;
PushButton aNewLibButton;
PushButton aInsertLibButton;
PushButton aDelButton;
ScriptDocument m_aCurDocument;
LibraryLocation m_eCurLocation;
DECL_LINK( TreeListHighlightHdl, SvTreeListBox * );
DECL_LINK( BasicSelectHdl, ListBox * );
DECL_LINK( ButtonHdl, Button * );
DECL_LINK( CheckPasswordHdl, SvxPasswordDialog * );
void CheckButtons();
void DeleteCurrent();
void NewLib();
void InsertLib();
void implExportLib( const String& aLibName, const String& aTargetURL,
const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& Handler );
void Export();
void ExportAsPackage( const String& aLibName );
void ExportAsBasic( const String& aLibName );
void EndTabDialog( USHORT nRet );
void FillListBox();
void InsertListBoxEntry( const ScriptDocument& rDocument, LibraryLocation eLocation );
void SetCurLib();
SvLBoxEntry* ImpInsertLibEntry( const String& rLibName, ULONG nPos );
virtual void ActivatePage();
virtual void DeactivatePage();
TabDialog* pTabDlg;
public:
LibPage( Window* pParent );
virtual ~LibPage();
void SetTabDlg( TabDialog* p ) { pTabDlg = p;}
};
// Helper functions
SbModule* createModImpl( Window* pWin, const ScriptDocument& rDocument,
BasicTreeListBox& rBasicBox, const String& rLibName, String aModName, bool bMain = false );
void createLibImpl( Window* pWin, const ScriptDocument& rDocument,
BasicCheckBox* pLibBox, BasicTreeListBox* pBasicBox );
#endif // _MODULDLG_HXX
<commit_msg>INTEGRATION: CWS ab53 (1.24.10); FILE MERGED 2008/06/06 13:13:17 ab 1.24.10.1: #i89523# Removed unused code<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: moduldlg.hxx,v $
* $Revision: 1.25 $
*
* 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 _MODULDLG_HXX
#define _MODULDLG_HXX
#include <svheader.hxx>
#include <bastype2.hxx>
#include <vcl/dialog.hxx>
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#include <vcl/fixed.hxx>
#include <svtools/svtabbx.hxx>
#include <vcl/tabdlg.hxx>
#include <vcl/tabpage.hxx>
#include "com/sun/star/task/XInteractionHandler.hpp"
#include <vcl/tabctrl.hxx>
#include <vcl/lstbox.hxx>
class StarBASIC;
#define NEWOBJECTMODE_LIB 1
#define NEWOBJECTMODE_MOD 2
#define NEWOBJECTMODE_DLG 3
#define NEWOBJECTMODE_METH 4
class NewObjectDialog : public ModalDialog
{
private:
FixedText aText;
Edit aEdit;
OKButton aOKButton;
CancelButton aCancelButton;
DECL_LINK(OkButtonHandler, Button *);
public:
NewObjectDialog(Window * pParent, USHORT nMode, bool bCheckName = false);
~NewObjectDialog();
String GetObjectName() const { return aEdit.GetText(); }
void SetObjectName( const String& rName ) { aEdit.SetText( rName ); aEdit.SetSelection( Selection( 0, rName.Len() ) );}
};
class ExportDialog : public ModalDialog
{
private:
RadioButton maExportAsPackageButton;
RadioButton maExportAsBasicButton;
OKButton maOKButton;
CancelButton maCancelButton;
sal_Bool mbExportAsPackage;
DECL_LINK(OkButtonHandler, Button *);
public:
ExportDialog( Window * pParent );
~ExportDialog();
sal_Bool isExportAsPackage( void ) { return mbExportAsPackage; }
};
class ExtBasicTreeListBox : public BasicTreeListBox
{
protected:
virtual BOOL EditingEntry( SvLBoxEntry* pEntry, Selection& rSel );
virtual BOOL EditedEntry( SvLBoxEntry* pEntry, const String& rNewText );
virtual DragDropMode NotifyStartDrag( TransferDataContainer& rData, SvLBoxEntry* pEntry );
virtual BOOL NotifyAcceptDrop( SvLBoxEntry* pEntry );
virtual BOOL NotifyMoving( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry,
SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos );
virtual BOOL NotifyCopying( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry,
SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos );
BOOL NotifyCopyingMoving( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry,
SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos, BOOL bMove );
public:
ExtBasicTreeListBox( Window* pParent, const ResId& rRes );
~ExtBasicTreeListBox();
};
#define LIBMODE_CHOOSER 1
#define LIBMODE_MANAGER 2
class BasicCheckBox : public SvTabListBox
{
private:
USHORT nMode;
SvLBoxButtonData* pCheckButton;
ScriptDocument m_aDocument;
void Init();
public:
BasicCheckBox( Window* pParent, const ResId& rResId );
~BasicCheckBox();
SvLBoxEntry* DoInsertEntry( const String& rStr, ULONG nPos = LISTBOX_APPEND );
void RemoveEntry( ULONG nPos );
SvLBoxEntry* FindEntry( const String& rName );
ULONG GetSelectEntryPos() const;
ULONG GetCheckedEntryCount() const;
void CheckEntryPos( ULONG nPos, BOOL bCheck = TRUE );
BOOL IsChecked( ULONG nPos ) const;
virtual void InitEntry( SvLBoxEntry*, const XubString&, const Image&, const Image&, SvLBoxButtonKind eButtonKind );
virtual BOOL EditingEntry( SvLBoxEntry* pEntry, Selection& rSel );
virtual BOOL EditedEntry( SvLBoxEntry* pEntry, const String& rNewText );
void SetDocument( const ScriptDocument& rDocument ) { m_aDocument = rDocument; }
void SetMode( USHORT n );
USHORT GetMode() const { return nMode; }
};
class LibDialog: public ModalDialog
{
private:
OKButton aOKButton;
CancelButton aCancelButton;
FixedText aStorageName;
BasicCheckBox aLibBox;
FixedLine aFixedLine;
CheckBox aReferenceBox;
CheckBox aReplaceBox;
public:
LibDialog( Window* pParent );
~LibDialog();
void SetStorageName( const String& rName );
BasicCheckBox& GetLibBox() { return aLibBox; }
BOOL IsReference() const { return aReferenceBox.IsChecked(); }
BOOL IsReplace() const { return aReplaceBox.IsChecked(); }
void EnableReference( BOOL b ) { aReferenceBox.Enable( b ); }
void EnableReplace( BOOL b ) { aReplaceBox.Enable( b ); }
};
class OrganizeDialog : public TabDialog
{
private:
TabControl aTabCtrl;
BasicEntryDescriptor m_aCurEntry;
public:
OrganizeDialog( Window* pParent, INT16 tabId, BasicEntryDescriptor& rDesc );
~OrganizeDialog();
virtual short Execute();
DECL_LINK( ActivatePageHdl, TabControl * );
};
class ObjectPage: public TabPage
{
protected:
FixedText aLibText;
ExtBasicTreeListBox aBasicBox;
PushButton aEditButton;
CancelButton aCloseButton;
PushButton aNewModButton;
PushButton aNewDlgButton;
PushButton aDelButton;
DECL_LINK( BasicBoxHighlightHdl, BasicTreeListBox * );
DECL_LINK( ButtonHdl, Button * );
void CheckButtons();
bool GetSelection( ScriptDocument& rDocument, String& rLibName );
void DeleteCurrent();
void NewModule();
void NewDialog();
void EndTabDialog( USHORT nRet );
TabDialog* pTabDlg;
virtual void ActivatePage();
virtual void DeactivatePage();
public:
ObjectPage( Window* pParent, const ResId& rResId, USHORT nMode );
void SetCurrentEntry( BasicEntryDescriptor& rDesc );
void SetTabDlg( TabDialog* p ) { pTabDlg = p;}
};
class SvxPasswordDialog;
class LibPage: public TabPage
{
protected:
FixedText aBasicsText;
ListBox aBasicsBox;
FixedText aLibText;
BasicCheckBox aLibBox;
PushButton aEditButton;
CancelButton aCloseButton;
PushButton aPasswordButton;
PushButton aExportButton;
PushButton aNewLibButton;
PushButton aInsertLibButton;
PushButton aDelButton;
ScriptDocument m_aCurDocument;
LibraryLocation m_eCurLocation;
DECL_LINK( TreeListHighlightHdl, SvTreeListBox * );
DECL_LINK( BasicSelectHdl, ListBox * );
DECL_LINK( ButtonHdl, Button * );
DECL_LINK( CheckPasswordHdl, SvxPasswordDialog * );
void CheckButtons();
void DeleteCurrent();
void NewLib();
void InsertLib();
void implExportLib( const String& aLibName, const String& aTargetURL,
const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& Handler );
void Export();
void ExportAsPackage( const String& aLibName );
void ExportAsBasic( const String& aLibName );
void EndTabDialog( USHORT nRet );
void FillListBox();
void InsertListBoxEntry( const ScriptDocument& rDocument, LibraryLocation eLocation );
void SetCurLib();
SvLBoxEntry* ImpInsertLibEntry( const String& rLibName, ULONG nPos );
virtual void ActivatePage();
virtual void DeactivatePage();
TabDialog* pTabDlg;
public:
LibPage( Window* pParent );
virtual ~LibPage();
void SetTabDlg( TabDialog* p ) { pTabDlg = p;}
};
// Helper functions
SbModule* createModImpl( Window* pWin, const ScriptDocument& rDocument,
BasicTreeListBox& rBasicBox, const String& rLibName, String aModName, bool bMain = false );
void createLibImpl( Window* pWin, const ScriptDocument& rDocument,
BasicCheckBox* pLibBox, BasicTreeListBox* pBasicBox );
#endif // _MODULDLG_HXX
<|endoftext|> |
<commit_before>/* ------------------------------------------------------------------
* Copyright (C) 1998-2009 PacketVideo
*
* 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 "dec_if.h"
#include <stdlib.h>
#include <string.h>
#include <pvamrwbdecoder_api.h>
#include <pvamrwbdecoder.h>
#include <pvamrwbdecoder_cnst.h>
#include <dtx.h>
/* This is basically a C rewrite of decode_amr_wb.cpp */
struct state {
void *st; /* State structure */
unsigned char *pt_st;
int16 *ScratchMem;
uint8* iInputBuf;
int16* iInputSampleBuf;
int16* iOutputBuf;
uint8 quality;
int16 mode;
int16 mode_old;
int16 frame_type;
int16 reset_flag;
int16 reset_flag_old;
int16 status;
RX_State rx_state;
};
void* D_IF_init(void) {
struct state* state = (struct state*) malloc(sizeof(struct state));
memset(state, 0, sizeof(*state));
state->iInputSampleBuf = (int16*) malloc(sizeof(int16)*KAMRWB_NB_BITS_MAX);
state->reset_flag = 0;
state->reset_flag_old = 1;
state->mode_old = 0;
state->rx_state.prev_ft = RX_SPEECH_GOOD;
state->rx_state.prev_mode = 0;
state->pt_st = (unsigned char*) malloc(pvDecoder_AmrWbMemRequirements());
pvDecoder_AmrWb_Init(&state->st, state->pt_st, &state->ScratchMem);
return state;
}
void D_IF_exit(void* s) {
struct state* state = (struct state*) s;
free(state->pt_st);
free(state->iInputSampleBuf);
free(state);
}
void D_IF_decode(void* s, const unsigned char* in, short* out, int bfi) {
struct state* state = (struct state*) s;
state->mode = (in[0] >> 3) & 0x0f;
in++;
state->quality = 1; /* ? */
mime_unsorting((uint8*) in, state->iInputSampleBuf, &state->frame_type, &state->mode, state->quality, &state->rx_state);
if ((state->frame_type == RX_NO_DATA) | (state->frame_type == RX_SPEECH_LOST)) {
state->mode = state->mode_old;
state->reset_flag = 0;
} else {
state->mode_old = state->mode;
/* if homed: check if this frame is another homing frame */
if (state->reset_flag_old == 1) {
/* only check until end of first subframe */
state->reset_flag = pvDecoder_AmrWb_homing_frame_test_first(state->iInputSampleBuf, state->mode);
}
}
/* produce encoder homing frame if homed & input=decoder homing frame */
if ((state->reset_flag != 0) && (state->reset_flag_old != 0)) {
/* set homing sequence ( no need to decode anything */
for (int16 i = 0; i < AMR_WB_PCM_FRAME; i++) {
out[i] = EHF_MASK;
}
} else {
int16 frameLength;
state->status = pvDecoder_AmrWb(state->mode,
state->iInputSampleBuf,
out,
&frameLength,
state->st,
state->frame_type,
state->ScratchMem);
}
for (int16 i = 0; i < AMR_WB_PCM_FRAME; i++) { /* Delete the 2 LSBs (14-bit output) */
out[i] &= 0xfffC;
}
/* if not homed: check whether current frame is a homing frame */
if (state->reset_flag_old == 0) {
/* check whole frame */
state->reset_flag = pvDecoder_AmrWb_homing_frame_test(state->iInputSampleBuf, state->mode);
}
/* reset decoder if current frame is a homing frame */
if (state->reset_flag != 0) {
pvDecoder_AmrWb_Reset(state->st, 1);
}
state->reset_flag_old = state->reset_flag;
}
<commit_msg>Handle the bad frame indicator parameter in the amr-wb decoder as well<commit_after>/* ------------------------------------------------------------------
* Copyright (C) 1998-2009 PacketVideo
*
* 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 "dec_if.h"
#include <stdlib.h>
#include <string.h>
#include <pvamrwbdecoder_api.h>
#include <pvamrwbdecoder.h>
#include <pvamrwbdecoder_cnst.h>
#include <dtx.h>
/* This is basically a C rewrite of decode_amr_wb.cpp */
struct state {
void *st; /* State structure */
unsigned char *pt_st;
int16 *ScratchMem;
uint8* iInputBuf;
int16* iInputSampleBuf;
int16* iOutputBuf;
uint8 quality;
int16 mode;
int16 mode_old;
int16 frame_type;
int16 reset_flag;
int16 reset_flag_old;
int16 status;
RX_State rx_state;
};
void* D_IF_init(void) {
struct state* state = (struct state*) malloc(sizeof(struct state));
memset(state, 0, sizeof(*state));
state->iInputSampleBuf = (int16*) malloc(sizeof(int16)*KAMRWB_NB_BITS_MAX);
state->reset_flag = 0;
state->reset_flag_old = 1;
state->mode_old = 0;
state->rx_state.prev_ft = RX_SPEECH_GOOD;
state->rx_state.prev_mode = 0;
state->pt_st = (unsigned char*) malloc(pvDecoder_AmrWbMemRequirements());
pvDecoder_AmrWb_Init(&state->st, state->pt_st, &state->ScratchMem);
return state;
}
void D_IF_exit(void* s) {
struct state* state = (struct state*) s;
free(state->pt_st);
free(state->iInputSampleBuf);
free(state);
}
void D_IF_decode(void* s, const unsigned char* in, short* out, int bfi) {
struct state* state = (struct state*) s;
state->mode = (in[0] >> 3) & 0x0f;
in++;
if (bfi) {
state->mode = 15; // NO_DATA
}
state->quality = 1; /* ? */
mime_unsorting((uint8*) in, state->iInputSampleBuf, &state->frame_type, &state->mode, state->quality, &state->rx_state);
if ((state->frame_type == RX_NO_DATA) | (state->frame_type == RX_SPEECH_LOST)) {
state->mode = state->mode_old;
state->reset_flag = 0;
} else {
state->mode_old = state->mode;
/* if homed: check if this frame is another homing frame */
if (state->reset_flag_old == 1) {
/* only check until end of first subframe */
state->reset_flag = pvDecoder_AmrWb_homing_frame_test_first(state->iInputSampleBuf, state->mode);
}
}
/* produce encoder homing frame if homed & input=decoder homing frame */
if ((state->reset_flag != 0) && (state->reset_flag_old != 0)) {
/* set homing sequence ( no need to decode anything */
for (int16 i = 0; i < AMR_WB_PCM_FRAME; i++) {
out[i] = EHF_MASK;
}
} else {
int16 frameLength;
state->status = pvDecoder_AmrWb(state->mode,
state->iInputSampleBuf,
out,
&frameLength,
state->st,
state->frame_type,
state->ScratchMem);
}
for (int16 i = 0; i < AMR_WB_PCM_FRAME; i++) { /* Delete the 2 LSBs (14-bit output) */
out[i] &= 0xfffC;
}
/* if not homed: check whether current frame is a homing frame */
if (state->reset_flag_old == 0) {
/* check whole frame */
state->reset_flag = pvDecoder_AmrWb_homing_frame_test(state->iInputSampleBuf, state->mode);
}
/* reset decoder if current frame is a homing frame */
if (state->reset_flag != 0) {
pvDecoder_AmrWb_Reset(state->st, 1);
}
state->reset_flag_old = state->reset_flag;
}
<|endoftext|> |
<commit_before>#include "3RVX.h"
int APIENTRY
wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow)
{
using namespace Gdiplus;
hInst = hInstance;
GdiplusStartupInput gdiplusStartupInput;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
mainWnd = CreateMainWnd(hInstance);
if(mainWnd == NULL)
return EXIT_FAILURE;
AllocConsole();
FILE *in, *out, *err;
freopen_s(&in, "CONIN$", "r", stdin);
freopen_s(&out, "CONOUT$", "w", stdout);
freopen_s(&err, "CONOUT$", "w", stderr);
printf("Starting up");
HRESULT hr = CoInitializeEx(NULL,
COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
/* Tell the program to initialize */
PostMessage(mainWnd, WM_3RVX_CONTROL, MSG_LOAD, NULL);
/* Start the event loop */
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
GdiplusShutdown(gdiplusToken);
return (int) msg.wParam;
}
void Init()
{
}
HWND CreateMainWnd(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = NULL;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = NULL;
wcex.cbWndExtra = NULL;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = L"3RVX";
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&wcex))
{
return NULL;
}
HWND hWnd = CreateWindowEx(
NULL,
L"3RVX", L"3RVX",
NULL, NULL, NULL, //your boat, gently down the stream
NULL, NULL, HWND_MESSAGE, NULL, hInstance, NULL);
return hWnd;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if(message == WM_3RVX_CONTROL)
{
switch(wParam)
{
case MSG_LOAD:
Init();
break;
case 101:
printf("%x\n", lParam);
break;
}
}
return DefWindowProc(hWnd, message, wParam, lParam);
}<commit_msg>Use new message definitions in main<commit_after>#include "3RVX.h"
#include "Controllers\Volume\IVolume.h"
#include "Controllers\Volume\CoreAudio.h"
int APIENTRY
wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow)
{
using namespace Gdiplus;
hInst = hInstance;
GdiplusStartupInput gdiplusStartupInput;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
mainWnd = CreateMainWnd(hInstance);
if(mainWnd == NULL)
return EXIT_FAILURE;
AllocConsole();
FILE *in, *out, *err;
freopen_s(&in, "CONIN$", "r", stdin);
freopen_s(&out, "CONOUT$", "w", stdout);
freopen_s(&err, "CONOUT$", "w", stderr);
printf("Starting...\n");
HRESULT hr = CoInitializeEx(NULL,
COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
/* Tell the program to initialize */
PostMessage(mainWnd, WM_3RVX_CONTROL, MSG_LOAD, NULL);
/* Start the event loop */
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
GdiplusShutdown(gdiplusToken);
return (int) msg.wParam;
}
void Init()
{
ca = new CoreAudio(mainWnd);
ca->Init();
}
HWND CreateMainWnd(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = NULL;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = NULL;
wcex.cbWndExtra = NULL;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = L"3RVX";
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&wcex))
{
return NULL;
}
HWND hWnd = CreateWindowEx(
NULL,
L"3RVX", L"3RVX",
NULL, NULL, NULL, //your boat, gently down the stream
NULL, NULL, HWND_MESSAGE, NULL, hInstance, NULL);
return hWnd;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (message == MSG_VOLCHNG) {
printf("Volume level: %.0f\n", ca->Volume() * 100.0f);
}
if (message == MSG_DEVCHNG) {
printf("Device change detected.\n");
ca->ReattachDefaultDevice();
}
if(message == WM_3RVX_CONTROL)
{
switch(wParam)
{
case MSG_LOAD:
Init();
break;
case 101:
printf("%x\n", lParam);
break;
}
}
return DefWindowProc(hWnd, message, wParam, lParam);
}<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2013 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "heuristic_spatial_split.h"
namespace embree
{
namespace isa
{
__forceinline SpatialSplit::Mapping::Mapping(const PrimInfo& pinfo)
{
const ssef diag = (ssef) pinfo.geomBounds.size();
scale = select(diag != 0.0f,rcp(diag) * ssef(BINS * 0.99f),ssef(0.0f));
ofs = (ssef) pinfo.geomBounds.lower;
}
__forceinline ssei SpatialSplit::Mapping::bin(const Vec3fa& p) const
{
const ssei i = floori((ssef(p)-ofs)*scale);
#if 1
assert(i[0] >=0 && i[0] < BINS);
assert(i[1] >=0 && i[1] < BINS);
assert(i[2] >=0 && i[2] < BINS);
return i;
#else
return clamp(i,ssei(0),ssei(BINS-1));
#endif
}
__forceinline float SpatialSplit::Mapping::pos(const int bin, const int dim) const {
return float(bin)/scale[dim]+ofs[dim];
}
__forceinline bool SpatialSplit::Mapping::invalid(const int dim) const {
return scale[dim] == 0.0f;
}
__forceinline SpatialSplit::BinInfo::BinInfo()
{
for (size_t i=0; i<BINS; i++) {
bounds[i][0] = bounds[i][1] = bounds[i][2] = bounds[i][3] = empty;
numBegin[i] = numEnd[i] = 0;
}
}
__forceinline void SpatialSplit::BinInfo::bin (const Bezier1* prims, size_t N, const PrimInfo& pinfo, const Mapping& mapping)
{
for (size_t i=0; i<N; i++)
{
const ssei bin0 = mapping.bin(min(prims[i].p0,prims[i].p3));
const ssei bin1 = mapping.bin(max(prims[i].p0,prims[i].p3));
for (size_t dim=0; dim<3; dim++)
{
size_t bin;
Bezier1 curve = prims[i];
for (bin=bin0[dim]; bin<bin1[dim]; bin++)
{
const float pos = mapping.pos(bin+1,dim);
Bezier1 bincurve,restcurve;
if (curve.split(dim,pos,bincurve,restcurve)) {
bounds[bin][dim].extend(bincurve.bounds());
curve = restcurve;
}
}
numBegin[bin0[dim]][dim]++;
numEnd [bin1[dim]][dim]++;
bounds [bin][dim].extend(curve.bounds());
}
}
}
__forceinline void SpatialSplit::BinInfo::bin(BezierRefList& prims, const PrimInfo& pinfo, const Mapping& mapping)
{
BezierRefList::iterator i=prims;
while (BezierRefList::item* block = i.next())
bin(block->base(),block->size(),pinfo,mapping);
}
__forceinline void SpatialSplit::BinInfo::merge (const BinInfo& other)
{
for (size_t i=0; i<BINS; i++)
{
numBegin[i] += other.numBegin[i];
numEnd[i] += other.numEnd[i];
bounds[i][0].extend(other.bounds[i][0]);
bounds[i][1].extend(other.bounds[i][1]);
bounds[i][2].extend(other.bounds[i][2]);
}
}
__forceinline SpatialSplit::Split SpatialSplit::BinInfo::best(BezierRefList& prims, const PrimInfo& pinfo, const Mapping& mapping)
{
/* sweep from right to left and compute parallel prefix of merged bounds */
ssef rAreas[BINS];
ssei rCounts[BINS];
ssei count = 0; BBox3fa bx = empty; BBox3fa by = empty; BBox3fa bz = empty;
for (size_t i=BINS-1; i>0; i--)
{
count += numEnd[i];
rCounts[i] = count;
bx.extend(bounds[i][0]); rAreas[i][0] = halfArea(bx);
by.extend(bounds[i][1]); rAreas[i][1] = halfArea(by);
bz.extend(bounds[i][2]); rAreas[i][2] = halfArea(bz);
}
/* sweep from left to right and compute SAH */
ssei ii = 1; ssef vbestSAH = pos_inf; ssei vbestPos = 0;
count = 0; bx = empty; by = empty; bz = empty;
for (size_t i=1; i<BINS; i++, ii+=1)
{
count += numBegin[i-1];
bx.extend(bounds[i-1][0]); float Ax = halfArea(bx);
by.extend(bounds[i-1][1]); float Ay = halfArea(by);
bz.extend(bounds[i-1][2]); float Az = halfArea(bz);
const ssef lArea = ssef(Ax,Ay,Az,Az);
const ssef rArea = rAreas[i];
const ssei lCount = blocks(count);
const ssei rCount = blocks(rCounts[i]);
const ssef sah = lArea*ssef(lCount) + rArea*ssef(rCount);
vbestPos = select(sah < vbestSAH,ii ,vbestPos);
vbestSAH = select(sah < vbestSAH,sah,vbestSAH);
}
/* find best dimension */
float bestSAH = inf;
int bestDim = -1;
int bestPos = 0.0f;
for (size_t dim=0; dim<3; dim++)
{
/* ignore zero sized dimensions */
if (unlikely(mapping.invalid(dim)))
continue;
/* test if this is a better dimension */
if (vbestSAH[dim] < bestSAH && vbestPos[dim] != 0) {
bestDim = dim;
bestPos = vbestPos[dim]; //mapping.pos(vbestPos[dim],dim);
bestSAH = vbestSAH[dim];
}
}
/* compute bounds of left and right side */
if (bestDim == -1)
return Split(inf,-1,0.0f,mapping);
/* calculate bounding box of left and right side */
BBox3fa lbounds = empty, rbounds = empty;
size_t lnum = 0, rnum = 0;
for (BezierRefList::block_iterator_unsafe i = prims; i; i++)
{
const int bin0 = mapping.bin(min(i->p0,i->p3))[bestDim];
const int bin1 = mapping.bin(max(i->p0,i->p3))[bestDim];
//const float p0p = i->p0[bestDim];
//const float p3p = i->p3[bestDim];
/* sort to the left side */
//if (p0p <= bestPos && p3p <= bestPos) {
if (bin0 < bestPos && bin1 < bestPos) {
lbounds.extend(i->bounds()); lnum++;
continue;
}
/* sort to the right side */
//if (p0p >= bestPos && p3p >= bestPos) {
if (bin0 >= bestPos && bin1 >= bestPos) {
rbounds.extend(i->bounds()); rnum++;
continue;
}
Bezier1 left,right;
float fpos = mapping.pos(bestPos,bestDim);
if (i->split(bestDim,fpos,left,right)) {
lbounds.extend(left .bounds()); lnum++;
rbounds.extend(right.bounds()); rnum++;
continue;
}
lbounds.extend(i->bounds()); lnum++;
}
if (lnum == 0 || rnum == 0)
return Split(inf,-1,0.0f,mapping);
#if 0
float sah = float(lnum)*halfArea(lbounds) + float(rnum)*halfArea(rbounds);
return Split(sah,bestDim,bestPos,mapping);
#else // FIXME: there is something wrong, this code block should work!!!
{
size_t lnum = 0, rnum = 0;
BBox3fa lbounds = empty, rbounds = empty;
for (size_t i=0; i<bestPos; i++) { lnum+=numBegin[i][bestDim]; lbounds.extend(bounds[i][bestDim]); }
for (size_t i=bestPos; i<BINS; i++) { rnum+=numEnd[i][bestDim]; rbounds.extend(bounds[i][bestDim]); }
float sah = float(lnum)*halfArea(lbounds) + float(rnum)*halfArea(rbounds);
return Split(sah,bestDim,bestPos,mapping);
}
#endif
}
template<>
const SpatialSplit::Split SpatialSplit::find<false>(size_t threadIndex, size_t threadCount, BezierRefList& prims, const PrimInfo& pinfo)
{
BinInfo binner;
Mapping mapping(pinfo);
binner.bin(prims,pinfo,mapping);
return binner.best(prims,pinfo,mapping);
}
SpatialSplit::TaskBinParallel::TaskBinParallel(size_t threadIndex, size_t threadCount, BezierRefList& prims, const PrimInfo& pinfo, const Mapping& mapping)
: iter(prims), pinfo(pinfo), mapping(mapping)
{
/* parallel binning */
size_t numTasks = min(maxTasks,threadCount);
TaskScheduler::executeTask(threadIndex,numTasks,_task_bin_parallel,this,numTasks,"build::task_bin_parallel");
/* reduction of bin informations */
BinInfo bins = binners[0];
for (size_t i=1; i<numTasks; i++)
bins.merge(binners[i]);
/* calculation of best split */
split = bins.best(prims,pinfo,mapping);
}
void SpatialSplit::TaskBinParallel::task_bin_parallel(size_t threadIndex, size_t threadCount, size_t taskIndex, size_t taskCount, TaskScheduler::Event* event)
{
while (BezierRefList::item* block = iter.next())
binners[taskIndex].bin(block->base(),block->size(),pinfo,mapping);
}
template<>
const SpatialSplit::Split SpatialSplit::find<true>(size_t threadIndex, size_t threadCount, BezierRefList& prims, const PrimInfo& pinfo)
{
const Mapping mapping(pinfo);
return TaskBinParallel(threadIndex,threadCount,prims,pinfo,mapping).split;
}
template<>
void SpatialSplit::Split::split<false>(size_t threadIndex,size_t threadCount, PrimRefBlockAlloc<Bezier1>& alloc,
BezierRefList& prims,
BezierRefList& lprims_o, PrimInfo& linfo_o,
BezierRefList& rprims_o, PrimInfo& rinfo_o) const
{
/* sort each curve to left, right, or left and right */
BezierRefList::item* lblock = lprims_o.insert(alloc.malloc(threadIndex));
BezierRefList::item* rblock = rprims_o.insert(alloc.malloc(threadIndex));
while (BezierRefList::item* block = prims.take())
{
for (size_t i=0; i<block->size(); i++)
{
const Bezier1& prim = block->at(i);
const int bin0 = mapping.bin(min(prim.p0,prim.p3))[dim];
const int bin1 = mapping.bin(max(prim.p0,prim.p3))[dim];
//const float p0p = prim.p0[dim];
//const float p3p = prim.p3[dim];
/* sort to the left side */
if (bin0 < pos && bin1 < pos)
{
linfo_o.add(prim.bounds(),prim.center());
if (likely(lblock->insert(prim))) continue;
lblock = lprims_o.insert(alloc.malloc(threadIndex));
lblock->insert(prim);
continue;
}
/* sort to the right side */
if (bin0 >= pos && bin1 >= pos)
{
rinfo_o.add(prim.bounds(),prim.center());
if (likely(rblock->insert(prim))) continue;
rblock = rprims_o.insert(alloc.malloc(threadIndex));
rblock->insert(prim);
continue;
}
/* split and sort to left and right */
Bezier1 left,right;
float fpos = mapping.pos(pos,dim);
if (prim.split(dim,fpos,left,right))
{
linfo_o.add(left.bounds(),left.center());
if (!lblock->insert(left)) {
lblock = lprims_o.insert(alloc.malloc(threadIndex));
lblock->insert(left);
}
rinfo_o.add(right.bounds(),right.center());
if (!rblock->insert(right)) {
rblock = rprims_o.insert(alloc.malloc(threadIndex));
rblock->insert(right);
}
continue;
}
/* insert to left side as fallback */
linfo_o.add(prim.bounds(),prim.center());
if (!lblock->insert(prim)) {
lblock = lprims_o.insert(alloc.malloc(threadIndex));
lblock->insert(prim);
}
}
alloc.free(threadIndex,block);
}
}
SpatialSplit::TaskSplitParallel::TaskSplitParallel(size_t threadIndex, size_t threadCount, const Split* split,
PrimRefBlockAlloc<Bezier1>& alloc, BezierRefList& prims,
BezierRefList& lprims_o, PrimInfo& linfo_o,
BezierRefList& rprims_o, PrimInfo& rinfo_o)
: split(split), alloc(alloc), prims(prims), lprims_o(lprims_o), linfo_o(linfo_o), rprims_o(rprims_o), rinfo_o(rinfo_o)
{
/* parallel calculation of centroid bounds */
size_t numTasks = min(maxTasks,threadCount);
TaskScheduler::executeTask(threadIndex,numTasks,_task_split_parallel,this,numTasks,"build::task_split_parallel");
/* reduction of bounding info */
linfo_o = linfos[0];
rinfo_o = rinfos[0];
for (size_t i=1; i<numTasks; i++) {
linfo_o.merge(linfos[i]);
rinfo_o.merge(rinfos[i]);
}
}
void SpatialSplit::TaskSplitParallel::task_split_parallel(size_t threadIndex, size_t threadCount, size_t taskIndex, size_t taskCount, TaskScheduler::Event* event)
{
split->split(threadIndex,threadCount,alloc,prims,lprims_o,linfos[taskIndex],rprims_o,rinfos[taskIndex]);
}
template<>
void SpatialSplit::Split::split<true>(size_t threadIndex, size_t threadCount,
PrimRefBlockAlloc<Bezier1>& alloc, BezierRefList& prims,
BezierRefList& lprims_o, PrimInfo& linfo_o,
BezierRefList& rprims_o, PrimInfo& rinfo_o) const
{
TaskSplitParallel(threadIndex,threadCount,this,alloc,prims,lprims_o,linfo_o,rprims_o,rinfo_o);
}
}
}
<commit_msg>performance improvement of bounding calculation in spatial splitter<commit_after>// ======================================================================== //
// Copyright 2009-2013 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "heuristic_spatial_split.h"
namespace embree
{
namespace isa
{
__forceinline SpatialSplit::Mapping::Mapping(const PrimInfo& pinfo)
{
const ssef diag = (ssef) pinfo.geomBounds.size();
scale = select(diag != 0.0f,rcp(diag) * ssef(BINS * 0.99f),ssef(0.0f));
ofs = (ssef) pinfo.geomBounds.lower;
}
__forceinline ssei SpatialSplit::Mapping::bin(const Vec3fa& p) const
{
const ssei i = floori((ssef(p)-ofs)*scale);
#if 1
assert(i[0] >=0 && i[0] < BINS);
assert(i[1] >=0 && i[1] < BINS);
assert(i[2] >=0 && i[2] < BINS);
return i;
#else
return clamp(i,ssei(0),ssei(BINS-1));
#endif
}
__forceinline float SpatialSplit::Mapping::pos(const int bin, const int dim) const {
return float(bin)/scale[dim]+ofs[dim];
}
__forceinline bool SpatialSplit::Mapping::invalid(const int dim) const {
return scale[dim] == 0.0f;
}
__forceinline SpatialSplit::BinInfo::BinInfo()
{
for (size_t i=0; i<BINS; i++) {
bounds[i][0] = bounds[i][1] = bounds[i][2] = bounds[i][3] = empty;
numBegin[i] = numEnd[i] = 0;
}
}
__forceinline void SpatialSplit::BinInfo::bin (const Bezier1* prims, size_t N, const PrimInfo& pinfo, const Mapping& mapping)
{
for (size_t i=0; i<N; i++)
{
const ssei bin0 = mapping.bin(min(prims[i].p0,prims[i].p3));
const ssei bin1 = mapping.bin(max(prims[i].p0,prims[i].p3));
for (size_t dim=0; dim<3; dim++)
{
size_t bin;
Bezier1 curve = prims[i];
for (bin=bin0[dim]; bin<bin1[dim]; bin++)
{
const float pos = mapping.pos(bin+1,dim);
Bezier1 bincurve,restcurve;
if (curve.split(dim,pos,bincurve,restcurve)) {
bounds[bin][dim].extend(bincurve.bounds());
curve = restcurve;
}
}
numBegin[bin0[dim]][dim]++;
numEnd [bin1[dim]][dim]++;
bounds [bin][dim].extend(curve.bounds());
}
}
}
__forceinline void SpatialSplit::BinInfo::bin(BezierRefList& prims, const PrimInfo& pinfo, const Mapping& mapping)
{
BezierRefList::iterator i=prims;
while (BezierRefList::item* block = i.next())
bin(block->base(),block->size(),pinfo,mapping);
}
__forceinline void SpatialSplit::BinInfo::merge (const BinInfo& other)
{
for (size_t i=0; i<BINS; i++)
{
numBegin[i] += other.numBegin[i];
numEnd[i] += other.numEnd[i];
bounds[i][0].extend(other.bounds[i][0]);
bounds[i][1].extend(other.bounds[i][1]);
bounds[i][2].extend(other.bounds[i][2]);
}
}
__forceinline SpatialSplit::Split SpatialSplit::BinInfo::best(BezierRefList& prims, const PrimInfo& pinfo, const Mapping& mapping)
{
/* sweep from right to left and compute parallel prefix of merged bounds */
ssef rAreas[BINS];
ssei rCounts[BINS];
ssei count = 0; BBox3fa bx = empty; BBox3fa by = empty; BBox3fa bz = empty;
for (size_t i=BINS-1; i>0; i--)
{
count += numEnd[i];
rCounts[i] = count;
bx.extend(bounds[i][0]); rAreas[i][0] = halfArea(bx);
by.extend(bounds[i][1]); rAreas[i][1] = halfArea(by);
bz.extend(bounds[i][2]); rAreas[i][2] = halfArea(bz);
}
/* sweep from left to right and compute SAH */
ssei ii = 1; ssef vbestSAH = pos_inf; ssei vbestPos = 0;
count = 0; bx = empty; by = empty; bz = empty;
for (size_t i=1; i<BINS; i++, ii+=1)
{
count += numBegin[i-1];
bx.extend(bounds[i-1][0]); float Ax = halfArea(bx);
by.extend(bounds[i-1][1]); float Ay = halfArea(by);
bz.extend(bounds[i-1][2]); float Az = halfArea(bz);
const ssef lArea = ssef(Ax,Ay,Az,Az);
const ssef rArea = rAreas[i];
const ssei lCount = blocks(count);
const ssei rCount = blocks(rCounts[i]);
const ssef sah = lArea*ssef(lCount) + rArea*ssef(rCount);
vbestPos = select(sah < vbestSAH,ii ,vbestPos);
vbestSAH = select(sah < vbestSAH,sah,vbestSAH);
}
/* find best dimension */
float bestSAH = inf;
int bestDim = -1;
int bestPos = 0.0f;
for (size_t dim=0; dim<3; dim++)
{
/* ignore zero sized dimensions */
if (unlikely(mapping.invalid(dim)))
continue;
/* test if this is a better dimension */
if (vbestSAH[dim] < bestSAH && vbestPos[dim] != 0) {
bestDim = dim;
bestPos = vbestPos[dim];
bestSAH = vbestSAH[dim];
}
}
/* return invalid split if no split found */
if (bestDim == -1)
return Split(inf,-1,0.0f,mapping);
/* compute bounds of left and right side */
size_t lnum = 0, rnum = 0;
BBox3fa lbounds = empty, rbounds = empty;
for (size_t i=0; i<bestPos; i++) { lnum+=numBegin[i][bestDim]; lbounds.extend(bounds[i][bestDim]); }
for (size_t i=bestPos; i<BINS; i++) { rnum+=numEnd[i][bestDim]; rbounds.extend(bounds[i][bestDim]); }
/* return invalid split if no progress made */
if (lnum == 0 || rnum == 0)
return Split(inf,-1,0.0f,mapping);
/* calculate SAH and return best found split */
float sah = float(lnum)*halfArea(lbounds) + float(rnum)*halfArea(rbounds);
return Split(sah,bestDim,bestPos,mapping);
}
template<>
const SpatialSplit::Split SpatialSplit::find<false>(size_t threadIndex, size_t threadCount, BezierRefList& prims, const PrimInfo& pinfo)
{
BinInfo binner;
Mapping mapping(pinfo);
binner.bin(prims,pinfo,mapping);
return binner.best(prims,pinfo,mapping);
}
SpatialSplit::TaskBinParallel::TaskBinParallel(size_t threadIndex, size_t threadCount, BezierRefList& prims, const PrimInfo& pinfo, const Mapping& mapping)
: iter(prims), pinfo(pinfo), mapping(mapping)
{
/* parallel binning */
size_t numTasks = min(maxTasks,threadCount);
TaskScheduler::executeTask(threadIndex,numTasks,_task_bin_parallel,this,numTasks,"build::task_bin_parallel");
/* reduction of bin informations */
BinInfo bins = binners[0];
for (size_t i=1; i<numTasks; i++)
bins.merge(binners[i]);
/* calculation of best split */
split = bins.best(prims,pinfo,mapping);
}
void SpatialSplit::TaskBinParallel::task_bin_parallel(size_t threadIndex, size_t threadCount, size_t taskIndex, size_t taskCount, TaskScheduler::Event* event)
{
while (BezierRefList::item* block = iter.next())
binners[taskIndex].bin(block->base(),block->size(),pinfo,mapping);
}
template<>
const SpatialSplit::Split SpatialSplit::find<true>(size_t threadIndex, size_t threadCount, BezierRefList& prims, const PrimInfo& pinfo)
{
const Mapping mapping(pinfo);
return TaskBinParallel(threadIndex,threadCount,prims,pinfo,mapping).split;
}
template<>
void SpatialSplit::Split::split<false>(size_t threadIndex,size_t threadCount, PrimRefBlockAlloc<Bezier1>& alloc,
BezierRefList& prims,
BezierRefList& lprims_o, PrimInfo& linfo_o,
BezierRefList& rprims_o, PrimInfo& rinfo_o) const
{
/* sort each curve to left, right, or left and right */
BezierRefList::item* lblock = lprims_o.insert(alloc.malloc(threadIndex));
BezierRefList::item* rblock = rprims_o.insert(alloc.malloc(threadIndex));
while (BezierRefList::item* block = prims.take())
{
for (size_t i=0; i<block->size(); i++)
{
const Bezier1& prim = block->at(i);
const int bin0 = mapping.bin(min(prim.p0,prim.p3))[dim];
const int bin1 = mapping.bin(max(prim.p0,prim.p3))[dim];
/* sort to the left side */
if (bin0 < pos && bin1 < pos)
{
linfo_o.add(prim.bounds(),prim.center());
if (likely(lblock->insert(prim))) continue;
lblock = lprims_o.insert(alloc.malloc(threadIndex));
lblock->insert(prim);
continue;
}
/* sort to the right side */
if (bin0 >= pos && bin1 >= pos)
{
rinfo_o.add(prim.bounds(),prim.center());
if (likely(rblock->insert(prim))) continue;
rblock = rprims_o.insert(alloc.malloc(threadIndex));
rblock->insert(prim);
continue;
}
/* split and sort to left and right */
Bezier1 left,right;
float fpos = mapping.pos(pos,dim);
if (prim.split(dim,fpos,left,right))
{
linfo_o.add(left.bounds(),left.center());
if (!lblock->insert(left)) {
lblock = lprims_o.insert(alloc.malloc(threadIndex));
lblock->insert(left);
}
rinfo_o.add(right.bounds(),right.center());
if (!rblock->insert(right)) {
rblock = rprims_o.insert(alloc.malloc(threadIndex));
rblock->insert(right);
}
continue;
}
/* insert to left side as fallback */
linfo_o.add(prim.bounds(),prim.center());
if (!lblock->insert(prim)) {
lblock = lprims_o.insert(alloc.malloc(threadIndex));
lblock->insert(prim);
}
}
alloc.free(threadIndex,block);
}
}
SpatialSplit::TaskSplitParallel::TaskSplitParallel(size_t threadIndex, size_t threadCount, const Split* split,
PrimRefBlockAlloc<Bezier1>& alloc, BezierRefList& prims,
BezierRefList& lprims_o, PrimInfo& linfo_o,
BezierRefList& rprims_o, PrimInfo& rinfo_o)
: split(split), alloc(alloc), prims(prims), lprims_o(lprims_o), linfo_o(linfo_o), rprims_o(rprims_o), rinfo_o(rinfo_o)
{
/* parallel calculation of centroid bounds */
size_t numTasks = min(maxTasks,threadCount);
TaskScheduler::executeTask(threadIndex,numTasks,_task_split_parallel,this,numTasks,"build::task_split_parallel");
/* reduction of bounding info */
linfo_o = linfos[0];
rinfo_o = rinfos[0];
for (size_t i=1; i<numTasks; i++) {
linfo_o.merge(linfos[i]);
rinfo_o.merge(rinfos[i]);
}
}
void SpatialSplit::TaskSplitParallel::task_split_parallel(size_t threadIndex, size_t threadCount, size_t taskIndex, size_t taskCount, TaskScheduler::Event* event)
{
split->split(threadIndex,threadCount,alloc,prims,lprims_o,linfos[taskIndex],rprims_o,rinfos[taskIndex]);
}
template<>
void SpatialSplit::Split::split<true>(size_t threadIndex, size_t threadCount,
PrimRefBlockAlloc<Bezier1>& alloc, BezierRefList& prims,
BezierRefList& lprims_o, PrimInfo& linfo_o,
BezierRefList& rprims_o, PrimInfo& rinfo_o) const
{
TaskSplitParallel(threadIndex,threadCount,this,alloc,prims,lprims_o,linfo_o,rprims_o,rinfo_o);
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Discard TCP Server */
#include <string.h>
#include "arp.h"
#include "conduit.h"
#include "dix.h"
#include "inet.h"
#include "inet4.h"
#include "inet4address.h"
#include "tcp.h"
extern int esInit(Object** nameSpace);
extern void esRegisterInternetProtocol(es::Context* context);
static void* discard(void* param);
int nunThreads = 0;
Handle<es::Resolver> resolver;
int main()
{
Object* root = NULL;
esInit(&root);
Handle<es::Context> context(root);
esRegisterInternetProtocol(context);
// Create resolver object
resolver = context->lookup("network/resolver");
// Create internet config object
Handle<es::InternetConfig> config = context->lookup("network/config");
// Setup DIX interface
Handle<es::NetworkInterface> nic = context->lookup("device/ethernet");
nic->start();
int dixID = config->addInterface(nic);// add Interface
esReport("dixID: %d\n", dixID);
ASSERT(config->getScopeID(nic) == dixID);
// 192.168.2.40 Register host address
InAddr addr = { htonl(192 << 24 | 168 << 16 | 2 << 8 | 40) };
Handle<es::InternetAddress> host = resolver->getHostByAddress(&addr.addr, sizeof addr, dixID);
config->addAddress(host, 16);
esSleep(90000000); // Wait for the host address to be settled.
Handle<es::Socket> serverSocket = host->socket(AF_INET, es::Socket::Stream, 9);
serverSocket->listen(5);
es::Socket* discardServer;
while (true)
{
while ((discardServer = serverSocket->accept()) == 0)
{
}
esReport("accepted\n");
discard(discardServer);
}
config->removeAddress(host);
nic->stop();
esReport("done.\n");
}
// discard service
static void* discard(void* param)
{
numThreads++;
int id = numThreads;
Socket* discardServer = static_cast<Socket*>(param);
char input[9],prev[9];
strcpy(prev,"dummy");
int timeoutcount = 0;
while (timeoutcount <= 10)
{
discardServer->read(input,9);
if (strcmp(prev,input) == 0)
{
timeoutcount++;
esSleep(9000000);
}
else
{
// discard any data sent. Do not reply
esReport(" discarding \"%s\" by thread %d\n",input,id);
strcpy(prev,input);
timeoutcount = 0;
}
memset(input,0,9);
}
discardServer->close();
discardServer->release();
}
<commit_msg>a glitch error fix<commit_after>/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Discard TCP Server */
#include <string.h>
#include "arp.h"
#include "conduit.h"
#include "dix.h"
#include "inet.h"
#include "inet4.h"
#include "inet4address.h"
#include "tcp.h"
extern int esInit(Object** nameSpace);
extern void esRegisterInternetProtocol(es::Context* context);
static void* discard(void* param);
int numThreads = 0;
Handle<es::Resolver> resolver;
int main()
{
Object* root = NULL;
esInit(&root);
Handle<es::Context> context(root);
esRegisterInternetProtocol(context);
// Create resolver object
resolver = context->lookup("network/resolver");
// Create internet config object
Handle<es::InternetConfig> config = context->lookup("network/config");
// Setup DIX interface
Handle<es::NetworkInterface> nic = context->lookup("device/ethernet");
nic->start();
int dixID = config->addInterface(nic);// add Interface
esReport("dixID: %d\n", dixID);
ASSERT(config->getScopeID(nic) == dixID);
// 192.168.2.40 Register host address
InAddr addr = { htonl(192 << 24 | 168 << 16 | 2 << 8 | 40) };
Handle<es::InternetAddress> host = resolver->getHostByAddress(&addr.addr, sizeof addr, dixID);
config->addAddress(host, 16);
esSleep(90000000); // Wait for the host address to be settled.
Handle<es::Socket> serverSocket = host->socket(AF_INET, es::Socket::Stream, 9);
serverSocket->listen(5);
es::Socket* discardServer;
while (true)
{
while ((discardServer = serverSocket->accept()) == 0)
{
}
esReport("accepted\n");
discard(discardServer);
}
config->removeAddress(host);
nic->stop();
esReport("done.\n");
}
// discard service
static void* discard(void* param)
{
numThreads++;
int id = numThreads;
Socket* discardServer = static_cast<Socket*>(param);
char input[9],prev[9];
strcpy(prev,"dummy");
int timeoutcount = 0;
while (timeoutcount <= 10)
{
discardServer->read(input,9);
if (strcmp(prev,input) == 0)
{
timeoutcount++;
esSleep(9000000);
}
else
{
// discard any data sent. Do not reply
esReport(" discarding \"%s\" by thread %d\n",input,id);
strcpy(prev,input);
timeoutcount = 0;
}
memset(input,0,9);
}
discardServer->close();
discardServer->release();
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// peloton_service.cpp
//
// Identification: src/backend/networking/peloton_service.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "backend/networking/peloton_service.h"
#include "backend/networking/peloton_endpoint.h"
#include "backend/networking/rpc_server.h"
#include "backend/common/logger.h"
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <iostream>
namespace peloton {
namespace networking {
void PelotonService::TransactionInit(::google::protobuf::RpcController* controller,
const TransactionInitRequest* request,
TransactionInitResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionWork(::google::protobuf::RpcController* controller,
const TransactionWorkRequest* request,
TransactionWorkResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionPrefetch(::google::protobuf::RpcController* controller,
const TransactionPrefetchResult* request,
TransactionPrefetchAcknowledgement* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionMap(::google::protobuf::RpcController* controller,
const TransactionMapRequest* request,
TransactionMapResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionReduce(::google::protobuf::RpcController* controller,
const TransactionReduceRequest* request,
TransactionReduceResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionPrepare(::google::protobuf::RpcController* controller,
const TransactionPrepareRequest* request,
TransactionPrepareResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionFinish(::google::protobuf::RpcController* controller,
const TransactionFinishRequest* request,
TransactionFinishResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionRedirect(::google::protobuf::RpcController* controller,
const TransactionRedirectRequest* request,
TransactionRedirectResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionDebug(::google::protobuf::RpcController* controller,
const TransactionDebugRequest* request,
TransactionDebugResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::SendData(::google::protobuf::RpcController* controller,
const SendDataRequest* request,
SendDataResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::Initialize(::google::protobuf::RpcController* controller,
const InitializeRequest* request,
InitializeResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::ShutdownPrepare(::google::protobuf::RpcController* controller,
const ShutdownPrepareRequest* request,
ShutdownPrepareResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::Shutdown(::google::protobuf::RpcController* controller,
const ShutdownRequest* request,
ShutdownResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::Heartbeat(::google::protobuf::RpcController* controller,
const HeartbeatRequest* request,
HeartbeatResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
/*
* If request is not null, this is a rpc call, server should handle the reqeust
*/
if (request != NULL) {
LOG_TRACE("Received from client, sender site: %d, last_txn_id: %lld",
request->sender_site(),
request->last_transaction_id());
response->set_sender_site(9876);
Status status = ABORT_SPECULATIVE;
response->set_status(status);
// if callback exist, run it
if (done) {
done->Run();
}
}
/*
* Here is for the client callback for Heartbeat
*/
else {
// proecess the response
LOG_TRACE("proecess the Heartbeat response");
if (response->has_sender_site() == true) {
std::cout << "sender site: " << response->sender_site() << std::endl;
} else {
std::cout << "No response: site is null" << std::endl;
}
if (response->has_status() == true) {
std::cout << "Status: " << response->status() << std::endl;
} else {
std::cout << "No response: status is null" << std::endl;
}
}
}
void PelotonService::UnevictData(::google::protobuf::RpcController* controller,
const UnevictDataRequest* request,
UnevictDataResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TimeSync(::google::protobuf::RpcController* controller,
const TimeSyncRequest* request,
TimeSyncResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
/*
void StartPelotonService() {
::google::protobuf::Service* service = NULL;
try {
RpcServer rpc_server(PELOTON_ENDPOINT_ADDR);
service = new PelotonService();
rpc_server.RegisterService(service);
rpc_server.Start();
} catch (peloton::message::exception& e) {
std::cerr << "NN EXCEPTION : " << e.what() << std::endl;
delete service;
} catch (std::exception& e) {
std::cerr << "STD EXCEPTION : " << e.what() << std::endl;
delete service;
} catch (...) {
std::cerr << "UNTRAPPED EXCEPTION " << std::endl;
delete service;
}
}
*/
} // namespace networking
} // namespace peloton
<commit_msg>Fix compilation error<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// peloton_service.cpp
//
// Identification: src/backend/networking/peloton_service.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "backend/networking/peloton_service.h"
#include "backend/networking/peloton_endpoint.h"
#include "backend/networking/rpc_server.h"
#include "backend/common/logger.h"
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <iostream>
namespace peloton {
namespace networking {
void PelotonService::TransactionInit(::google::protobuf::RpcController* controller,
const TransactionInitRequest* request,
TransactionInitResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionWork(::google::protobuf::RpcController* controller,
const TransactionWorkRequest* request,
TransactionWorkResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionPrefetch(::google::protobuf::RpcController* controller,
const TransactionPrefetchResult* request,
TransactionPrefetchAcknowledgement* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionMap(::google::protobuf::RpcController* controller,
const TransactionMapRequest* request,
TransactionMapResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionReduce(::google::protobuf::RpcController* controller,
const TransactionReduceRequest* request,
TransactionReduceResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionPrepare(::google::protobuf::RpcController* controller,
const TransactionPrepareRequest* request,
TransactionPrepareResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionFinish(::google::protobuf::RpcController* controller,
const TransactionFinishRequest* request,
TransactionFinishResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionRedirect(::google::protobuf::RpcController* controller,
const TransactionRedirectRequest* request,
TransactionRedirectResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TransactionDebug(::google::protobuf::RpcController* controller,
const TransactionDebugRequest* request,
TransactionDebugResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::SendData(::google::protobuf::RpcController* controller,
const SendDataRequest* request,
SendDataResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::Initialize(::google::protobuf::RpcController* controller,
const InitializeRequest* request,
InitializeResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::ShutdownPrepare(::google::protobuf::RpcController* controller,
const ShutdownPrepareRequest* request,
ShutdownPrepareResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::Shutdown(::google::protobuf::RpcController* controller,
const ShutdownRequest* request,
ShutdownResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::Heartbeat(::google::protobuf::RpcController* controller,
const HeartbeatRequest* request,
HeartbeatResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
/*
* If request is not null, this is a rpc call, server should handle the reqeust
*/
if (request != NULL) {
LOG_TRACE("Received from client, sender site: %d, last_txn_id: %ld",
request->sender_site(),
request->last_transaction_id());
response->set_sender_site(9876);
Status status = ABORT_SPECULATIVE;
response->set_status(status);
// if callback exist, run it
if (done) {
done->Run();
}
}
/*
* Here is for the client callback for Heartbeat
*/
else {
// proecess the response
LOG_TRACE("proecess the Heartbeat response");
if (response->has_sender_site() == true) {
std::cout << "sender site: " << response->sender_site() << std::endl;
} else {
std::cout << "No response: site is null" << std::endl;
}
if (response->has_status() == true) {
std::cout << "Status: " << response->status() << std::endl;
} else {
std::cout << "No response: status is null" << std::endl;
}
}
}
void PelotonService::UnevictData(::google::protobuf::RpcController* controller,
const UnevictDataRequest* request,
UnevictDataResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
void PelotonService::TimeSync(::google::protobuf::RpcController* controller,
const TimeSyncRequest* request,
TimeSyncResponse* response,
::google::protobuf::Closure* done) {
// TODO: controller should be set, we probably use it in the future
if (controller->Failed()) {
std::string error = controller->ErrorText();
LOG_TRACE( "PelotonService with controller failed:%s ", error.c_str() );
}
// TODO: process request and set response
std::cout << request << response;
// if callback exist, run it
if (done) {
done->Run();
}
}
/*
void StartPelotonService() {
::google::protobuf::Service* service = NULL;
try {
RpcServer rpc_server(PELOTON_ENDPOINT_ADDR);
service = new PelotonService();
rpc_server.RegisterService(service);
rpc_server.Start();
} catch (peloton::message::exception& e) {
std::cerr << "NN EXCEPTION : " << e.what() << std::endl;
delete service;
} catch (std::exception& e) {
std::cerr << "STD EXCEPTION : " << e.what() << std::endl;
delete service;
} catch (...) {
std::cerr << "UNTRAPPED EXCEPTION " << std::endl;
delete service;
}
}
*/
} // namespace networking
} // namespace peloton
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* Copyright (c) 2007-2008 The Florida State University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Gabe Black
*/
#ifndef __ARM_FAULTS_HH__
#define __ARM_FAULTS_HH__
#include "arch/arm/miscregs.hh"
#include "arch/arm/types.hh"
#include "config/full_system.hh"
#include "sim/faults.hh"
// The design of the "name" and "vect" functions is in sim/faults.hh
namespace ArmISA
{
typedef const Addr FaultOffset;
class ArmFault : public FaultBase
{
protected:
Addr getVector(ThreadContext *tc);
public:
enum StatusEncoding
{
// Fault Status register encodings
// ARM ARM B3.9.4
AlignmentFault = 0x1,
DebugEvent = 0x2,
AccessFlag0 = 0x3,
InstructionCacheMaintenance = 0x4,
Translation0 = 0x5,
AccessFlag1 = 0x6,
Translation1 = 0x7,
SynchronousExternalAbort0 = 0x8,
Domain0 = 0x9,
SynchronousExternalAbort1 = 0xa,
Domain1 = 0xb,
TranslationTableWalkExtAbt0 = 0xc,
Permission0 = 0xd,
TranslationTableWalkExtAbt1 = 0xe,
Permission1 = 0xf,
AsynchronousExternalAbort = 0x16,
MemoryAccessAsynchronousParityError = 0x18,
MemoryAccessSynchronousParityError = 0x19,
TranslationTableWalkPrtyErr0 = 0x1c,
TranslationTableWalkPrtyErr1 = 0x1e,
};
struct FaultVals
{
const FaultName name;
const FaultOffset offset;
const OperatingMode nextMode;
const uint8_t armPcOffset;
const uint8_t thumbPcOffset;
const bool abortDisable;
const bool fiqDisable;
FaultStat count;
};
#if FULL_SYSTEM
void invoke(ThreadContext *tc);
#endif
virtual FaultStat& countStat() = 0;
virtual FaultOffset offset() = 0;
virtual OperatingMode nextMode() = 0;
virtual uint8_t armPcOffset() = 0;
virtual uint8_t thumbPcOffset() = 0;
virtual bool abortDisable() = 0;
virtual bool fiqDisable() = 0;
};
template<typename T>
class ArmFaultVals : public ArmFault
{
protected:
static FaultVals vals;
public:
FaultName name() const { return vals.name; }
FaultStat & countStat() {return vals.count;}
FaultOffset offset() { return vals.offset; }
OperatingMode nextMode() { return vals.nextMode; }
uint8_t armPcOffset() { return vals.armPcOffset; }
uint8_t thumbPcOffset() { return vals.thumbPcOffset; }
bool abortDisable() { return vals.abortDisable; }
bool fiqDisable() { return vals.fiqDisable; }
};
class Reset : public ArmFaultVals<Reset>
#if FULL_SYSTEM
{
public:
void invoke(ThreadContext *tc);
};
#else
{};
#endif //FULL_SYSTEM
class UndefinedInstruction : public ArmFaultVals<UndefinedInstruction>
{
#if !FULL_SYSTEM
protected:
ExtMachInst machInst;
bool unknown;
const char *mnemonic;
public:
UndefinedInstruction(ExtMachInst _machInst,
bool _unknown,
const char *_mnemonic = NULL) :
machInst(_machInst), unknown(_unknown), mnemonic(_mnemonic)
{
}
void invoke(ThreadContext *tc);
#endif
};
class SupervisorCall : public ArmFaultVals<SupervisorCall>
{
#if !FULL_SYSTEM
protected:
ExtMachInst machInst;
public:
SupervisorCall(ExtMachInst _machInst) : machInst(_machInst)
{}
void invoke(ThreadContext *tc);
#endif
};
template <class T>
class AbortFault : public ArmFaultVals<T>
{
protected:
Addr faultAddr;
bool write;
uint8_t domain;
uint8_t status;
public:
AbortFault(Addr _faultAddr, bool _write,
uint8_t _domain, uint8_t _status) :
faultAddr(_faultAddr), write(_write),
domain(_domain), status(_status)
{}
void invoke(ThreadContext *tc);
};
class PrefetchAbort : public AbortFault<PrefetchAbort>
{
public:
static const MiscRegIndex FsrIndex = MISCREG_IFSR;
static const MiscRegIndex FarIndex = MISCREG_IFAR;
PrefetchAbort(Addr _addr, uint8_t _status) :
AbortFault<PrefetchAbort>(_addr, false, 0, _status)
{}
};
class DataAbort : public AbortFault<DataAbort>
{
public:
static const MiscRegIndex FsrIndex = MISCREG_DFSR;
static const MiscRegIndex FarIndex = MISCREG_DFAR;
DataAbort(Addr _addr, uint8_t _domain, bool _write, uint8_t _status) :
AbortFault<DataAbort>(_addr, _write, _domain, _status)
{}
};
class Interrupt : public ArmFaultVals<Interrupt> {};
class FastInterrupt : public ArmFaultVals<FastInterrupt> {};
} // ArmISA namespace
#endif // __ARM_FAULTS_HH__
<commit_msg>ARM: DFSR status value for sync external data abort is expected to be 0x8 in ARMv7<commit_after>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* Copyright (c) 2007-2008 The Florida State University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Gabe Black
*/
#ifndef __ARM_FAULTS_HH__
#define __ARM_FAULTS_HH__
#include "arch/arm/miscregs.hh"
#include "arch/arm/types.hh"
#include "config/full_system.hh"
#include "sim/faults.hh"
// The design of the "name" and "vect" functions is in sim/faults.hh
namespace ArmISA
{
typedef const Addr FaultOffset;
class ArmFault : public FaultBase
{
protected:
Addr getVector(ThreadContext *tc);
public:
enum StatusEncoding
{
// Fault Status register encodings
// ARM ARM B3.9.4
AlignmentFault = 0x1,
DebugEvent = 0x2,
AccessFlag0 = 0x3,
InstructionCacheMaintenance = 0x4,
Translation0 = 0x5,
AccessFlag1 = 0x6,
Translation1 = 0x7,
SynchronousExternalAbort0 = 0x8,
Domain0 = 0x9,
SynchronousExternalAbort1 = 0x8,
Domain1 = 0xb,
TranslationTableWalkExtAbt0 = 0xc,
Permission0 = 0xd,
TranslationTableWalkExtAbt1 = 0xe,
Permission1 = 0xf,
AsynchronousExternalAbort = 0x16,
MemoryAccessAsynchronousParityError = 0x18,
MemoryAccessSynchronousParityError = 0x19,
TranslationTableWalkPrtyErr0 = 0x1c,
TranslationTableWalkPrtyErr1 = 0x1e,
};
struct FaultVals
{
const FaultName name;
const FaultOffset offset;
const OperatingMode nextMode;
const uint8_t armPcOffset;
const uint8_t thumbPcOffset;
const bool abortDisable;
const bool fiqDisable;
FaultStat count;
};
#if FULL_SYSTEM
void invoke(ThreadContext *tc);
#endif
virtual FaultStat& countStat() = 0;
virtual FaultOffset offset() = 0;
virtual OperatingMode nextMode() = 0;
virtual uint8_t armPcOffset() = 0;
virtual uint8_t thumbPcOffset() = 0;
virtual bool abortDisable() = 0;
virtual bool fiqDisable() = 0;
};
template<typename T>
class ArmFaultVals : public ArmFault
{
protected:
static FaultVals vals;
public:
FaultName name() const { return vals.name; }
FaultStat & countStat() {return vals.count;}
FaultOffset offset() { return vals.offset; }
OperatingMode nextMode() { return vals.nextMode; }
uint8_t armPcOffset() { return vals.armPcOffset; }
uint8_t thumbPcOffset() { return vals.thumbPcOffset; }
bool abortDisable() { return vals.abortDisable; }
bool fiqDisable() { return vals.fiqDisable; }
};
class Reset : public ArmFaultVals<Reset>
#if FULL_SYSTEM
{
public:
void invoke(ThreadContext *tc);
};
#else
{};
#endif //FULL_SYSTEM
class UndefinedInstruction : public ArmFaultVals<UndefinedInstruction>
{
#if !FULL_SYSTEM
protected:
ExtMachInst machInst;
bool unknown;
const char *mnemonic;
public:
UndefinedInstruction(ExtMachInst _machInst,
bool _unknown,
const char *_mnemonic = NULL) :
machInst(_machInst), unknown(_unknown), mnemonic(_mnemonic)
{
}
void invoke(ThreadContext *tc);
#endif
};
class SupervisorCall : public ArmFaultVals<SupervisorCall>
{
#if !FULL_SYSTEM
protected:
ExtMachInst machInst;
public:
SupervisorCall(ExtMachInst _machInst) : machInst(_machInst)
{}
void invoke(ThreadContext *tc);
#endif
};
template <class T>
class AbortFault : public ArmFaultVals<T>
{
protected:
Addr faultAddr;
bool write;
uint8_t domain;
uint8_t status;
public:
AbortFault(Addr _faultAddr, bool _write,
uint8_t _domain, uint8_t _status) :
faultAddr(_faultAddr), write(_write),
domain(_domain), status(_status)
{}
void invoke(ThreadContext *tc);
};
class PrefetchAbort : public AbortFault<PrefetchAbort>
{
public:
static const MiscRegIndex FsrIndex = MISCREG_IFSR;
static const MiscRegIndex FarIndex = MISCREG_IFAR;
PrefetchAbort(Addr _addr, uint8_t _status) :
AbortFault<PrefetchAbort>(_addr, false, 0, _status)
{}
};
class DataAbort : public AbortFault<DataAbort>
{
public:
static const MiscRegIndex FsrIndex = MISCREG_DFSR;
static const MiscRegIndex FarIndex = MISCREG_DFAR;
DataAbort(Addr _addr, uint8_t _domain, bool _write, uint8_t _status) :
AbortFault<DataAbort>(_addr, _write, _domain, _status)
{}
};
class Interrupt : public ArmFaultVals<Interrupt> {};
class FastInterrupt : public ArmFaultVals<FastInterrupt> {};
} // ArmISA namespace
#endif // __ARM_FAULTS_HH__
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGuiOgreBaseApplication.cpp
created: 9/3/2004
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2008 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#if defined(__linux__) || defined(__FreeBSD__)
# include <unistd.h>
#endif
// this controls conditional compile of file for Apple
#include "CEGUISamplesConfig.h"
#ifdef CEGUI_SAMPLES_USE_OGRE
#include <OgreWindowEventUtilities.h>
#include "CEGuiOgreBaseApplication.h"
#include "CEGUIDefaultResourceProvider.h"
#include "CEGuiSample.h"
#include "CEGUIRenderingRoot.h"
#include "CEGUIGeometryBuffer.h"
CEGuiOgreBaseApplication::CEGuiOgreBaseApplication() :
d_ogreRoot(0),
d_renderer(0),
d_initialised(false),
d_frameListener(0),
d_windowEventListener(0),
d_fps_frames(0),
d_fps_time(0.0f)
{
strcpy(d_fps_textbuff, "");
using namespace Ogre;
d_ogreRoot = new Root();
if (d_ogreRoot->showConfigDialog())
{
// initialise system according to user options.
d_window = d_ogreRoot->initialise(true);
// Create the scene manager
SceneManager* sm = d_ogreRoot->
createSceneManager(ST_GENERIC, "SampleSceneMgr");
// Create and initialise the camera
d_camera = sm->createCamera("SampleCam");
d_camera->setPosition(Vector3(0,0,500));
d_camera->lookAt(Vector3(0,0,-300));
d_camera->setNearClipDistance(5);
// Create a viewport covering whole window
Viewport* vp = d_window->addViewport(d_camera);
vp->setBackgroundColour(ColourValue(0, 0, 0));
// Update the camera aspect ratio to that of the viewport
d_camera->setAspectRatio(Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
// initialise GUI system using the new automagic function
d_renderer = &CEGUI::OgreRenderer::bootstrapSystem();
initialiseResourceGroupDirectories();
initialiseDefaultResourceGroups();
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
// create frame listener
d_frameListener= new CEGuiDemoFrameListener(this, d_window, d_camera);
d_ogreRoot->addFrameListener(d_frameListener);
// add a listener for OS framework window events (for resizing)
d_windowEventListener = new WndEvtListener(d_renderer);
WindowEventUtilities::addWindowEventListener(d_window,
d_windowEventListener);
// setup required to do direct rendering of FPS value
const CEGUI::Rect scrn(CEGUI::Vector2(0, 0),
d_renderer->getDisplaySize());
d_fps_geometry = &d_renderer->createGeometryBuffer();
d_fps_geometry->setClippingRegion(scrn);
// setup for logo
CEGUI::ImagesetManager::getSingleton().
createFromImageFile("cegui_logo", "logo.png", "imagesets");
d_logo_geometry = &d_renderer->createGeometryBuffer();
d_logo_geometry->setClippingRegion(scrn);
d_logo_geometry->setPivot(CEGUI::Vector3(50, 34.75f, 0));
d_logo_geometry->setTranslation(CEGUI::Vector3(10, 520, 0));
CEGUI::ImagesetManager::getSingleton().get("cegui_logo").
getImage("full_image").draw(*d_logo_geometry,
CEGUI::Rect(0, 0, 100, 69.5f), 0);
// clearing this queue actually makes sure it's created(!)
d_renderer->getDefaultRenderingRoot().clearGeometry(CEGUI::RQ_OVERLAY);
// subscribe handler to render overlay items
d_renderer->getDefaultRenderingRoot().
subscribeEvent(CEGUI::RenderingSurface::EventRenderQueueStarted,
CEGUI::Event::Subscriber(
&CEGuiOgreBaseApplication::overlayHandler, this));
d_initialised = true;
}
else
{
// aborted. Clean up and set root to 0 so when app attempts to run it knows what happened here.
delete d_ogreRoot;
d_ogreRoot = 0;
}
}
CEGuiOgreBaseApplication::~CEGuiOgreBaseApplication()
{
delete d_frameListener;
CEGUI::OgreRenderer::destroySystem();
delete d_ogreRoot;
delete d_windowEventListener;
}
bool CEGuiOgreBaseApplication::execute(CEGuiSample* sampleApp)
{
// if initialisation failed or was cancelled by user, bail out now.
if (d_ogreRoot && d_initialised)
{
// perform sample initialisation
sampleApp->initialiseSample();
// start rendering via Ogre3D engine.
try
{
d_ogreRoot->startRendering();
}
catch(Ogre::Exception&)
{
return false;
}
catch(CEGUI::Exception&)
{
return false;
}
return true;
}
else
{
return false;
}
}
void CEGuiOgreBaseApplication::cleanup()
{
// nothing to do here.
}
void CEGuiOgreBaseApplication::initialiseResourceGroupDirectories()
{
using namespace Ogre;
ResourceGroupManager& rgm = ResourceGroupManager::getSingleton();
// add resource groups that we use
rgm.createResourceGroup("imagesets");
rgm.createResourceGroup("fonts");
rgm.createResourceGroup("layouts");
rgm.createResourceGroup("schemes");
rgm.createResourceGroup("looknfeels");
rgm.createResourceGroup("lua_scripts");
rgm.createResourceGroup("schemas");
// add CEGUI sample framework datafile dirs as resource locations
ResourceGroupManager::getSingleton().addResourceLocation("./", "FileSystem");
const char* dataPathPrefix = getDataPathPrefix();
char resourcePath[PATH_MAX];
// for each resource type, set a resource group directory
sprintf(resourcePath, "%s/%s", dataPathPrefix, "schemes/");
ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "schemes");
sprintf(resourcePath, "%s/%s", dataPathPrefix, "imagesets/");
ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "imagesets");
sprintf(resourcePath, "%s/%s", dataPathPrefix, "fonts/");
ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "fonts");
sprintf(resourcePath, "%s/%s", dataPathPrefix, "layouts/");
ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "layouts");
sprintf(resourcePath, "%s/%s", dataPathPrefix, "looknfeel/");
ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "looknfeels");
sprintf(resourcePath, "%s/%s", dataPathPrefix, "lua_scripts/");
ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "lua_scripts");
sprintf(resourcePath, "%s/%s", dataPathPrefix, "xml_schemas/");
ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "schemas");
}
void CEGuiOgreBaseApplication::doFrameUpdate(float elapsed)
{
// update fps fields
doFPSUpdate(elapsed);
// update logo rotation
static float rot = 0.0f;
d_logo_geometry->setRotation(CEGUI::Vector3(rot, 0, 0));
rot += 180.0f * elapsed;
if (rot > 360.0f)
rot -= 360.0f;
}
void CEGuiOgreBaseApplication::doFPSUpdate(float elapsed)
{
// another frame
d_fps_frames += 1;
// has at least a second passed since we last updated the text?
if ((d_fps_time += elapsed) >= 1.0f)
{
// update FPS text to output
sprintf(d_fps_textbuff , "FPS: %d", d_fps_frames);
// reset counter
d_fps_frames = 0;
// update timer
d_fps_time -= 1.0f;
}
}
bool CEGuiOgreBaseApplication::overlayHandler(const CEGUI::EventArgs& args)
{
using namespace CEGUI;
if (static_cast<const RenderQueueEventArgs&>(args).queueID != RQ_OVERLAY)
return false;
// render FPS:
Font* fnt = System::getSingleton().getDefaultFont();
if (fnt)
{
d_fps_geometry->reset();
fnt->drawText(*d_fps_geometry, d_fps_textbuff, Vector2(0, 0), 0,
colour(0xFFFFFFFF));
d_fps_geometry->draw();
}
d_logo_geometry->draw();
return true;
}
////////////////////////////////////////////////////////////////////////////////
/*******************************************************************************
Start of CEGuiDemoFrameListener mehods
*******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
CEGuiDemoFrameListener::CEGuiDemoFrameListener(CEGuiBaseApplication* baseApp, Ogre::RenderWindow* window, Ogre::Camera* camera, bool useBufferedInputKeys, bool useBufferedInputMouse)
{
// OIS setup
OIS::ParamList paramList;
size_t windowHnd = 0;
std::ostringstream windowHndStr;
// get window handle
window->getCustomAttribute("WINDOW", &windowHnd);
// fill param list
windowHndStr << (unsigned int)windowHnd;
paramList.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
// #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX && defined (DEBUG)
// paramList.insert(std::make_pair(std::string("x11_mouse_grab"), "false"));
// paramList.insert(std::make_pair(std::string("x11_mouse_hide"), "false"));
// #endif
// create input system
d_inputManager = OIS::InputManager::createInputSystem(paramList);
// create buffered keyboard
#ifdef CEGUI_OLD_OIS_API
if (d_inputManager->numKeyboards() > 0)
#else
if (d_inputManager->getNumberOfDevices(OIS::OISKeyboard) > 0)
#endif
{
d_keyboard = static_cast<OIS::Keyboard*>(d_inputManager->createInputObject(OIS::OISKeyboard, true));
d_keyboard->setEventCallback(this);
}
// create buffered mouse
#ifdef CEGUI_OLD_OIS_API
if (d_inputManager->numMice() > 0)
#else
if (d_inputManager->getNumberOfDevices(OIS::OISMouse) > 0)
#endif
{
d_mouse = static_cast<OIS::Mouse*>(d_inputManager->createInputObject(OIS::OISMouse, true));
d_mouse->setEventCallback(this);
unsigned int width, height, depth;
int left, top;
window->getMetrics(width, height, depth, left, top);
const OIS::MouseState& mouseState = d_mouse->getMouseState();
mouseState.width = width;
mouseState.height = height;
}
// store inputs we want to make use of
d_camera = camera;
d_window = window;
// we've not quit yet.
d_quit = false;
// setup base app ptr
d_baseApp = baseApp;
}
CEGuiDemoFrameListener::~CEGuiDemoFrameListener()
{
if (d_inputManager)
{
d_inputManager->destroyInputObject(d_mouse);
d_inputManager->destroyInputObject(d_keyboard);
OIS::InputManager::destroyInputSystem(d_inputManager);
}
}
bool CEGuiDemoFrameListener::frameStarted(const Ogre::FrameEvent& evt)
{
if(d_window->isClosed() || d_quit || d_baseApp->isQuitting())
{
return false;
}
else
{
// always inject a time pulse to enable widget automation
CEGUI::System::getSingleton().injectTimePulse(static_cast<float>(evt.timeSinceLastFrame));
static_cast<CEGuiOgreBaseApplication*>(d_baseApp)->
doFrameUpdate(static_cast<float>(evt.timeSinceLastFrame));
// update input system
if (d_mouse)
d_mouse->capture();
if (d_keyboard)
d_keyboard->capture();
return true;
}
}
bool CEGuiDemoFrameListener::frameEnded(const Ogre::FrameEvent& evt)
{
return true;
}
bool CEGuiDemoFrameListener::mouseMoved(const OIS::MouseEvent &e)
{
CEGUI::System& cegui = CEGUI::System::getSingleton();
cegui.injectMouseMove(e.state.X.rel, e.state.Y.rel);
cegui.injectMouseWheelChange(e.state.Z.rel * 0.03);
return true;
}
bool CEGuiDemoFrameListener::keyPressed(const OIS::KeyEvent &e)
{
// give 'quitting' priority
if (e.key == OIS::KC_ESCAPE)
{
d_quit = true;
return true;
}
// do event injection
CEGUI::System& cegui = CEGUI::System::getSingleton();
// key down
cegui.injectKeyDown(e.key);
// now character
cegui.injectChar(e.text);
return true;
}
bool CEGuiDemoFrameListener::keyReleased(const OIS::KeyEvent &e)
{
CEGUI::System::getSingleton().injectKeyUp(e.key);
return true;
}
bool CEGuiDemoFrameListener::mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id)
{
CEGUI::System::getSingleton().injectMouseButtonDown(convertOISButtonToCegui(id));
return true;
}
bool CEGuiDemoFrameListener::mouseReleased(const OIS::MouseEvent &e, OIS::MouseButtonID id)
{
CEGUI::System::getSingleton().injectMouseButtonUp(convertOISButtonToCegui(id));
return true;
}
CEGUI::MouseButton CEGuiDemoFrameListener::convertOISButtonToCegui(int buttonID)
{
using namespace OIS;
switch (buttonID)
{
case OIS::MB_Left:
return CEGUI::LeftButton;
case OIS::MB_Right:
return CEGUI::RightButton;
case OIS::MB_Middle:
return CEGUI::MiddleButton;
default:
return CEGUI::LeftButton;
}
}
////////////////////////////////////////////////////////////////////////////////
/*******************************************************************************
Start of WndEvtListener member functions
*******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
WndEvtListener::WndEvtListener(CEGUI::OgreRenderer* renderer) :
d_renderer(renderer)
{}
void WndEvtListener::windowResized(Ogre::RenderWindow* rw)
{
CEGUI::System::getSingleton().notifyDisplaySizeChanged(
CEGUI::Size(static_cast<float>(rw->getWidth()),
static_cast<float>(rw->getHeight())));
}
#endif
<commit_msg>MOD: In the samples, don't grab the mouse and keyboard in debug builds when using Ogre under X.<commit_after>/***********************************************************************
filename: CEGuiOgreBaseApplication.cpp
created: 9/3/2004
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2008 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#if defined(__linux__) || defined(__FreeBSD__)
# include <unistd.h>
#endif
// this controls conditional compile of file for Apple
#include "CEGUISamplesConfig.h"
#ifdef CEGUI_SAMPLES_USE_OGRE
#include <OgreWindowEventUtilities.h>
#include "CEGuiOgreBaseApplication.h"
#include "CEGUIDefaultResourceProvider.h"
#include "CEGuiSample.h"
#include "CEGUIRenderingRoot.h"
#include "CEGUIGeometryBuffer.h"
CEGuiOgreBaseApplication::CEGuiOgreBaseApplication() :
d_ogreRoot(0),
d_renderer(0),
d_initialised(false),
d_frameListener(0),
d_windowEventListener(0),
d_fps_frames(0),
d_fps_time(0.0f)
{
strcpy(d_fps_textbuff, "");
using namespace Ogre;
d_ogreRoot = new Root();
if (d_ogreRoot->showConfigDialog())
{
// initialise system according to user options.
d_window = d_ogreRoot->initialise(true);
// Create the scene manager
SceneManager* sm = d_ogreRoot->
createSceneManager(ST_GENERIC, "SampleSceneMgr");
// Create and initialise the camera
d_camera = sm->createCamera("SampleCam");
d_camera->setPosition(Vector3(0,0,500));
d_camera->lookAt(Vector3(0,0,-300));
d_camera->setNearClipDistance(5);
// Create a viewport covering whole window
Viewport* vp = d_window->addViewport(d_camera);
vp->setBackgroundColour(ColourValue(0, 0, 0));
// Update the camera aspect ratio to that of the viewport
d_camera->setAspectRatio(Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
// initialise GUI system using the new automagic function
d_renderer = &CEGUI::OgreRenderer::bootstrapSystem();
initialiseResourceGroupDirectories();
initialiseDefaultResourceGroups();
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
// create frame listener
d_frameListener= new CEGuiDemoFrameListener(this, d_window, d_camera);
d_ogreRoot->addFrameListener(d_frameListener);
// add a listener for OS framework window events (for resizing)
d_windowEventListener = new WndEvtListener(d_renderer);
WindowEventUtilities::addWindowEventListener(d_window,
d_windowEventListener);
// setup required to do direct rendering of FPS value
const CEGUI::Rect scrn(CEGUI::Vector2(0, 0),
d_renderer->getDisplaySize());
d_fps_geometry = &d_renderer->createGeometryBuffer();
d_fps_geometry->setClippingRegion(scrn);
// setup for logo
CEGUI::ImagesetManager::getSingleton().
createFromImageFile("cegui_logo", "logo.png", "imagesets");
d_logo_geometry = &d_renderer->createGeometryBuffer();
d_logo_geometry->setClippingRegion(scrn);
d_logo_geometry->setPivot(CEGUI::Vector3(50, 34.75f, 0));
d_logo_geometry->setTranslation(CEGUI::Vector3(10, 520, 0));
CEGUI::ImagesetManager::getSingleton().get("cegui_logo").
getImage("full_image").draw(*d_logo_geometry,
CEGUI::Rect(0, 0, 100, 69.5f), 0);
// clearing this queue actually makes sure it's created(!)
d_renderer->getDefaultRenderingRoot().clearGeometry(CEGUI::RQ_OVERLAY);
// subscribe handler to render overlay items
d_renderer->getDefaultRenderingRoot().
subscribeEvent(CEGUI::RenderingSurface::EventRenderQueueStarted,
CEGUI::Event::Subscriber(
&CEGuiOgreBaseApplication::overlayHandler, this));
d_initialised = true;
}
else
{
// aborted. Clean up and set root to 0 so when app attempts to run it knows what happened here.
delete d_ogreRoot;
d_ogreRoot = 0;
}
}
CEGuiOgreBaseApplication::~CEGuiOgreBaseApplication()
{
delete d_frameListener;
CEGUI::OgreRenderer::destroySystem();
delete d_ogreRoot;
delete d_windowEventListener;
}
bool CEGuiOgreBaseApplication::execute(CEGuiSample* sampleApp)
{
// if initialisation failed or was cancelled by user, bail out now.
if (d_ogreRoot && d_initialised)
{
// perform sample initialisation
sampleApp->initialiseSample();
// start rendering via Ogre3D engine.
try
{
d_ogreRoot->startRendering();
}
catch(Ogre::Exception&)
{
return false;
}
catch(CEGUI::Exception&)
{
return false;
}
return true;
}
else
{
return false;
}
}
void CEGuiOgreBaseApplication::cleanup()
{
// nothing to do here.
}
void CEGuiOgreBaseApplication::initialiseResourceGroupDirectories()
{
using namespace Ogre;
ResourceGroupManager& rgm = ResourceGroupManager::getSingleton();
// add resource groups that we use
rgm.createResourceGroup("imagesets");
rgm.createResourceGroup("fonts");
rgm.createResourceGroup("layouts");
rgm.createResourceGroup("schemes");
rgm.createResourceGroup("looknfeels");
rgm.createResourceGroup("lua_scripts");
rgm.createResourceGroup("schemas");
// add CEGUI sample framework datafile dirs as resource locations
ResourceGroupManager::getSingleton().addResourceLocation("./", "FileSystem");
const char* dataPathPrefix = getDataPathPrefix();
char resourcePath[PATH_MAX];
// for each resource type, set a resource group directory
sprintf(resourcePath, "%s/%s", dataPathPrefix, "schemes/");
ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "schemes");
sprintf(resourcePath, "%s/%s", dataPathPrefix, "imagesets/");
ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "imagesets");
sprintf(resourcePath, "%s/%s", dataPathPrefix, "fonts/");
ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "fonts");
sprintf(resourcePath, "%s/%s", dataPathPrefix, "layouts/");
ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "layouts");
sprintf(resourcePath, "%s/%s", dataPathPrefix, "looknfeel/");
ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "looknfeels");
sprintf(resourcePath, "%s/%s", dataPathPrefix, "lua_scripts/");
ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "lua_scripts");
sprintf(resourcePath, "%s/%s", dataPathPrefix, "xml_schemas/");
ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "schemas");
}
void CEGuiOgreBaseApplication::doFrameUpdate(float elapsed)
{
// update fps fields
doFPSUpdate(elapsed);
// update logo rotation
static float rot = 0.0f;
d_logo_geometry->setRotation(CEGUI::Vector3(rot, 0, 0));
rot += 180.0f * elapsed;
if (rot > 360.0f)
rot -= 360.0f;
}
void CEGuiOgreBaseApplication::doFPSUpdate(float elapsed)
{
// another frame
d_fps_frames += 1;
// has at least a second passed since we last updated the text?
if ((d_fps_time += elapsed) >= 1.0f)
{
// update FPS text to output
sprintf(d_fps_textbuff , "FPS: %d", d_fps_frames);
// reset counter
d_fps_frames = 0;
// update timer
d_fps_time -= 1.0f;
}
}
bool CEGuiOgreBaseApplication::overlayHandler(const CEGUI::EventArgs& args)
{
using namespace CEGUI;
if (static_cast<const RenderQueueEventArgs&>(args).queueID != RQ_OVERLAY)
return false;
// render FPS:
Font* fnt = System::getSingleton().getDefaultFont();
if (fnt)
{
d_fps_geometry->reset();
fnt->drawText(*d_fps_geometry, d_fps_textbuff, Vector2(0, 0), 0,
colour(0xFFFFFFFF));
d_fps_geometry->draw();
}
d_logo_geometry->draw();
return true;
}
////////////////////////////////////////////////////////////////////////////////
/*******************************************************************************
Start of CEGuiDemoFrameListener mehods
*******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
CEGuiDemoFrameListener::CEGuiDemoFrameListener(CEGuiBaseApplication* baseApp, Ogre::RenderWindow* window, Ogre::Camera* camera, bool useBufferedInputKeys, bool useBufferedInputMouse)
{
// OIS setup
OIS::ParamList paramList;
size_t windowHnd = 0;
std::ostringstream windowHndStr;
// get window handle
window->getCustomAttribute("WINDOW", &windowHnd);
// fill param list
windowHndStr << (unsigned int)windowHnd;
paramList.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX && defined (DEBUG)
paramList.insert(std::make_pair(std::string("x11_keyboard_grab"), "false"));
paramList.insert(std::make_pair(std::string("x11_mouse_grab"), "false"));
paramList.insert(std::make_pair(std::string("x11_mouse_hide"), "false"));
#endif
// create input system
d_inputManager = OIS::InputManager::createInputSystem(paramList);
// create buffered keyboard
#ifdef CEGUI_OLD_OIS_API
if (d_inputManager->numKeyboards() > 0)
#else
if (d_inputManager->getNumberOfDevices(OIS::OISKeyboard) > 0)
#endif
{
d_keyboard = static_cast<OIS::Keyboard*>(d_inputManager->createInputObject(OIS::OISKeyboard, true));
d_keyboard->setEventCallback(this);
}
// create buffered mouse
#ifdef CEGUI_OLD_OIS_API
if (d_inputManager->numMice() > 0)
#else
if (d_inputManager->getNumberOfDevices(OIS::OISMouse) > 0)
#endif
{
d_mouse = static_cast<OIS::Mouse*>(d_inputManager->createInputObject(OIS::OISMouse, true));
d_mouse->setEventCallback(this);
unsigned int width, height, depth;
int left, top;
window->getMetrics(width, height, depth, left, top);
const OIS::MouseState& mouseState = d_mouse->getMouseState();
mouseState.width = width;
mouseState.height = height;
}
// store inputs we want to make use of
d_camera = camera;
d_window = window;
// we've not quit yet.
d_quit = false;
// setup base app ptr
d_baseApp = baseApp;
}
CEGuiDemoFrameListener::~CEGuiDemoFrameListener()
{
if (d_inputManager)
{
d_inputManager->destroyInputObject(d_mouse);
d_inputManager->destroyInputObject(d_keyboard);
OIS::InputManager::destroyInputSystem(d_inputManager);
}
}
bool CEGuiDemoFrameListener::frameStarted(const Ogre::FrameEvent& evt)
{
if(d_window->isClosed() || d_quit || d_baseApp->isQuitting())
{
return false;
}
else
{
// always inject a time pulse to enable widget automation
CEGUI::System::getSingleton().injectTimePulse(static_cast<float>(evt.timeSinceLastFrame));
static_cast<CEGuiOgreBaseApplication*>(d_baseApp)->
doFrameUpdate(static_cast<float>(evt.timeSinceLastFrame));
// update input system
if (d_mouse)
d_mouse->capture();
if (d_keyboard)
d_keyboard->capture();
return true;
}
}
bool CEGuiDemoFrameListener::frameEnded(const Ogre::FrameEvent& evt)
{
return true;
}
bool CEGuiDemoFrameListener::mouseMoved(const OIS::MouseEvent &e)
{
CEGUI::System& cegui = CEGUI::System::getSingleton();
cegui.injectMouseMove(e.state.X.rel, e.state.Y.rel);
cegui.injectMouseWheelChange(e.state.Z.rel * 0.03);
return true;
}
bool CEGuiDemoFrameListener::keyPressed(const OIS::KeyEvent &e)
{
// give 'quitting' priority
if (e.key == OIS::KC_ESCAPE)
{
d_quit = true;
return true;
}
// do event injection
CEGUI::System& cegui = CEGUI::System::getSingleton();
// key down
cegui.injectKeyDown(e.key);
// now character
cegui.injectChar(e.text);
return true;
}
bool CEGuiDemoFrameListener::keyReleased(const OIS::KeyEvent &e)
{
CEGUI::System::getSingleton().injectKeyUp(e.key);
return true;
}
bool CEGuiDemoFrameListener::mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id)
{
CEGUI::System::getSingleton().injectMouseButtonDown(convertOISButtonToCegui(id));
return true;
}
bool CEGuiDemoFrameListener::mouseReleased(const OIS::MouseEvent &e, OIS::MouseButtonID id)
{
CEGUI::System::getSingleton().injectMouseButtonUp(convertOISButtonToCegui(id));
return true;
}
CEGUI::MouseButton CEGuiDemoFrameListener::convertOISButtonToCegui(int buttonID)
{
using namespace OIS;
switch (buttonID)
{
case OIS::MB_Left:
return CEGUI::LeftButton;
case OIS::MB_Right:
return CEGUI::RightButton;
case OIS::MB_Middle:
return CEGUI::MiddleButton;
default:
return CEGUI::LeftButton;
}
}
////////////////////////////////////////////////////////////////////////////////
/*******************************************************************************
Start of WndEvtListener member functions
*******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
WndEvtListener::WndEvtListener(CEGUI::OgreRenderer* renderer) :
d_renderer(renderer)
{}
void WndEvtListener::windowResized(Ogre::RenderWindow* rw)
{
CEGUI::System::getSingleton().notifyDisplaySizeChanged(
CEGUI::Size(static_cast<float>(rw->getWidth()),
static_cast<float>(rw->getHeight())));
}
#endif
<|endoftext|> |
<commit_before>#ifndef ARGPARSE_VALUE_HPP
#define ARGPARSE_VALUE_HPP
#include <iostream>
namespace argparse {
template<class T>
class ConvertedValue {
public:
typedef T value_type;
public:
void set_value(T val) { errored_ = false; value_ = val; }
void set_error(std::string msg) { errored_ = true; error_msg_ = msg; }
T value() const { return value_; }
std::string error() const { return error_msg_; }
operator bool() { return valid(); }
bool valid() const { return !errored_; }
private:
T value_;
std::string error_msg_;
bool errored_ = true;
};
//How the value associated with an argumetn was initialized
enum class Provenance {
UNSPECIFIED,//The value was default constructed
DEFAULT, //The value was set by a default (e.g. as a command-line argument default value)
SPECIFIED, //The value was explicitly specified (e.g. explicitly specified on the command-line)
INFERRED, //The value was inferred, or conditionally set based on other values
};
/*
* ArgValue represents the 'value' of a command-line option/argument
*
* It supports implicit conversion to the underlying value_type, which means it can
* be seamlessly used as the value_type in most situations.
*
* It additionally tracks the provenance off the option, along with it's associated argument group.
*/
template<typename T>
class ArgValue {
public:
typedef T value_type;
public: //Accessors
//Automatic conversion to underlying value type
operator T() const { return value_; }
//Returns the value assoicated with this argument
const T& value() const { return value_; }
//Returns the provenance of this argument (i.e. how it was initialized)
Provenance provenance() const { return provenance_; }
//Returns the group this argument is associated with (or an empty string if none)
const std::string& argument_group() const { return argument_group_; }
const std::string& argument_name() const { return argument_name_; }
public: //Mutators
void set(ConvertedValue<T> val, Provenance prov) {
if (!val) {
//If the value didn't convert properly, it should
//have an error message so raise it
throw ArgParseConversionError(val.error());
}
value_ = val.value();
provenance_ = prov;
}
void set(T val, Provenance prov) {
value_ = val;
provenance_ = prov;
}
T& mutable_value(Provenance prov) {
provenance_ = prov;
return value_;
}
void set_argument_group(std::string grp) {
argument_group_ = grp;
}
void set_argument_name(std::string name_str) {
argument_name_ = name_str;
}
private:
T value_ = T();
Provenance provenance_ = Provenance::UNSPECIFIED;
std::string argument_group_ = "";
std::string argument_name_ = "";
};
//Automatically convert to the underlying type for ostream output
template<typename T>
std::ostream& operator<<(std::ostream& os, const ArgValue<T> t) {
return os << T(t);
}
}
#endif
<commit_msg>Fix missing header<commit_after>#ifndef ARGPARSE_VALUE_HPP
#define ARGPARSE_VALUE_HPP
#include <iostream>
#include "argparse_error.hpp"
namespace argparse {
template<class T>
class ConvertedValue {
public:
typedef T value_type;
public:
void set_value(T val) { errored_ = false; value_ = val; }
void set_error(std::string msg) { errored_ = true; error_msg_ = msg; }
T value() const { return value_; }
std::string error() const { return error_msg_; }
operator bool() { return valid(); }
bool valid() const { return !errored_; }
private:
T value_;
std::string error_msg_;
bool errored_ = true;
};
//How the value associated with an argumetn was initialized
enum class Provenance {
UNSPECIFIED,//The value was default constructed
DEFAULT, //The value was set by a default (e.g. as a command-line argument default value)
SPECIFIED, //The value was explicitly specified (e.g. explicitly specified on the command-line)
INFERRED, //The value was inferred, or conditionally set based on other values
};
/*
* ArgValue represents the 'value' of a command-line option/argument
*
* It supports implicit conversion to the underlying value_type, which means it can
* be seamlessly used as the value_type in most situations.
*
* It additionally tracks the provenance off the option, along with it's associated argument group.
*/
template<typename T>
class ArgValue {
public:
typedef T value_type;
public: //Accessors
//Automatic conversion to underlying value type
operator T() const { return value_; }
//Returns the value assoicated with this argument
const T& value() const { return value_; }
//Returns the provenance of this argument (i.e. how it was initialized)
Provenance provenance() const { return provenance_; }
//Returns the group this argument is associated with (or an empty string if none)
const std::string& argument_group() const { return argument_group_; }
const std::string& argument_name() const { return argument_name_; }
public: //Mutators
void set(ConvertedValue<T> val, Provenance prov) {
if (!val.valid()) {
//If the value didn't convert properly, it should
//have an error message so raise it
throw ArgParseConversionError(val.error());
}
value_ = val.value();
provenance_ = prov;
}
void set(T val, Provenance prov) {
value_ = val;
provenance_ = prov;
}
T& mutable_value(Provenance prov) {
provenance_ = prov;
return value_;
}
void set_argument_group(std::string grp) {
argument_group_ = grp;
}
void set_argument_name(std::string name_str) {
argument_name_ = name_str;
}
private:
T value_ = T();
Provenance provenance_ = Provenance::UNSPECIFIED;
std::string argument_group_ = "";
std::string argument_name_ = "";
};
//Automatically convert to the underlying type for ostream output
template<typename T>
std::ostream& operator<<(std::ostream& os, const ArgValue<T> t) {
return os << T(t);
}
}
#endif
<|endoftext|> |
<commit_before>//===- HexagonTargetTransformInfo.cpp - Hexagon specific TTI pass ---------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
/// \file
/// This file implements a TargetTransformInfo analysis pass specific to the
/// Hexagon target machine. It uses the target's detailed information to provide
/// more precise answers to certain TTI queries, while letting the target
/// independent and default TTI implementations handle the rest.
///
//===----------------------------------------------------------------------===//
#include "HexagonTargetTransformInfo.h"
#include "HexagonSubtarget.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/User.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/Utils/UnrollLoop.h"
using namespace llvm;
#define DEBUG_TYPE "hexagontti"
static cl::opt<bool> HexagonAutoHVX("hexagon-autohvx", cl::init(false),
cl::Hidden, cl::desc("Enable loop vectorizer for HVX"));
static cl::opt<bool> EmitLookupTables("hexagon-emit-lookup-tables",
cl::init(true), cl::Hidden,
cl::desc("Control lookup table emission on Hexagon target"));
// Constant "cost factor" to make floating point operations more expensive
// in terms of vectorization cost. This isn't the best way, but it should
// do. Ultimately, the cost should use cycles.
static const unsigned FloatFactor = 4;
bool HexagonTTIImpl::useHVX() const {
return ST.useHVXOps() && HexagonAutoHVX;
}
bool HexagonTTIImpl::isTypeForHVX(Type *VecTy) const {
assert(VecTy->isVectorTy());
// Avoid types like <2 x i32*>.
if (!cast<VectorType>(VecTy)->getElementType()->isIntegerTy())
return false;
EVT VecVT = EVT::getEVT(VecTy);
if (!VecVT.isSimple() || VecVT.getSizeInBits() <= 64)
return false;
if (ST.isHVXVectorType(VecVT.getSimpleVT()))
return true;
auto Action = TLI.getPreferredVectorAction(VecVT.getSimpleVT());
return Action == TargetLoweringBase::TypeWidenVector;
}
unsigned HexagonTTIImpl::getTypeNumElements(Type *Ty) const {
if (Ty->isVectorTy())
return Ty->getVectorNumElements();
assert((Ty->isIntegerTy() || Ty->isFloatingPointTy()) &&
"Expecting scalar type");
return 1;
}
TargetTransformInfo::PopcntSupportKind
HexagonTTIImpl::getPopcntSupport(unsigned IntTyWidthInBit) const {
// Return fast hardware support as every input < 64 bits will be promoted
// to 64 bits.
return TargetTransformInfo::PSK_FastHardware;
}
// The Hexagon target can unroll loops with run-time trip counts.
void HexagonTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
TTI::UnrollingPreferences &UP) {
UP.Runtime = UP.Partial = true;
// Only try to peel innermost loops with small runtime trip counts.
if (L && L->empty() && canPeel(L) &&
SE.getSmallConstantTripCount(L) == 0 &&
SE.getSmallConstantMaxTripCount(L) > 0 &&
SE.getSmallConstantMaxTripCount(L) <= 5) {
UP.PeelCount = 2;
}
}
bool HexagonTTIImpl::shouldFavorPostInc() const {
return true;
}
/// --- Vector TTI begin ---
unsigned HexagonTTIImpl::getNumberOfRegisters(bool Vector) const {
if (Vector)
return useHVX() ? 32 : 0;
return 32;
}
unsigned HexagonTTIImpl::getMaxInterleaveFactor(unsigned VF) {
return useHVX() ? 2 : 0;
}
unsigned HexagonTTIImpl::getRegisterBitWidth(bool Vector) const {
return Vector ? getMinVectorRegisterBitWidth() : 32;
}
unsigned HexagonTTIImpl::getMinVectorRegisterBitWidth() const {
return useHVX() ? ST.getVectorLength()*8 : 0;
}
unsigned HexagonTTIImpl::getMinimumVF(unsigned ElemWidth) const {
return (8 * ST.getVectorLength()) / ElemWidth;
}
unsigned HexagonTTIImpl::getScalarizationOverhead(Type *Ty, bool Insert,
bool Extract) {
return BaseT::getScalarizationOverhead(Ty, Insert, Extract);
}
unsigned HexagonTTIImpl::getOperandsScalarizationOverhead(
ArrayRef<const Value*> Args, unsigned VF) {
return BaseT::getOperandsScalarizationOverhead(Args, VF);
}
unsigned HexagonTTIImpl::getCallInstrCost(Function *F, Type *RetTy,
ArrayRef<Type*> Tys) {
return BaseT::getCallInstrCost(F, RetTy, Tys);
}
unsigned HexagonTTIImpl::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
ArrayRef<Value*> Args, FastMathFlags FMF, unsigned VF) {
return BaseT::getIntrinsicInstrCost(ID, RetTy, Args, FMF, VF);
}
unsigned HexagonTTIImpl::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
ArrayRef<Type*> Tys, FastMathFlags FMF,
unsigned ScalarizationCostPassed) {
if (ID == Intrinsic::bswap) {
std::pair<int, MVT> LT = TLI.getTypeLegalizationCost(DL, RetTy);
return LT.first + 2;
}
return BaseT::getIntrinsicInstrCost(ID, RetTy, Tys, FMF,
ScalarizationCostPassed);
}
unsigned HexagonTTIImpl::getAddressComputationCost(Type *Tp,
ScalarEvolution *SE, const SCEV *S) {
return 0;
}
unsigned HexagonTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
unsigned Alignment, unsigned AddressSpace, const Instruction *I) {
assert(Opcode == Instruction::Load || Opcode == Instruction::Store);
if (Opcode == Instruction::Store)
return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, I);
if (Src->isVectorTy()) {
VectorType *VecTy = cast<VectorType>(Src);
unsigned VecWidth = VecTy->getBitWidth();
if (useHVX() && isTypeForHVX(VecTy)) {
unsigned RegWidth = getRegisterBitWidth(true);
Alignment = std::min(Alignment, RegWidth/8);
// Cost of HVX loads.
if (VecWidth % RegWidth == 0)
return VecWidth / RegWidth;
// Cost of constructing HVX vector from scalar loads.
unsigned AlignWidth = 8 * std::max(1u, Alignment);
unsigned NumLoads = alignTo(VecWidth, AlignWidth) / AlignWidth;
return 3*NumLoads;
}
// Non-HVX vectors.
// Add extra cost for floating point types.
unsigned Cost = VecTy->getElementType()->isFloatingPointTy() ? FloatFactor
: 1;
Alignment = std::min(Alignment, 8u);
unsigned AlignWidth = 8 * std::max(1u, Alignment);
unsigned NumLoads = alignTo(VecWidth, AlignWidth) / AlignWidth;
if (Alignment == 4 || Alignment == 8)
return Cost * NumLoads;
// Loads of less than 32 bits will need extra inserts to compose a vector.
unsigned LogA = Log2_32(Alignment);
return (3 - LogA) * Cost * NumLoads;
}
return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, I);
}
unsigned HexagonTTIImpl::getMaskedMemoryOpCost(unsigned Opcode,
Type *Src, unsigned Alignment, unsigned AddressSpace) {
return BaseT::getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
}
unsigned HexagonTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp,
int Index, Type *SubTp) {
return 1;
}
unsigned HexagonTTIImpl::getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
Value *Ptr, bool VariableMask, unsigned Alignment) {
return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
Alignment);
}
unsigned HexagonTTIImpl::getInterleavedMemoryOpCost(unsigned Opcode,
Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
unsigned Alignment, unsigned AddressSpace, bool UseMaskForCond,
bool UseMaskForGaps) {
if (Indices.size() != Factor || UseMaskForCond || UseMaskForGaps)
return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
Alignment, AddressSpace,
UseMaskForCond, UseMaskForGaps);
return getMemoryOpCost(Opcode, VecTy, Alignment, AddressSpace, nullptr);
}
unsigned HexagonTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
Type *CondTy, const Instruction *I) {
if (ValTy->isVectorTy()) {
std::pair<int, MVT> LT = TLI.getTypeLegalizationCost(DL, ValTy);
if (Opcode == Instruction::FCmp)
return LT.first + FloatFactor * getTypeNumElements(ValTy);
}
return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
}
unsigned HexagonTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
TTI::OperandValueKind Opd1Info, TTI::OperandValueKind Opd2Info,
TTI::OperandValueProperties Opd1PropInfo,
TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value*> Args) {
if (Ty->isVectorTy()) {
std::pair<int, MVT> LT = TLI.getTypeLegalizationCost(DL, Ty);
if (LT.second.isFloatingPoint())
return LT.first + FloatFactor * getTypeNumElements(Ty);
}
return BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
Opd1PropInfo, Opd2PropInfo, Args);
}
unsigned HexagonTTIImpl::getCastInstrCost(unsigned Opcode, Type *DstTy,
Type *SrcTy, const Instruction *I) {
if (SrcTy->isFPOrFPVectorTy() || DstTy->isFPOrFPVectorTy()) {
unsigned SrcN = SrcTy->isFPOrFPVectorTy() ? getTypeNumElements(SrcTy) : 0;
unsigned DstN = DstTy->isFPOrFPVectorTy() ? getTypeNumElements(DstTy) : 0;
std::pair<int, MVT> SrcLT = TLI.getTypeLegalizationCost(DL, SrcTy);
std::pair<int, MVT> DstLT = TLI.getTypeLegalizationCost(DL, DstTy);
return std::max(SrcLT.first, DstLT.first) + FloatFactor * (SrcN + DstN);
}
return 1;
}
unsigned HexagonTTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
unsigned Index) {
Type *ElemTy = Val->isVectorTy() ? cast<VectorType>(Val)->getElementType()
: Val;
if (Opcode == Instruction::InsertElement) {
// Need two rotations for non-zero index.
unsigned Cost = (Index != 0) ? 2 : 0;
if (ElemTy->isIntegerTy(32))
return Cost;
// If it's not a 32-bit value, there will need to be an extract.
return Cost + getVectorInstrCost(Instruction::ExtractElement, Val, Index);
}
if (Opcode == Instruction::ExtractElement)
return 2;
return 1;
}
/// --- Vector TTI end ---
unsigned HexagonTTIImpl::getPrefetchDistance() const {
return ST.getL1PrefetchDistance();
}
unsigned HexagonTTIImpl::getCacheLineSize() const {
return ST.getL1CacheLineSize();
}
int HexagonTTIImpl::getUserCost(const User *U,
ArrayRef<const Value *> Operands) {
auto isCastFoldedIntoLoad = [this](const CastInst *CI) -> bool {
if (!CI->isIntegerCast())
return false;
// Only extensions from an integer type shorter than 32-bit to i32
// can be folded into the load.
const DataLayout &DL = getDataLayout();
unsigned SBW = DL.getTypeSizeInBits(CI->getSrcTy());
unsigned DBW = DL.getTypeSizeInBits(CI->getDestTy());
if (DBW != 32 || SBW >= DBW)
return false;
const LoadInst *LI = dyn_cast<const LoadInst>(CI->getOperand(0));
// Technically, this code could allow multiple uses of the load, and
// check if all the uses are the same extension operation, but this
// should be sufficient for most cases.
return LI && LI->hasOneUse();
};
if (const CastInst *CI = dyn_cast<const CastInst>(U))
if (isCastFoldedIntoLoad(CI))
return TargetTransformInfo::TCC_Free;
return BaseT::getUserCost(U, Operands);
}
bool HexagonTTIImpl::shouldBuildLookupTables() const {
return EmitLookupTables;
}
<commit_msg>[Hexagon] assert getRegisterBitWidth returns non-zero value. NFCI.<commit_after>//===- HexagonTargetTransformInfo.cpp - Hexagon specific TTI pass ---------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
/// \file
/// This file implements a TargetTransformInfo analysis pass specific to the
/// Hexagon target machine. It uses the target's detailed information to provide
/// more precise answers to certain TTI queries, while letting the target
/// independent and default TTI implementations handle the rest.
///
//===----------------------------------------------------------------------===//
#include "HexagonTargetTransformInfo.h"
#include "HexagonSubtarget.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/User.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/Utils/UnrollLoop.h"
using namespace llvm;
#define DEBUG_TYPE "hexagontti"
static cl::opt<bool> HexagonAutoHVX("hexagon-autohvx", cl::init(false),
cl::Hidden, cl::desc("Enable loop vectorizer for HVX"));
static cl::opt<bool> EmitLookupTables("hexagon-emit-lookup-tables",
cl::init(true), cl::Hidden,
cl::desc("Control lookup table emission on Hexagon target"));
// Constant "cost factor" to make floating point operations more expensive
// in terms of vectorization cost. This isn't the best way, but it should
// do. Ultimately, the cost should use cycles.
static const unsigned FloatFactor = 4;
bool HexagonTTIImpl::useHVX() const {
return ST.useHVXOps() && HexagonAutoHVX;
}
bool HexagonTTIImpl::isTypeForHVX(Type *VecTy) const {
assert(VecTy->isVectorTy());
// Avoid types like <2 x i32*>.
if (!cast<VectorType>(VecTy)->getElementType()->isIntegerTy())
return false;
EVT VecVT = EVT::getEVT(VecTy);
if (!VecVT.isSimple() || VecVT.getSizeInBits() <= 64)
return false;
if (ST.isHVXVectorType(VecVT.getSimpleVT()))
return true;
auto Action = TLI.getPreferredVectorAction(VecVT.getSimpleVT());
return Action == TargetLoweringBase::TypeWidenVector;
}
unsigned HexagonTTIImpl::getTypeNumElements(Type *Ty) const {
if (Ty->isVectorTy())
return Ty->getVectorNumElements();
assert((Ty->isIntegerTy() || Ty->isFloatingPointTy()) &&
"Expecting scalar type");
return 1;
}
TargetTransformInfo::PopcntSupportKind
HexagonTTIImpl::getPopcntSupport(unsigned IntTyWidthInBit) const {
// Return fast hardware support as every input < 64 bits will be promoted
// to 64 bits.
return TargetTransformInfo::PSK_FastHardware;
}
// The Hexagon target can unroll loops with run-time trip counts.
void HexagonTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
TTI::UnrollingPreferences &UP) {
UP.Runtime = UP.Partial = true;
// Only try to peel innermost loops with small runtime trip counts.
if (L && L->empty() && canPeel(L) &&
SE.getSmallConstantTripCount(L) == 0 &&
SE.getSmallConstantMaxTripCount(L) > 0 &&
SE.getSmallConstantMaxTripCount(L) <= 5) {
UP.PeelCount = 2;
}
}
bool HexagonTTIImpl::shouldFavorPostInc() const {
return true;
}
/// --- Vector TTI begin ---
unsigned HexagonTTIImpl::getNumberOfRegisters(bool Vector) const {
if (Vector)
return useHVX() ? 32 : 0;
return 32;
}
unsigned HexagonTTIImpl::getMaxInterleaveFactor(unsigned VF) {
return useHVX() ? 2 : 0;
}
unsigned HexagonTTIImpl::getRegisterBitWidth(bool Vector) const {
return Vector ? getMinVectorRegisterBitWidth() : 32;
}
unsigned HexagonTTIImpl::getMinVectorRegisterBitWidth() const {
return useHVX() ? ST.getVectorLength()*8 : 0;
}
unsigned HexagonTTIImpl::getMinimumVF(unsigned ElemWidth) const {
return (8 * ST.getVectorLength()) / ElemWidth;
}
unsigned HexagonTTIImpl::getScalarizationOverhead(Type *Ty, bool Insert,
bool Extract) {
return BaseT::getScalarizationOverhead(Ty, Insert, Extract);
}
unsigned HexagonTTIImpl::getOperandsScalarizationOverhead(
ArrayRef<const Value*> Args, unsigned VF) {
return BaseT::getOperandsScalarizationOverhead(Args, VF);
}
unsigned HexagonTTIImpl::getCallInstrCost(Function *F, Type *RetTy,
ArrayRef<Type*> Tys) {
return BaseT::getCallInstrCost(F, RetTy, Tys);
}
unsigned HexagonTTIImpl::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
ArrayRef<Value*> Args, FastMathFlags FMF, unsigned VF) {
return BaseT::getIntrinsicInstrCost(ID, RetTy, Args, FMF, VF);
}
unsigned HexagonTTIImpl::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
ArrayRef<Type*> Tys, FastMathFlags FMF,
unsigned ScalarizationCostPassed) {
if (ID == Intrinsic::bswap) {
std::pair<int, MVT> LT = TLI.getTypeLegalizationCost(DL, RetTy);
return LT.first + 2;
}
return BaseT::getIntrinsicInstrCost(ID, RetTy, Tys, FMF,
ScalarizationCostPassed);
}
unsigned HexagonTTIImpl::getAddressComputationCost(Type *Tp,
ScalarEvolution *SE, const SCEV *S) {
return 0;
}
unsigned HexagonTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
unsigned Alignment, unsigned AddressSpace, const Instruction *I) {
assert(Opcode == Instruction::Load || Opcode == Instruction::Store);
if (Opcode == Instruction::Store)
return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, I);
if (Src->isVectorTy()) {
VectorType *VecTy = cast<VectorType>(Src);
unsigned VecWidth = VecTy->getBitWidth();
if (useHVX() && isTypeForHVX(VecTy)) {
unsigned RegWidth = getRegisterBitWidth(true);
assert(RegWidth && "Non-zero vector register width expected");
// Cost of HVX loads.
if (VecWidth % RegWidth == 0)
return VecWidth / RegWidth;
// Cost of constructing HVX vector from scalar loads.
Alignment = std::min(Alignment, RegWidth / 8);
unsigned AlignWidth = 8 * std::max(1u, Alignment);
unsigned NumLoads = alignTo(VecWidth, AlignWidth) / AlignWidth;
return 3 * NumLoads;
}
// Non-HVX vectors.
// Add extra cost for floating point types.
unsigned Cost = VecTy->getElementType()->isFloatingPointTy() ? FloatFactor
: 1;
Alignment = std::min(Alignment, 8u);
unsigned AlignWidth = 8 * std::max(1u, Alignment);
unsigned NumLoads = alignTo(VecWidth, AlignWidth) / AlignWidth;
if (Alignment == 4 || Alignment == 8)
return Cost * NumLoads;
// Loads of less than 32 bits will need extra inserts to compose a vector.
unsigned LogA = Log2_32(Alignment);
return (3 - LogA) * Cost * NumLoads;
}
return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, I);
}
unsigned HexagonTTIImpl::getMaskedMemoryOpCost(unsigned Opcode,
Type *Src, unsigned Alignment, unsigned AddressSpace) {
return BaseT::getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
}
unsigned HexagonTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp,
int Index, Type *SubTp) {
return 1;
}
unsigned HexagonTTIImpl::getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
Value *Ptr, bool VariableMask, unsigned Alignment) {
return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
Alignment);
}
unsigned HexagonTTIImpl::getInterleavedMemoryOpCost(unsigned Opcode,
Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
unsigned Alignment, unsigned AddressSpace, bool UseMaskForCond,
bool UseMaskForGaps) {
if (Indices.size() != Factor || UseMaskForCond || UseMaskForGaps)
return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
Alignment, AddressSpace,
UseMaskForCond, UseMaskForGaps);
return getMemoryOpCost(Opcode, VecTy, Alignment, AddressSpace, nullptr);
}
unsigned HexagonTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
Type *CondTy, const Instruction *I) {
if (ValTy->isVectorTy()) {
std::pair<int, MVT> LT = TLI.getTypeLegalizationCost(DL, ValTy);
if (Opcode == Instruction::FCmp)
return LT.first + FloatFactor * getTypeNumElements(ValTy);
}
return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
}
unsigned HexagonTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
TTI::OperandValueKind Opd1Info, TTI::OperandValueKind Opd2Info,
TTI::OperandValueProperties Opd1PropInfo,
TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value*> Args) {
if (Ty->isVectorTy()) {
std::pair<int, MVT> LT = TLI.getTypeLegalizationCost(DL, Ty);
if (LT.second.isFloatingPoint())
return LT.first + FloatFactor * getTypeNumElements(Ty);
}
return BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
Opd1PropInfo, Opd2PropInfo, Args);
}
unsigned HexagonTTIImpl::getCastInstrCost(unsigned Opcode, Type *DstTy,
Type *SrcTy, const Instruction *I) {
if (SrcTy->isFPOrFPVectorTy() || DstTy->isFPOrFPVectorTy()) {
unsigned SrcN = SrcTy->isFPOrFPVectorTy() ? getTypeNumElements(SrcTy) : 0;
unsigned DstN = DstTy->isFPOrFPVectorTy() ? getTypeNumElements(DstTy) : 0;
std::pair<int, MVT> SrcLT = TLI.getTypeLegalizationCost(DL, SrcTy);
std::pair<int, MVT> DstLT = TLI.getTypeLegalizationCost(DL, DstTy);
return std::max(SrcLT.first, DstLT.first) + FloatFactor * (SrcN + DstN);
}
return 1;
}
unsigned HexagonTTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
unsigned Index) {
Type *ElemTy = Val->isVectorTy() ? cast<VectorType>(Val)->getElementType()
: Val;
if (Opcode == Instruction::InsertElement) {
// Need two rotations for non-zero index.
unsigned Cost = (Index != 0) ? 2 : 0;
if (ElemTy->isIntegerTy(32))
return Cost;
// If it's not a 32-bit value, there will need to be an extract.
return Cost + getVectorInstrCost(Instruction::ExtractElement, Val, Index);
}
if (Opcode == Instruction::ExtractElement)
return 2;
return 1;
}
/// --- Vector TTI end ---
unsigned HexagonTTIImpl::getPrefetchDistance() const {
return ST.getL1PrefetchDistance();
}
unsigned HexagonTTIImpl::getCacheLineSize() const {
return ST.getL1CacheLineSize();
}
int HexagonTTIImpl::getUserCost(const User *U,
ArrayRef<const Value *> Operands) {
auto isCastFoldedIntoLoad = [this](const CastInst *CI) -> bool {
if (!CI->isIntegerCast())
return false;
// Only extensions from an integer type shorter than 32-bit to i32
// can be folded into the load.
const DataLayout &DL = getDataLayout();
unsigned SBW = DL.getTypeSizeInBits(CI->getSrcTy());
unsigned DBW = DL.getTypeSizeInBits(CI->getDestTy());
if (DBW != 32 || SBW >= DBW)
return false;
const LoadInst *LI = dyn_cast<const LoadInst>(CI->getOperand(0));
// Technically, this code could allow multiple uses of the load, and
// check if all the uses are the same extension operation, but this
// should be sufficient for most cases.
return LI && LI->hasOneUse();
};
if (const CastInst *CI = dyn_cast<const CastInst>(U))
if (isCastFoldedIntoLoad(CI))
return TargetTransformInfo::TCC_Free;
return BaseT::getUserCost(U, Operands);
}
bool HexagonTTIImpl::shouldBuildLookupTables() const {
return EmitLookupTables;
}
<|endoftext|> |
<commit_before>//===--- RenamingAction.cpp - Clang refactoring library -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Provides an action to rename every symbol at a point.
///
//===----------------------------------------------------------------------===//
#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/FileManager.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Refactoring.h"
#include "clang/Tooling/Refactoring/RefactoringAction.h"
#include "clang/Tooling/Refactoring/RefactoringDiagnostic.h"
#include "clang/Tooling/Refactoring/RefactoringOptions.h"
#include "clang/Tooling/Refactoring/Rename/SymbolName.h"
#include "clang/Tooling/Refactoring/Rename/USRFinder.h"
#include "clang/Tooling/Refactoring/Rename/USRFindingAction.h"
#include "clang/Tooling/Refactoring/Rename/USRLocFinder.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/STLExtras.h"
#include <string>
#include <vector>
using namespace llvm;
namespace clang {
namespace tooling {
namespace {
class SymbolSelectionRequirement : public SourceRangeSelectionRequirement {
public:
Expected<const NamedDecl *> evaluate(RefactoringRuleContext &Context) const {
Expected<SourceRange> Selection =
SourceRangeSelectionRequirement::evaluate(Context);
if (!Selection)
return Selection.takeError();
const NamedDecl *ND =
getNamedDeclAt(Context.getASTContext(), Selection->getBegin());
if (!ND)
return Context.createDiagnosticError(
Selection->getBegin(), diag::err_refactor_selection_no_symbol);
return getCanonicalSymbolDeclaration(ND);
}
};
class OccurrenceFinder final : public FindSymbolOccurrencesRefactoringRule {
public:
OccurrenceFinder(const NamedDecl *ND) : ND(ND) {}
Expected<SymbolOccurrences>
findSymbolOccurrences(RefactoringRuleContext &Context) override {
std::vector<std::string> USRs =
getUSRsForDeclaration(ND, Context.getASTContext());
std::string PrevName = ND->getNameAsString();
return getOccurrencesOfUSRs(
USRs, PrevName, Context.getASTContext().getTranslationUnitDecl());
}
private:
const NamedDecl *ND;
};
class RenameOccurrences final : public SourceChangeRefactoringRule {
public:
RenameOccurrences(const NamedDecl *ND, std::string NewName)
: Finder(ND), NewName(NewName) {}
Expected<AtomicChanges>
createSourceReplacements(RefactoringRuleContext &Context) {
Expected<SymbolOccurrences> Occurrences =
Finder.findSymbolOccurrences(Context);
if (!Occurrences)
return Occurrences.takeError();
// FIXME: Verify that the new name is valid.
SymbolName Name(NewName);
return createRenameReplacements(
*Occurrences, Context.getASTContext().getSourceManager(), Name);
}
private:
OccurrenceFinder Finder;
std::string NewName;
};
class LocalRename final : public RefactoringAction {
public:
StringRef getCommand() const override { return "local-rename"; }
StringRef getDescription() const override {
return "Finds and renames symbols in code with no indexer support";
}
/// Returns a set of refactoring actions rules that are defined by this
/// action.
RefactoringActionRules createActionRules() const override {
RefactoringActionRules Rules;
Rules.push_back(createRefactoringActionRule<RenameOccurrences>(
SymbolSelectionRequirement(), OptionRequirement<NewNameOption>()));
return Rules;
}
};
} // end anonymous namespace
std::unique_ptr<RefactoringAction> createLocalRenameAction() {
return llvm::make_unique<LocalRename>();
}
Expected<std::vector<AtomicChange>>
createRenameReplacements(const SymbolOccurrences &Occurrences,
const SourceManager &SM, const SymbolName &NewName) {
// FIXME: A true local rename can use just one AtomicChange.
std::vector<AtomicChange> Changes;
for (const auto &Occurrence : Occurrences) {
ArrayRef<SourceRange> Ranges = Occurrence.getNameRanges();
assert(NewName.getNamePieces().size() == Ranges.size() &&
"Mismatching number of ranges and name pieces");
AtomicChange Change(SM, Ranges[0].getBegin());
for (const auto &Range : llvm::enumerate(Ranges)) {
auto Error =
Change.replace(SM, CharSourceRange::getCharRange(Range.value()),
NewName.getNamePieces()[Range.index()]);
if (Error)
return std::move(Error);
}
Changes.push_back(std::move(Change));
}
return std::move(Changes);
}
/// Takes each atomic change and inserts its replacements into the set of
/// replacements that belong to the appropriate file.
static void convertChangesToFileReplacements(
ArrayRef<AtomicChange> AtomicChanges,
std::map<std::string, tooling::Replacements> *FileToReplaces) {
for (const auto &AtomicChange : AtomicChanges) {
for (const auto &Replace : AtomicChange.getReplacements()) {
llvm::Error Err = (*FileToReplaces)[Replace.getFilePath()].add(Replace);
if (Err) {
llvm::errs() << "Renaming failed in " << Replace.getFilePath() << "! "
<< llvm::toString(std::move(Err)) << "\n";
}
}
}
}
class RenamingASTConsumer : public ASTConsumer {
public:
RenamingASTConsumer(
const std::vector<std::string> &NewNames,
const std::vector<std::string> &PrevNames,
const std::vector<std::vector<std::string>> &USRList,
std::map<std::string, tooling::Replacements> &FileToReplaces,
bool PrintLocations)
: NewNames(NewNames), PrevNames(PrevNames), USRList(USRList),
FileToReplaces(FileToReplaces), PrintLocations(PrintLocations) {}
void HandleTranslationUnit(ASTContext &Context) override {
for (unsigned I = 0; I < NewNames.size(); ++I) {
// If the previous name was not found, ignore this rename request.
if (PrevNames[I].empty())
continue;
HandleOneRename(Context, NewNames[I], PrevNames[I], USRList[I]);
}
}
void HandleOneRename(ASTContext &Context, const std::string &NewName,
const std::string &PrevName,
const std::vector<std::string> &USRs) {
const SourceManager &SourceMgr = Context.getSourceManager();
SymbolOccurrences Occurrences = tooling::getOccurrencesOfUSRs(
USRs, PrevName, Context.getTranslationUnitDecl());
if (PrintLocations) {
for (const auto &Occurrence : Occurrences) {
FullSourceLoc FullLoc(Occurrence.getNameRanges()[0].getBegin(),
SourceMgr);
errs() << "clang-rename: renamed at: " << SourceMgr.getFilename(FullLoc)
<< ":" << FullLoc.getSpellingLineNumber() << ":"
<< FullLoc.getSpellingColumnNumber() << "\n";
}
}
// FIXME: Support multi-piece names.
// FIXME: better error handling (propagate error out).
SymbolName NewNameRef(NewName);
Expected<std::vector<AtomicChange>> Change =
createRenameReplacements(Occurrences, SourceMgr, NewNameRef);
if (!Change) {
llvm::errs() << "Failed to create renaming replacements for '" << PrevName
<< "'! " << llvm::toString(Change.takeError()) << "\n";
return;
}
convertChangesToFileReplacements(*Change, &FileToReplaces);
}
private:
const std::vector<std::string> &NewNames, &PrevNames;
const std::vector<std::vector<std::string>> &USRList;
std::map<std::string, tooling::Replacements> &FileToReplaces;
bool PrintLocations;
};
// A renamer to rename symbols which are identified by a give USRList to
// new name.
//
// FIXME: Merge with the above RenamingASTConsumer.
class USRSymbolRenamer : public ASTConsumer {
public:
USRSymbolRenamer(const std::vector<std::string> &NewNames,
const std::vector<std::vector<std::string>> &USRList,
std::map<std::string, tooling::Replacements> &FileToReplaces)
: NewNames(NewNames), USRList(USRList), FileToReplaces(FileToReplaces) {
assert(USRList.size() == NewNames.size());
}
void HandleTranslationUnit(ASTContext &Context) override {
for (unsigned I = 0; I < NewNames.size(); ++I) {
// FIXME: Apply AtomicChanges directly once the refactoring APIs are
// ready.
auto AtomicChanges = tooling::createRenameAtomicChanges(
USRList[I], NewNames[I], Context.getTranslationUnitDecl());
convertChangesToFileReplacements(AtomicChanges, &FileToReplaces);
}
}
private:
const std::vector<std::string> &NewNames;
const std::vector<std::vector<std::string>> &USRList;
std::map<std::string, tooling::Replacements> &FileToReplaces;
};
std::unique_ptr<ASTConsumer> RenamingAction::newASTConsumer() {
return llvm::make_unique<RenamingASTConsumer>(NewNames, PrevNames, USRList,
FileToReplaces, PrintLocations);
}
std::unique_ptr<ASTConsumer> QualifiedRenamingAction::newASTConsumer() {
return llvm::make_unique<USRSymbolRenamer>(NewNames, USRList, FileToReplaces);
}
} // end namespace tooling
} // end namespace clang
<commit_msg>Fix a few nits in RenamingAction.<commit_after>//===--- RenamingAction.cpp - Clang refactoring library -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Provides an action to rename every symbol at a point.
///
//===----------------------------------------------------------------------===//
#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/FileManager.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Refactoring.h"
#include "clang/Tooling/Refactoring/RefactoringAction.h"
#include "clang/Tooling/Refactoring/RefactoringDiagnostic.h"
#include "clang/Tooling/Refactoring/RefactoringOptions.h"
#include "clang/Tooling/Refactoring/Rename/SymbolName.h"
#include "clang/Tooling/Refactoring/Rename/USRFinder.h"
#include "clang/Tooling/Refactoring/Rename/USRFindingAction.h"
#include "clang/Tooling/Refactoring/Rename/USRLocFinder.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/STLExtras.h"
#include <string>
#include <vector>
using namespace llvm;
namespace clang {
namespace tooling {
namespace {
class SymbolSelectionRequirement : public SourceRangeSelectionRequirement {
public:
Expected<const NamedDecl *> evaluate(RefactoringRuleContext &Context) const {
Expected<SourceRange> Selection =
SourceRangeSelectionRequirement::evaluate(Context);
if (!Selection)
return Selection.takeError();
const NamedDecl *ND =
getNamedDeclAt(Context.getASTContext(), Selection->getBegin());
if (!ND)
return Context.createDiagnosticError(
Selection->getBegin(), diag::err_refactor_selection_no_symbol);
return getCanonicalSymbolDeclaration(ND);
}
};
class OccurrenceFinder final : public FindSymbolOccurrencesRefactoringRule {
public:
OccurrenceFinder(const NamedDecl *ND) : ND(ND) {}
Expected<SymbolOccurrences>
findSymbolOccurrences(RefactoringRuleContext &Context) override {
std::vector<std::string> USRs =
getUSRsForDeclaration(ND, Context.getASTContext());
std::string PrevName = ND->getNameAsString();
return getOccurrencesOfUSRs(
USRs, PrevName, Context.getASTContext().getTranslationUnitDecl());
}
private:
const NamedDecl *ND;
};
class RenameOccurrences final : public SourceChangeRefactoringRule {
public:
RenameOccurrences(const NamedDecl *ND, std::string NewName)
: Finder(ND), NewName(std::move(NewName)) {}
Expected<AtomicChanges>
createSourceReplacements(RefactoringRuleContext &Context) override {
Expected<SymbolOccurrences> Occurrences =
Finder.findSymbolOccurrences(Context);
if (!Occurrences)
return Occurrences.takeError();
// FIXME: Verify that the new name is valid.
SymbolName Name(NewName);
return createRenameReplacements(
*Occurrences, Context.getASTContext().getSourceManager(), Name);
}
private:
OccurrenceFinder Finder;
std::string NewName;
};
class LocalRename final : public RefactoringAction {
public:
StringRef getCommand() const override { return "local-rename"; }
StringRef getDescription() const override {
return "Finds and renames symbols in code with no indexer support";
}
/// Returns a set of refactoring actions rules that are defined by this
/// action.
RefactoringActionRules createActionRules() const override {
RefactoringActionRules Rules;
Rules.push_back(createRefactoringActionRule<RenameOccurrences>(
SymbolSelectionRequirement(), OptionRequirement<NewNameOption>()));
return Rules;
}
};
} // end anonymous namespace
std::unique_ptr<RefactoringAction> createLocalRenameAction() {
return llvm::make_unique<LocalRename>();
}
Expected<std::vector<AtomicChange>>
createRenameReplacements(const SymbolOccurrences &Occurrences,
const SourceManager &SM, const SymbolName &NewName) {
// FIXME: A true local rename can use just one AtomicChange.
std::vector<AtomicChange> Changes;
for (const auto &Occurrence : Occurrences) {
ArrayRef<SourceRange> Ranges = Occurrence.getNameRanges();
assert(NewName.getNamePieces().size() == Ranges.size() &&
"Mismatching number of ranges and name pieces");
AtomicChange Change(SM, Ranges[0].getBegin());
for (const auto &Range : llvm::enumerate(Ranges)) {
auto Error =
Change.replace(SM, CharSourceRange::getCharRange(Range.value()),
NewName.getNamePieces()[Range.index()]);
if (Error)
return std::move(Error);
}
Changes.push_back(std::move(Change));
}
return std::move(Changes);
}
/// Takes each atomic change and inserts its replacements into the set of
/// replacements that belong to the appropriate file.
static void convertChangesToFileReplacements(
ArrayRef<AtomicChange> AtomicChanges,
std::map<std::string, tooling::Replacements> *FileToReplaces) {
for (const auto &AtomicChange : AtomicChanges) {
for (const auto &Replace : AtomicChange.getReplacements()) {
llvm::Error Err = (*FileToReplaces)[Replace.getFilePath()].add(Replace);
if (Err) {
llvm::errs() << "Renaming failed in " << Replace.getFilePath() << "! "
<< llvm::toString(std::move(Err)) << "\n";
}
}
}
}
class RenamingASTConsumer : public ASTConsumer {
public:
RenamingASTConsumer(
const std::vector<std::string> &NewNames,
const std::vector<std::string> &PrevNames,
const std::vector<std::vector<std::string>> &USRList,
std::map<std::string, tooling::Replacements> &FileToReplaces,
bool PrintLocations)
: NewNames(NewNames), PrevNames(PrevNames), USRList(USRList),
FileToReplaces(FileToReplaces), PrintLocations(PrintLocations) {}
void HandleTranslationUnit(ASTContext &Context) override {
for (unsigned I = 0; I < NewNames.size(); ++I) {
// If the previous name was not found, ignore this rename request.
if (PrevNames[I].empty())
continue;
HandleOneRename(Context, NewNames[I], PrevNames[I], USRList[I]);
}
}
void HandleOneRename(ASTContext &Context, const std::string &NewName,
const std::string &PrevName,
const std::vector<std::string> &USRs) {
const SourceManager &SourceMgr = Context.getSourceManager();
SymbolOccurrences Occurrences = tooling::getOccurrencesOfUSRs(
USRs, PrevName, Context.getTranslationUnitDecl());
if (PrintLocations) {
for (const auto &Occurrence : Occurrences) {
FullSourceLoc FullLoc(Occurrence.getNameRanges()[0].getBegin(),
SourceMgr);
errs() << "clang-rename: renamed at: " << SourceMgr.getFilename(FullLoc)
<< ":" << FullLoc.getSpellingLineNumber() << ":"
<< FullLoc.getSpellingColumnNumber() << "\n";
}
}
// FIXME: Support multi-piece names.
// FIXME: better error handling (propagate error out).
SymbolName NewNameRef(NewName);
Expected<std::vector<AtomicChange>> Change =
createRenameReplacements(Occurrences, SourceMgr, NewNameRef);
if (!Change) {
llvm::errs() << "Failed to create renaming replacements for '" << PrevName
<< "'! " << llvm::toString(Change.takeError()) << "\n";
return;
}
convertChangesToFileReplacements(*Change, &FileToReplaces);
}
private:
const std::vector<std::string> &NewNames, &PrevNames;
const std::vector<std::vector<std::string>> &USRList;
std::map<std::string, tooling::Replacements> &FileToReplaces;
bool PrintLocations;
};
// A renamer to rename symbols which are identified by a give USRList to
// new name.
//
// FIXME: Merge with the above RenamingASTConsumer.
class USRSymbolRenamer : public ASTConsumer {
public:
USRSymbolRenamer(const std::vector<std::string> &NewNames,
const std::vector<std::vector<std::string>> &USRList,
std::map<std::string, tooling::Replacements> &FileToReplaces)
: NewNames(NewNames), USRList(USRList), FileToReplaces(FileToReplaces) {
assert(USRList.size() == NewNames.size());
}
void HandleTranslationUnit(ASTContext &Context) override {
for (unsigned I = 0; I < NewNames.size(); ++I) {
// FIXME: Apply AtomicChanges directly once the refactoring APIs are
// ready.
auto AtomicChanges = tooling::createRenameAtomicChanges(
USRList[I], NewNames[I], Context.getTranslationUnitDecl());
convertChangesToFileReplacements(AtomicChanges, &FileToReplaces);
}
}
private:
const std::vector<std::string> &NewNames;
const std::vector<std::vector<std::string>> &USRList;
std::map<std::string, tooling::Replacements> &FileToReplaces;
};
std::unique_ptr<ASTConsumer> RenamingAction::newASTConsumer() {
return llvm::make_unique<RenamingASTConsumer>(NewNames, PrevNames, USRList,
FileToReplaces, PrintLocations);
}
std::unique_ptr<ASTConsumer> QualifiedRenamingAction::newASTConsumer() {
return llvm::make_unique<USRSymbolRenamer>(NewNames, USRList, FileToReplaces);
}
} // end namespace tooling
} // end namespace clang
<|endoftext|> |
<commit_before>//===- BoundsChecking.cpp - Instrumentation for run-time bounds checking --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a pass that instruments the code to perform run-time
// bounds checking on loads, stores, and other memory intrinsics.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "bounds-checking"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/Support/TargetFolder.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetLibraryInfo.h"
using namespace llvm;
static cl::opt<bool> SingleTrapBB("bounds-checking-single-trap",
cl::desc("Use one trap block per function"));
STATISTIC(ChecksAdded, "Bounds checks added");
STATISTIC(ChecksSkipped, "Bounds checks skipped");
STATISTIC(ChecksUnable, "Bounds checks unable to add");
typedef IRBuilder<true, TargetFolder> BuilderTy;
namespace {
struct BoundsChecking : public FunctionPass {
static char ID;
BoundsChecking() : FunctionPass(ID) {
initializeBoundsCheckingPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnFunction(Function &F);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<DataLayout>();
AU.addRequired<TargetLibraryInfo>();
}
private:
const DataLayout *TD;
const TargetLibraryInfo *TLI;
ObjectSizeOffsetEvaluator *ObjSizeEval;
BuilderTy *Builder;
Instruction *Inst;
BasicBlock *TrapBB;
BasicBlock *getTrapBB();
void emitBranchToTrap(Value *Cmp = 0);
bool computeAllocSize(Value *Ptr, APInt &Offset, Value* &OffsetValue,
APInt &Size, Value* &SizeValue);
bool instrument(Value *Ptr, Value *Val);
};
}
char BoundsChecking::ID = 0;
INITIALIZE_PASS(BoundsChecking, "bounds-checking", "Run-time bounds checking",
false, false)
/// getTrapBB - create a basic block that traps. All overflowing conditions
/// branch to this block. There's only one trap block per function.
BasicBlock *BoundsChecking::getTrapBB() {
if (TrapBB && SingleTrapBB)
return TrapBB;
Function *Fn = Inst->getParent()->getParent();
IRBuilder<>::InsertPointGuard Guard(*Builder);
TrapBB = BasicBlock::Create(Fn->getContext(), "trap", Fn);
llvm::Value *F = Intrinsic::getDeclaration(Fn->getParent(), Intrinsic::trap);
CallInst *TrapCall = Builder->CreateCall(F);
TrapCall->setDoesNotReturn();
TrapCall->setDoesNotThrow();
TrapCall->setDebugLoc(Inst->getDebugLoc());
Builder->CreateUnreachable();
return TrapBB;
}
/// emitBranchToTrap - emit a branch instruction to a trap block.
/// If Cmp is non-null, perform a jump only if its value evaluates to true.
void BoundsChecking::emitBranchToTrap(Value *Cmp) {
// check if the comparison is always false
ConstantInt *C = dyn_cast_or_null<ConstantInt>(Cmp);
if (C) {
++ChecksSkipped;
if (!C->getZExtValue())
return;
else
Cmp = 0; // unconditional branch
}
++ChecksAdded;
Instruction *Inst = Builder->GetInsertPoint();
BasicBlock *OldBB = Inst->getParent();
BasicBlock *Cont = OldBB->splitBasicBlock(Inst);
OldBB->getTerminator()->eraseFromParent();
if (Cmp)
BranchInst::Create(getTrapBB(), Cont, Cmp, OldBB);
else
BranchInst::Create(getTrapBB(), OldBB);
}
/// instrument - adds run-time bounds checks to memory accessing instructions.
/// Ptr is the pointer that will be read/written, and InstVal is either the
/// result from the load or the value being stored. It is used to determine the
/// size of memory block that is touched.
/// Returns true if any change was made to the IR, false otherwise.
bool BoundsChecking::instrument(Value *Ptr, Value *InstVal) {
uint64_t NeededSize = TD->getTypeStoreSize(InstVal->getType());
DEBUG(dbgs() << "Instrument " << *Ptr << " for " << Twine(NeededSize)
<< " bytes\n");
SizeOffsetEvalType SizeOffset = ObjSizeEval->compute(Ptr);
if (!ObjSizeEval->bothKnown(SizeOffset)) {
++ChecksUnable;
return false;
}
Value *Size = SizeOffset.first;
Value *Offset = SizeOffset.second;
ConstantInt *SizeCI = dyn_cast<ConstantInt>(Size);
Type *IntTy = TD->getIntPtrType(Ptr->getType());
Value *NeededSizeVal = ConstantInt::get(IntTy, NeededSize);
// three checks are required to ensure safety:
// . Offset >= 0 (since the offset is given from the base ptr)
// . Size >= Offset (unsigned)
// . Size - Offset >= NeededSize (unsigned)
//
// optimization: if Size >= 0 (signed), skip 1st check
// FIXME: add NSW/NUW here? -- we dont care if the subtraction overflows
Value *ObjSize = Builder->CreateSub(Size, Offset);
Value *Cmp2 = Builder->CreateICmpULT(Size, Offset);
Value *Cmp3 = Builder->CreateICmpULT(ObjSize, NeededSizeVal);
Value *Or = Builder->CreateOr(Cmp2, Cmp3);
if (!SizeCI || SizeCI->getValue().slt(0)) {
Value *Cmp1 = Builder->CreateICmpSLT(Offset, ConstantInt::get(IntTy, 0));
Or = Builder->CreateOr(Cmp1, Or);
}
emitBranchToTrap(Or);
return true;
}
bool BoundsChecking::runOnFunction(Function &F) {
TD = &getAnalysis<DataLayout>();
TLI = &getAnalysis<TargetLibraryInfo>();
TrapBB = 0;
BuilderTy TheBuilder(F.getContext(), TargetFolder(TD));
Builder = &TheBuilder;
ObjectSizeOffsetEvaluator TheObjSizeEval(TD, TLI, F.getContext());
ObjSizeEval = &TheObjSizeEval;
// check HANDLE_MEMORY_INST in include/llvm/Instruction.def for memory
// touching instructions
std::vector<Instruction*> WorkList;
for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) {
Instruction *I = &*i;
if (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<AtomicCmpXchgInst>(I) ||
isa<AtomicRMWInst>(I))
WorkList.push_back(I);
}
bool MadeChange = false;
for (std::vector<Instruction*>::iterator i = WorkList.begin(),
e = WorkList.end(); i != e; ++i) {
Inst = *i;
Builder->SetInsertPoint(Inst);
if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
MadeChange |= instrument(LI->getPointerOperand(), LI);
} else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
MadeChange |= instrument(SI->getPointerOperand(), SI->getValueOperand());
} else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Inst)) {
MadeChange |= instrument(AI->getPointerOperand(),AI->getCompareOperand());
} else if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(Inst)) {
MadeChange |= instrument(AI->getPointerOperand(), AI->getValOperand());
} else {
llvm_unreachable("unknown Instruction type");
}
}
return MadeChange;
}
FunctionPass *llvm::createBoundsCheckingPass() {
return new BoundsChecking();
}
<commit_msg>BoundsChecking: Fix refacto.<commit_after>//===- BoundsChecking.cpp - Instrumentation for run-time bounds checking --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a pass that instruments the code to perform run-time
// bounds checking on loads, stores, and other memory intrinsics.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "bounds-checking"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/Support/TargetFolder.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetLibraryInfo.h"
using namespace llvm;
static cl::opt<bool> SingleTrapBB("bounds-checking-single-trap",
cl::desc("Use one trap block per function"));
STATISTIC(ChecksAdded, "Bounds checks added");
STATISTIC(ChecksSkipped, "Bounds checks skipped");
STATISTIC(ChecksUnable, "Bounds checks unable to add");
typedef IRBuilder<true, TargetFolder> BuilderTy;
namespace {
struct BoundsChecking : public FunctionPass {
static char ID;
BoundsChecking() : FunctionPass(ID) {
initializeBoundsCheckingPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnFunction(Function &F);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<DataLayout>();
AU.addRequired<TargetLibraryInfo>();
}
private:
const DataLayout *TD;
const TargetLibraryInfo *TLI;
ObjectSizeOffsetEvaluator *ObjSizeEval;
BuilderTy *Builder;
Instruction *Inst;
BasicBlock *TrapBB;
BasicBlock *getTrapBB();
void emitBranchToTrap(Value *Cmp = 0);
bool computeAllocSize(Value *Ptr, APInt &Offset, Value* &OffsetValue,
APInt &Size, Value* &SizeValue);
bool instrument(Value *Ptr, Value *Val);
};
}
char BoundsChecking::ID = 0;
INITIALIZE_PASS(BoundsChecking, "bounds-checking", "Run-time bounds checking",
false, false)
/// getTrapBB - create a basic block that traps. All overflowing conditions
/// branch to this block. There's only one trap block per function.
BasicBlock *BoundsChecking::getTrapBB() {
if (TrapBB && SingleTrapBB)
return TrapBB;
Function *Fn = Inst->getParent()->getParent();
IRBuilder<>::InsertPointGuard Guard(*Builder);
TrapBB = BasicBlock::Create(Fn->getContext(), "trap", Fn);
Builder->SetInsertPoint(TrapBB);
llvm::Value *F = Intrinsic::getDeclaration(Fn->getParent(), Intrinsic::trap);
CallInst *TrapCall = Builder->CreateCall(F);
TrapCall->setDoesNotReturn();
TrapCall->setDoesNotThrow();
TrapCall->setDebugLoc(Inst->getDebugLoc());
Builder->CreateUnreachable();
return TrapBB;
}
/// emitBranchToTrap - emit a branch instruction to a trap block.
/// If Cmp is non-null, perform a jump only if its value evaluates to true.
void BoundsChecking::emitBranchToTrap(Value *Cmp) {
// check if the comparison is always false
ConstantInt *C = dyn_cast_or_null<ConstantInt>(Cmp);
if (C) {
++ChecksSkipped;
if (!C->getZExtValue())
return;
else
Cmp = 0; // unconditional branch
}
++ChecksAdded;
Instruction *Inst = Builder->GetInsertPoint();
BasicBlock *OldBB = Inst->getParent();
BasicBlock *Cont = OldBB->splitBasicBlock(Inst);
OldBB->getTerminator()->eraseFromParent();
if (Cmp)
BranchInst::Create(getTrapBB(), Cont, Cmp, OldBB);
else
BranchInst::Create(getTrapBB(), OldBB);
}
/// instrument - adds run-time bounds checks to memory accessing instructions.
/// Ptr is the pointer that will be read/written, and InstVal is either the
/// result from the load or the value being stored. It is used to determine the
/// size of memory block that is touched.
/// Returns true if any change was made to the IR, false otherwise.
bool BoundsChecking::instrument(Value *Ptr, Value *InstVal) {
uint64_t NeededSize = TD->getTypeStoreSize(InstVal->getType());
DEBUG(dbgs() << "Instrument " << *Ptr << " for " << Twine(NeededSize)
<< " bytes\n");
SizeOffsetEvalType SizeOffset = ObjSizeEval->compute(Ptr);
if (!ObjSizeEval->bothKnown(SizeOffset)) {
++ChecksUnable;
return false;
}
Value *Size = SizeOffset.first;
Value *Offset = SizeOffset.second;
ConstantInt *SizeCI = dyn_cast<ConstantInt>(Size);
Type *IntTy = TD->getIntPtrType(Ptr->getType());
Value *NeededSizeVal = ConstantInt::get(IntTy, NeededSize);
// three checks are required to ensure safety:
// . Offset >= 0 (since the offset is given from the base ptr)
// . Size >= Offset (unsigned)
// . Size - Offset >= NeededSize (unsigned)
//
// optimization: if Size >= 0 (signed), skip 1st check
// FIXME: add NSW/NUW here? -- we dont care if the subtraction overflows
Value *ObjSize = Builder->CreateSub(Size, Offset);
Value *Cmp2 = Builder->CreateICmpULT(Size, Offset);
Value *Cmp3 = Builder->CreateICmpULT(ObjSize, NeededSizeVal);
Value *Or = Builder->CreateOr(Cmp2, Cmp3);
if (!SizeCI || SizeCI->getValue().slt(0)) {
Value *Cmp1 = Builder->CreateICmpSLT(Offset, ConstantInt::get(IntTy, 0));
Or = Builder->CreateOr(Cmp1, Or);
}
emitBranchToTrap(Or);
return true;
}
bool BoundsChecking::runOnFunction(Function &F) {
TD = &getAnalysis<DataLayout>();
TLI = &getAnalysis<TargetLibraryInfo>();
TrapBB = 0;
BuilderTy TheBuilder(F.getContext(), TargetFolder(TD));
Builder = &TheBuilder;
ObjectSizeOffsetEvaluator TheObjSizeEval(TD, TLI, F.getContext());
ObjSizeEval = &TheObjSizeEval;
// check HANDLE_MEMORY_INST in include/llvm/Instruction.def for memory
// touching instructions
std::vector<Instruction*> WorkList;
for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) {
Instruction *I = &*i;
if (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<AtomicCmpXchgInst>(I) ||
isa<AtomicRMWInst>(I))
WorkList.push_back(I);
}
bool MadeChange = false;
for (std::vector<Instruction*>::iterator i = WorkList.begin(),
e = WorkList.end(); i != e; ++i) {
Inst = *i;
Builder->SetInsertPoint(Inst);
if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
MadeChange |= instrument(LI->getPointerOperand(), LI);
} else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
MadeChange |= instrument(SI->getPointerOperand(), SI->getValueOperand());
} else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Inst)) {
MadeChange |= instrument(AI->getPointerOperand(),AI->getCompareOperand());
} else if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(Inst)) {
MadeChange |= instrument(AI->getPointerOperand(), AI->getValOperand());
} else {
llvm_unreachable("unknown Instruction type");
}
}
return MadeChange;
}
FunctionPass *llvm::createBoundsCheckingPass() {
return new BoundsChecking();
}
<|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: geometricObject.C,v 1.25.16.1 2007/03/25 22:02:22 oliver Exp $
//
#include <BALL/VIEW/KERNEL/geometricObject.h>
#include <BALL/VIEW/DATATYPE/colorExtensions.h>
using std::endl;
using std::ostream;
using std::istream;
namespace BALL
{
namespace VIEW
{
GeometricObject::GeometricObject()
: color_(),
composite_(0)
{
}
GeometricObject::GeometricObject(const GeometricObject& geometric_object)
: color_(geometric_object.color_),
composite_(geometric_object.composite_)
{
}
GeometricObject::~GeometricObject()
{
#ifdef BALL_VIEW_DEBUG
Log.info() << "Destructing object " << this << " of class " << RTTI::getName<GeometricObject>() << endl;
#endif
}
void GeometricObject::clear()
{
color_ = ColorRGBA();
composite_ = 0;
}
void GeometricObject::set(const GeometricObject& geometric_object)
{
color_ = geometric_object.color_;
composite_ = geometric_object.composite_;
}
GeometricObject& GeometricObject::operator = (const GeometricObject& geometric_object)
{
set(geometric_object);
return *this;
}
void GeometricObject::swap(GeometricObject& geometric_object)
{
const Composite* composite = geometric_object.composite_;
geometric_object.composite_ = composite_;
composite_ = composite;
}
void GeometricObject::dump(ostream& s, Size depth) const
{
BALL_DUMP_STREAM_PREFIX(s);
BALL_DUMP_DEPTH(s, depth);
BALL_DUMP_HEADER(s, this, this);
BALL_DUMP_DEPTH(s,depth);
s << "composite : " << composite_ << endl;
BALL_DUMP_STREAM_SUFFIX(s);
}
void GeometricObject::getColors(HashSet<String>& color_set)
{
String c;
MultiColorExtension* mce = dynamic_cast<MultiColorExtension*>(this);
if (mce != 0)
{
const vector<ColorRGBA>& cs = mce->getColors();
for (Position p = 0; p < cs.size(); p++)
{
cs[p].get(c);
color_set.insert(c);
}
return;
}
ColorExtension2* ce2 = dynamic_cast<ColorExtension2*>(this);
if (ce2 != 0)
{
ce2->getColor2().get(c);
color_set.insert(c);
}
getColor().get(c);
color_set.insert(c);
}
} // namespace VIEW
} // namespace BALL
<commit_msg>Remove obsolete $Id$ from geometricObject.C.<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/VIEW/KERNEL/geometricObject.h>
#include <BALL/VIEW/DATATYPE/colorExtensions.h>
using std::endl;
using std::ostream;
using std::istream;
namespace BALL
{
namespace VIEW
{
GeometricObject::GeometricObject()
: color_(),
composite_(0)
{
}
GeometricObject::GeometricObject(const GeometricObject& geometric_object)
: color_(geometric_object.color_),
composite_(geometric_object.composite_)
{
}
GeometricObject::~GeometricObject()
{
#ifdef BALL_VIEW_DEBUG
Log.info() << "Destructing object " << this << " of class " << RTTI::getName<GeometricObject>() << endl;
#endif
}
void GeometricObject::clear()
{
color_ = ColorRGBA();
composite_ = 0;
}
void GeometricObject::set(const GeometricObject& geometric_object)
{
color_ = geometric_object.color_;
composite_ = geometric_object.composite_;
}
GeometricObject& GeometricObject::operator = (const GeometricObject& geometric_object)
{
set(geometric_object);
return *this;
}
void GeometricObject::swap(GeometricObject& geometric_object)
{
const Composite* composite = geometric_object.composite_;
geometric_object.composite_ = composite_;
composite_ = composite;
}
void GeometricObject::dump(ostream& s, Size depth) const
{
BALL_DUMP_STREAM_PREFIX(s);
BALL_DUMP_DEPTH(s, depth);
BALL_DUMP_HEADER(s, this, this);
BALL_DUMP_DEPTH(s,depth);
s << "composite : " << composite_ << endl;
BALL_DUMP_STREAM_SUFFIX(s);
}
void GeometricObject::getColors(HashSet<String>& color_set)
{
String c;
MultiColorExtension* mce = dynamic_cast<MultiColorExtension*>(this);
if (mce != 0)
{
const vector<ColorRGBA>& cs = mce->getColors();
for (Position p = 0; p < cs.size(); p++)
{
cs[p].get(c);
color_set.insert(c);
}
return;
}
ColorExtension2* ce2 = dynamic_cast<ColorExtension2*>(this);
if (ce2 != 0)
{
ce2->getColor2().get(c);
color_set.insert(c);
}
getColor().get(c);
color_set.insert(c);
}
} // namespace VIEW
} // namespace BALL
<|endoftext|> |
<commit_before>/*
* ConnectionProbe.hpp
*
* Created on: Apr 25, 2009
* Author: rasmussn
*/
#ifndef CONNECTIONPROBE_HPP_
#define CONNECTIONPROBE_HPP_
#include "../connections/HyPerConn.hpp"
namespace PV {
class ConnectionProbe {
public:
ConnectionProbe(int kPre);
ConnectionProbe(int kxPre, int kyPre, int kfPre);
ConnectionProbe(const char * filename, int kPre);
ConnectionProbe(const char * filename,int kxPre, int kyPre, int kfPre);
virtual ~ConnectionProbe();
virtual int outputState(float time, HyPerConn * c);
static int text_write_patch(FILE * fd, PVPatch * patch, float * data);
static int write_patch_indices(FILE * fp, PVPatch * patch,
const PVLayerLoc * loc, int kx0, int ky0, int kf0);
void setOutputIndices(bool flag) {outputIndices = flag;}
protected:
FILE * fp;
int kPre; // index of pre-synaptic neuron
int kxPre, kyPre, kfPre;
bool outputIndices;
};
} // namespace PV
#endif /* CONNECTIONPROBE_HPP_ */
<commit_msg>A flag was introduced to signal if we want to write STDP variables or not. A method to set this flag was added.<commit_after>/*
* ConnectionProbe.hpp
*
* Created on: Apr 25, 2009
* Author: rasmussn
*/
#ifndef CONNECTIONPROBE_HPP_
#define CONNECTIONPROBE_HPP_
#include "../connections/HyPerConn.hpp"
namespace PV {
class ConnectionProbe {
public:
ConnectionProbe(int kPre);
ConnectionProbe(int kxPre, int kyPre, int kfPre);
ConnectionProbe(const char * filename, int kPre);
ConnectionProbe(const char * filename,int kxPre, int kyPre, int kfPre);
virtual ~ConnectionProbe();
virtual int outputState(float time, HyPerConn * c);
static int text_write_patch(FILE * fd, PVPatch * patch, float * data);
static int write_patch_indices(FILE * fp, PVPatch * patch,
const PVLayerLoc * loc, int kx0, int ky0, int kf0);
void setOutputIndices(bool flag) {outputIndices = flag;}
void setStdpVars(bool flag) {stdpVars = flag;}
protected:
FILE * fp;
int kPre; // index of pre-synaptic neuron
int kxPre, kyPre, kfPre;
bool outputIndices;
bool stdpVars;
};
} // namespace PV
#endif /* CONNECTIONPROBE_HPP_ */
<|endoftext|> |
<commit_before>/*
* Copyright 2010 MQWeb - Franky Braem
*
* Licensed under the EUPL, Version 1.1 or – as soon they
* will be approved by the European Commission - subsequent
* versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the
* Licence.
* You may obtain a copy of the Licence at:
*
* http://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the Licence is
* distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the Licence for the specific language governing
* permissions and limitations under the Licence.
*/
#include <string.h> // For memcpy
#include <Poco/DateTimeParser.h>
#include <cmqc.h>
#include <MQ/PCF.h>
namespace MQ
{
PCF::PCF(bool zos)
: Message()
, _zos(zos)
{
}
PCF::PCF(int cmd, bool zos)
: Message()
, _zos(zos)
{
setFormat(MQFMT_ADMIN);
setType(MQMT_REQUEST);
setPersistence(MQPER_NOT_PERSISTENT);
buffer().resize(MQCFH_STRUC_LENGTH);
MQCFH* header = (MQCFH*)(MQBYTE*) &buffer()[0];
header->StrucLength = MQCFH_STRUC_LENGTH;
if ( _zos )
{
header->Type = MQCFT_COMMAND_XR;
header->Version = MQCFH_VERSION_3;
}
else
{
header->Type = (MQLONG) MQCFT_COMMAND;
header->Version = MQCFH_VERSION_1;
}
header->Command = cmd;
header->MsgSeqNumber = MQCFC_LAST;
header->Control = MQCFC_LAST;
header->ParameterCount = 0;
}
PCF::~PCF()
{
}
void PCF::init()
{
MQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);
int pos = MQCFH_STRUC_LENGTH;
for(int i = 0; i < header->ParameterCount; i++)
{
MQLONG *pcfType = (MQLONG*) &buffer()[pos];
_pointers[pcfType[2]] = pos;
pos += pcfType[1];
}
}
std::string PCF::getParameterString(MQLONG parameter) const
{
MQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);
std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
if ( it == _pointers.end() )
throw Poco::NotFoundException(parameter);
MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
if ( *pcfType == MQCFT_STRING || *pcfType == MQCFT_BYTE_STRING )
{
MQCFST* pcfParam = (MQCFST*) &buffer()[it->second];
std::string result(pcfParam->String, pcfParam->StringLength);
result.erase(result.find_last_not_of(" \n\r\t")+1); // trim
return result;
}
throw Poco::BadCastException(parameter);
}
std::string PCF::optParameterString(MQLONG parameter, const std::string& def) const
{
std::string result = def;
try
{
result = getParameterString(parameter);
}
catch(...)
{
}
return result;
}
Poco::DateTime PCF::getParameterDate(MQLONG dateParameter, MQLONG timeParameter) const
{
std::string dateValue = getParameterString(dateParameter);
dateValue.erase(dateValue.find_last_not_of(" \n\r\t")+1); // trim
std::string timeValue = getParameterString(timeParameter);
timeValue.erase(timeValue.find_last_not_of(" \n\r\t")+1); // trim
dateValue += timeValue;
if ( ! dateValue.empty() )
{
Poco::DateTime dateTime;
int timeZone;
Poco::DateTimeParser::parse("%Y%n%e%H%M%S", dateValue, dateTime, timeZone);
return dateTime;
}
return Poco::DateTime();
}
MQLONG PCF::getParameterNum(MQLONG parameter) const
{
std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
if ( it == _pointers.end() )
throw Poco::NotFoundException(parameter);
MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
if ( *pcfType == MQCFT_INTEGER )
{
MQCFIN* pcfParam = (MQCFIN*) &buffer()[it->second];
return pcfParam->Value;
}
throw Poco::BadCastException(parameter);
}
std::vector<std::string> PCF::getParameterStringList(MQLONG parameter) const
{
std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
if ( it == _pointers.end() )
throw Poco::NotFoundException(parameter);
MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
if ( *pcfType == MQCFT_STRING_LIST )
{
std::vector<std::string> list;
MQCFSL* pcfParam = (MQCFSL*) &buffer()[it->second];
for(int i = 0; i < pcfParam->Count; ++i)
{
std::string result(pcfParam->Strings, i * pcfParam->StringLength, pcfParam->StringLength);
result.erase(result.find_last_not_of(" \n\r\t")+1); // trim
list.push_back(result);
}
return list;
}
throw Poco::BadCastException(parameter);
}
MQLONG PCF::optParameterNum(MQLONG parameter, MQLONG def) const
{
MQLONG result = def;
try
{
result = getParameterNum(parameter);
}
catch(...)
{
}
return result;
}
void PCF::addParameter(MQLONG parameter, const std::string& value)
{
MQLONG structLength = ((MQCFST_STRUC_LENGTH_FIXED + value.length()) / 4 + 1) * 4;
_pointers[parameter] = buffer().size();
buffer().resize(buffer().size() + structLength);
MQCFST* pcfParam = (MQCFST*) &buffer()[_pointers[parameter]];
pcfParam->Type = MQCFT_STRING;
pcfParam->StrucLength = structLength;
pcfParam->Parameter = parameter;
pcfParam->CodedCharSetId = MQCCSI_DEFAULT;
pcfParam->StringLength = value.length();
memcpy(pcfParam->String, value.c_str(), pcfParam->StringLength);
MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
header->ParameterCount++;
}
void PCF::addParameter(MQLONG parameter, MQLONG value)
{
_pointers[parameter] = buffer().size();
buffer().resize(buffer().size() + MQCFIN_STRUC_LENGTH);
MQCFIN* pcfParam = (MQCFIN*) &buffer()[_pointers[parameter]];
pcfParam->Type = MQCFT_INTEGER;
pcfParam->StrucLength = MQCFIN_STRUC_LENGTH;
pcfParam->Parameter = parameter;
pcfParam->Value = value;
MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
header->ParameterCount++;
}
void PCF::addParameterList(MQLONG parameter, MQLONG *values)
{
int count = (sizeof values / sizeof values[0]);
int strucLength = MQCFIL_STRUC_LENGTH_FIXED + count * 4;
_pointers[parameter] = buffer().size();
buffer().resize(buffer().size() + strucLength);
MQCFIL *pcfIntegerList = (MQCFIL *) &buffer()[_pointers[parameter]];
pcfIntegerList->Count = count;
pcfIntegerList->Type = MQCFT_INTEGER_LIST;
pcfIntegerList->StrucLength = strucLength;
pcfIntegerList->Parameter = parameter;
pcfIntegerList->Values[0] = *values;
MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
header->ParameterCount++;
}
void PCF::addFilter(MQLONG parameter, MQLONG op, const std::string& value)
{
MQLONG strucLength = ((MQCFSF_STRUC_LENGTH_FIXED + value.length()) / 4 + 1) * 4;
_pointers[parameter] = buffer().size();
buffer().resize(buffer().size() + strucLength);
MQCFSF* pcfFilter = (MQCFSF*) &buffer()[_pointers[parameter]];
pcfFilter->Type = MQCFT_STRING_FILTER;
pcfFilter->StrucLength = strucLength;
pcfFilter->Parameter = parameter;
pcfFilter->Operator = op;
pcfFilter->CodedCharSetId = MQCCSI_DEFAULT;
pcfFilter->FilterValueLength = value.length();
memcpy(pcfFilter->FilterValue, value.c_str(), pcfFilter->FilterValueLength);
MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
header->ParameterCount++;
}
void PCF::addFilter(MQLONG parameter, MQLONG op, MQLONG value)
{
_pointers[parameter] = buffer().size();
buffer().resize(buffer().size() + MQCFIF_STRUC_LENGTH);
MQCFIF* pcfFilter = (MQCFIF*) &buffer()[_pointers[parameter]];
pcfFilter->Type = MQCFT_INTEGER_FILTER;
pcfFilter->StrucLength = MQCFIF_STRUC_LENGTH;
pcfFilter->Parameter = parameter;
pcfFilter->Operator = op;
pcfFilter->FilterValue = value;
MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
header->ParameterCount++;
}
std::vector<MQLONG> PCF::getParameters() const
{
std::vector<MQLONG> parameters;
for(std::map<MQLONG, int>::const_iterator it = _pointers.begin(); it != _pointers.end(); it++)
{
MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
parameters.push_back(pcfType[2]);
}
return parameters;
}
} // Namespace MQ
<commit_msg>Use Poco's trim functions<commit_after>/*
* Copyright 2010 MQWeb - Franky Braem
*
* Licensed under the EUPL, Version 1.1 or – as soon they
* will be approved by the European Commission - subsequent
* versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the
* Licence.
* You may obtain a copy of the Licence at:
*
* http://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the Licence is
* distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the Licence for the specific language governing
* permissions and limitations under the Licence.
*/
#include <string.h> // For memcpy
#include <Poco/DateTimeParser.h>
#include <cmqc.h>
#include <MQ/PCF.h>
namespace MQ
{
PCF::PCF(bool zos)
: Message()
, _zos(zos)
{
}
PCF::PCF(int cmd, bool zos)
: Message()
, _zos(zos)
{
setFormat(MQFMT_ADMIN);
setType(MQMT_REQUEST);
setPersistence(MQPER_NOT_PERSISTENT);
buffer().resize(MQCFH_STRUC_LENGTH);
MQCFH* header = (MQCFH*)(MQBYTE*) &buffer()[0];
header->StrucLength = MQCFH_STRUC_LENGTH;
if ( _zos )
{
header->Type = MQCFT_COMMAND_XR;
header->Version = MQCFH_VERSION_3;
}
else
{
header->Type = (MQLONG) MQCFT_COMMAND;
header->Version = MQCFH_VERSION_1;
}
header->Command = cmd;
header->MsgSeqNumber = MQCFC_LAST;
header->Control = MQCFC_LAST;
header->ParameterCount = 0;
}
PCF::~PCF()
{
}
void PCF::init()
{
MQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);
int pos = MQCFH_STRUC_LENGTH;
for(int i = 0; i < header->ParameterCount; i++)
{
MQLONG *pcfType = (MQLONG*) &buffer()[pos];
_pointers[pcfType[2]] = pos;
pos += pcfType[1];
}
}
std::string PCF::getParameterString(MQLONG parameter) const
{
MQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);
std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
if ( it == _pointers.end() )
throw Poco::NotFoundException(parameter);
MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
if ( *pcfType == MQCFT_STRING || *pcfType == MQCFT_BYTE_STRING )
{
MQCFST* pcfParam = (MQCFST*) &buffer()[it->second];
std::string result(pcfParam->String, pcfParam->StringLength);
return Poco::trimRightInPlace(result);
}
throw Poco::BadCastException(parameter);
}
std::string PCF::optParameterString(MQLONG parameter, const std::string& def) const
{
std::string result = def;
try
{
result = getParameterString(parameter);
}
catch(...)
{
}
return result;
}
Poco::DateTime PCF::getParameterDate(MQLONG dateParameter, MQLONG timeParameter) const
{
std::string dateValue = getParameterString(dateParameter);
Poco::trimRightInPlace(dateValue);
std::string timeValue = getParameterString(timeParameter);
Poco::trimRightInPlace(timeValue);
dateValue += timeValue;
if ( ! dateValue.empty() )
{
Poco::DateTime dateTime;
int timeZone;
Poco::DateTimeParser::parse("%Y%n%e%H%M%S", dateValue, dateTime, timeZone);
return dateTime;
}
return Poco::DateTime();
}
MQLONG PCF::getParameterNum(MQLONG parameter) const
{
std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
if ( it == _pointers.end() )
throw Poco::NotFoundException(parameter);
MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
if ( *pcfType == MQCFT_INTEGER )
{
MQCFIN* pcfParam = (MQCFIN*) &buffer()[it->second];
return pcfParam->Value;
}
throw Poco::BadCastException(parameter);
}
std::vector<std::string> PCF::getParameterStringList(MQLONG parameter) const
{
std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
if ( it == _pointers.end() )
throw Poco::NotFoundException(parameter);
MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
if ( *pcfType == MQCFT_STRING_LIST )
{
std::vector<std::string> list;
MQCFSL* pcfParam = (MQCFSL*) &buffer()[it->second];
for(int i = 0; i < pcfParam->Count; ++i)
{
std::string result(pcfParam->Strings, i * pcfParam->StringLength, pcfParam->StringLength);
Poco::trimRightInPlace(result);
list.push_back(result);
}
return list;
}
throw Poco::BadCastException(parameter);
}
MQLONG PCF::optParameterNum(MQLONG parameter, MQLONG def) const
{
MQLONG result = def;
try
{
result = getParameterNum(parameter);
}
catch(...)
{
}
return result;
}
void PCF::addParameter(MQLONG parameter, const std::string& value)
{
MQLONG structLength = ((MQCFST_STRUC_LENGTH_FIXED + value.length()) / 4 + 1) * 4;
_pointers[parameter] = buffer().size();
buffer().resize(buffer().size() + structLength);
MQCFST* pcfParam = (MQCFST*) &buffer()[_pointers[parameter]];
pcfParam->Type = MQCFT_STRING;
pcfParam->StrucLength = structLength;
pcfParam->Parameter = parameter;
pcfParam->CodedCharSetId = MQCCSI_DEFAULT;
pcfParam->StringLength = value.length();
memcpy(pcfParam->String, value.c_str(), pcfParam->StringLength);
MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
header->ParameterCount++;
}
void PCF::addParameter(MQLONG parameter, MQLONG value)
{
_pointers[parameter] = buffer().size();
buffer().resize(buffer().size() + MQCFIN_STRUC_LENGTH);
MQCFIN* pcfParam = (MQCFIN*) &buffer()[_pointers[parameter]];
pcfParam->Type = MQCFT_INTEGER;
pcfParam->StrucLength = MQCFIN_STRUC_LENGTH;
pcfParam->Parameter = parameter;
pcfParam->Value = value;
MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
header->ParameterCount++;
}
void PCF::addParameterList(MQLONG parameter, MQLONG *values)
{
int count = (sizeof values / sizeof values[0]);
int strucLength = MQCFIL_STRUC_LENGTH_FIXED + count * 4;
_pointers[parameter] = buffer().size();
buffer().resize(buffer().size() + strucLength);
MQCFIL *pcfIntegerList = (MQCFIL *) &buffer()[_pointers[parameter]];
pcfIntegerList->Count = count;
pcfIntegerList->Type = MQCFT_INTEGER_LIST;
pcfIntegerList->StrucLength = strucLength;
pcfIntegerList->Parameter = parameter;
pcfIntegerList->Values[0] = *values;
MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
header->ParameterCount++;
}
void PCF::addFilter(MQLONG parameter, MQLONG op, const std::string& value)
{
MQLONG strucLength = ((MQCFSF_STRUC_LENGTH_FIXED + value.length()) / 4 + 1) * 4;
_pointers[parameter] = buffer().size();
buffer().resize(buffer().size() + strucLength);
MQCFSF* pcfFilter = (MQCFSF*) &buffer()[_pointers[parameter]];
pcfFilter->Type = MQCFT_STRING_FILTER;
pcfFilter->StrucLength = strucLength;
pcfFilter->Parameter = parameter;
pcfFilter->Operator = op;
pcfFilter->CodedCharSetId = MQCCSI_DEFAULT;
pcfFilter->FilterValueLength = value.length();
memcpy(pcfFilter->FilterValue, value.c_str(), pcfFilter->FilterValueLength);
MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
header->ParameterCount++;
}
void PCF::addFilter(MQLONG parameter, MQLONG op, MQLONG value)
{
_pointers[parameter] = buffer().size();
buffer().resize(buffer().size() + MQCFIF_STRUC_LENGTH);
MQCFIF* pcfFilter = (MQCFIF*) &buffer()[_pointers[parameter]];
pcfFilter->Type = MQCFT_INTEGER_FILTER;
pcfFilter->StrucLength = MQCFIF_STRUC_LENGTH;
pcfFilter->Parameter = parameter;
pcfFilter->Operator = op;
pcfFilter->FilterValue = value;
MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
header->ParameterCount++;
}
std::vector<MQLONG> PCF::getParameters() const
{
std::vector<MQLONG> parameters;
for(std::map<MQLONG, int>::const_iterator it = _pointers.begin(); it != _pointers.end(); it++)
{
MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
parameters.push_back(pcfType[2]);
}
return parameters;
}
} // Namespace MQ
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
How to test SSL connections on Win32
-------------------------------------
On the server:
1) create the keystore:
%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA
2) In $CATALINA_HOME/conf/server.xml uncomment the lines:
<Connector className="org.apache.catalina.connector.http.HttpConnector"
port="8443" minProcessors="5" maxProcessors="75"
enableLookups="true"
acceptCount="10" debug="0" scheme="https" secure="true">
<Factory className="org.apache.catalina.net.SSLServerSocketFactory" clientAuth="false" protocol="TLS"/>
</Connector>
2) Export the certificate from the key store:
%JAVA_HOME%\bin\keytool -export -alias tomcat -file myroot.cer
On the client:
1) Connect (via https) to the server using a web-browser (type "https://<server_address>:8443)
2) Accept and install the certificate sent from the server
**/
#include "base/Log.h"
#include "base/messages.h"
#include "base/util/utils.h"
#include "http/constants.h"
#include "http/errors.h"
#include "http/Win32TransportAgent.h"
#include "event/FireEvent.h"
#define ENTERING(func) // LOG.debug("Entering %ls", func);
#define EXITING(func) // LOG.debug("Exiting %ls", func);
/*
* Constructor.
* In this implementation newProxy is ignored, since proxy configuration
* is taken from the WinInet subsystem.
*
* @param url the url where messages will be sent with sendMessage()
* @param proxy proxy information or NULL if no proxy should be used
*/
Win32TransportAgent::Win32TransportAgent(URL& newURL, Proxy& newProxy,
unsigned int maxResponseTimeout,
unsigned int maxmsgsize) : TransportAgent(){
url = newURL;
proxy.setProxy(newProxy);
if (maxResponseTimeout == 0) {
setTimeout(DEFAULT_MAX_TIMEOUT);
} else {
setTimeout(maxResponseTimeout);
}
}
Win32TransportAgent::~Win32TransportAgent(){}
/*
* Sends the given SyncML message to the server specified
* by the instal property 'url'. Returns the response status code or -1
* if it was not possible initialize the connection.
*
*/
char* Win32TransportAgent::sendMessage(const char* msg) {
ENTERING(L"TransportAgent::sendMessage");
if (!msg) {
sprintf(lastErrorMsg, "TransportAgent::sendMessage error: NULL message.");
goto exit;
}
HINTERNET inet = NULL,
connection = NULL,
request = NULL;
char bufferA[5000+1];
int status = -1;
unsigned int contentLength = 0;
WCHAR* wurlHost;
WCHAR* wurlResource;
char* response = NULL;
char* p = NULL;
DWORD size = 0,
read = 0,
flags = INTERNET_FLAG_RELOAD |
INTERNET_FLAG_NO_CACHE_WRITE |
INTERNET_FLAG_KEEP_CONNECTION | // This is necessary if authentication is required.
INTERNET_FLAG_NO_COOKIES; // This is used to avoid possible server errors on successive sessions.
LPCWSTR acceptTypes[2] = {TEXT("*/*"), NULL};
// Set flags for secure connection (https).
if (url.isSecure()) {
flags = flags
| INTERNET_FLAG_SECURE
| INTERNET_FLAG_IGNORE_CERT_CN_INVALID
| INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
;
}
//
// Open Internet connection.
//
WCHAR* ua = toWideChar(userAgent);
inet = InternetOpen (ua, INTERNET_OPEN_TYPE_PRECONFIG, NULL, 0, 0);
if (ua) {delete [] ua; ua = NULL; }
if (!inet) {
lastErrorCode = ERR_NETWORK_INIT;
DWORD code = GetLastError();
char* tmp = createHttpErrorMessage(code);
sprintf (lastErrorMsg, "InternetOpen Error: %d - %s", code, tmp);
delete [] tmp;
goto exit;
}
LOG.debug("Connecting to %s:%d", url.host, url.port);
//
// Open an HTTP session for a specified site by using lpszServer.
//
wurlHost = toWideChar(url.host);
if (!(connection = InternetConnect (inet,
wurlHost,
url.port,
NULL, // username
NULL, // password
INTERNET_SERVICE_HTTP,
0,
0))) {
lastErrorCode = ERR_CONNECT;
DWORD code = GetLastError();
char* tmp = createHttpErrorMessage(code);
sprintf (lastErrorMsg, "InternetConnect Error: %d - %s", code, tmp);
delete [] tmp;
goto exit;
}
LOG.debug("Requesting resource %s", url.resource);
//
// Open an HTTP request handle.
//
wurlResource = toWideChar(url.resource);
if (!(request = HttpOpenRequest (connection,
METHOD_POST,
wurlResource,
HTTP_VERSION,
NULL,
acceptTypes,
flags, 0))) {
lastErrorCode = ERR_CONNECT;
DWORD code = GetLastError();
char* tmp = createHttpErrorMessage(code);
sprintf (lastErrorMsg, "HttpOpenRequest Error: %d - %s", code, tmp);
delete [] tmp;
goto exit;
}
//
// Prepares headers
//
WCHAR headers[512];
contentLength = strlen(msg);
wsprintf(headers, TEXT("Content-Type: %s\r\nContent-Length: %d"), SYNCML_CONTENT_TYPE, contentLength);
//
// Try 5 times to send http request: used to retry sending request in case
// of authentication (proxy/server).
//
for (int i=0;; i++) {
// Fire Send Data Begin Transport Event
fireTransportEvent(contentLength, SEND_DATA_BEGIN);
// Send a request to the HTTP server.
if (!HttpSendRequest (request, headers, wcslen(headers), (void*)msg, contentLength)) {
DWORD code = GetLastError();
if (code == ERROR_INTERNET_CONNECTION_RESET) {
// Fire Send Data Begin Transport Event
fireTransportEvent(contentLength, SEND_DATA_BEGIN);
// Retry: some proxy need to resend the http request.
if (!HttpSendRequest (request, headers, wcslen(headers), (void*)msg, contentLength)) {
lastErrorCode = ERR_CONNECT;
char* tmp = createHttpErrorMessage(code);
sprintf (lastErrorMsg, "HttpSendRequest Error: %d - %s", code, tmp);
delete [] tmp;
goto exit;
}
}
// This is another type of error (e.g. cannot find server) -> exit
else {
lastErrorCode = ERR_CONNECT;
char* tmp = createHttpErrorMessage(code);
sprintf (lastErrorMsg, "HttpSendRequest Error: %d - %s", code, tmp);
delete [] tmp;
goto exit;
}
}
LOG.debug(MESSAGE_SENT);
// Fire Send Data End Transport Event
fireTransportEvent(contentLength, SEND_DATA_END);
// Check the status code.
size = sizeof(status);
HttpQueryInfo (request,
HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
(LPDWORD)&status,
(LPDWORD)&size,
NULL);
//
// OK (200) -> OUT
//
if (status == HTTP_STATUS_OK) {
break;
}
//
// 5th error -> OUT
//
if (i == MAX_AUTH_ATTEMPT) {
LOG.error("HTTP Authentication failed: bad username or password.");
break;
}
//
// Proxy Authentication Required (407) / Server Authentication Required (401).
// Need to set username/password.
//
else if(status == HTTP_STATUS_PROXY_AUTH_REQ ||
status == HTTP_STATUS_DENIED) {
LOG.debug("HTTP Authentication required.");
DWORD dwError;
// Automatic authentication (user/pass stored in win reg key).
if (strcmp(proxy.user, "") && strcmp(proxy.password, "")) {
WCHAR* wUser = toWideChar(proxy.user);
WCHAR* wPwd = toWideChar(proxy.password);
InternetSetOption(request, INTERNET_OPTION_PROXY_USERNAME, wUser, wcslen(wUser)+1);
InternetSetOption(request, INTERNET_OPTION_PROXY_PASSWORD, wPwd, wcslen(wPwd)+1);
delete [] wUser;
delete [] wPwd;
dwError = ERROR_INTERNET_FORCE_RETRY;
}
// Prompt dialog box.
else {
dwError = InternetErrorDlg(GetDesktopWindow(), request, NULL,
FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS |
FLAGS_ERROR_UI_FLAGS_GENERATE_DATA,
NULL);
}
if (dwError == ERROR_INTERNET_FORCE_RETRY) {
continue;
}
else {
LOG.error("HTTP Authentication failed.");
break;
}
}
//
// Other HTTP errors -> OUT
//
else {
break;
}
}
// If wrong status, exit immediately.
if (status != HTTP_STATUS_OK) {
lastErrorCode = ERR_HTTP;
sprintf(lastErrorMsg, "HTTP request error: %d", status);
LOG.error("%s", lastErrorMsg);
goto exit;
}
HttpQueryInfo (request,
HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
(LPDWORD)&contentLength,
(LPDWORD)&size,
NULL);
// ====================== Reading Response ==============================
LOG.debug(READING_RESPONSE);
LOG.debug("Content-length: %d", contentLength);
if (contentLength <= 0) {
lastErrorCode = ERR_READING_CONTENT;
sprintf(lastErrorMsg, "Invalid content-length: %d", contentLength);
LOG.error(lastErrorMsg);
goto exit;
}
// Fire Data Received Transport Event
fireTransportEvent(contentLength, RECEIVE_DATA_BEGIN);
// Allocate a block of memory for lpHeadersW.
response = new char[contentLength+1];
p = response;
(*p) = 0;
do {
if (!InternetReadFile (request, (LPVOID)bufferA, 5000, &read)) {
DWORD code = GetLastError();
lastErrorCode = ERR_READING_CONTENT;
char* tmp = createHttpErrorMessage(code);
sprintf(lastErrorMsg, "InternetReadFile Error: %d - %s", code, tmp);
delete [] tmp;
goto exit;
}
// Sanity check: some proxy could send additional bytes...
if ( (strlen(response) + read) > contentLength) {
// Correct 'read' value to be sure we won't overflow the 'rensponse' buffer.
read = contentLength - strlen(response);
}
if (read > 0) {
bufferA[read] = 0;
strcpy(p, bufferA); // here copy also the last '0' byte -> strlen(rensponse) make sense.
p += strlen(bufferA);
// Fire Data Received Transport Event
fireTransportEvent(read, DATA_RECEIVED);
}
} while (read);
// Fire Receive Data End Transport Event
fireTransportEvent(contentLength, RECEIVE_DATA_END);
LOG.debug("Response read");
LOG.debug("%s", response);
exit:
// Close the Internet handles.
if (inet) {
InternetCloseHandle (inet);
}
if (connection) {
InternetCloseHandle (connection);
}
if (request) {
InternetCloseHandle (request);
}
if ((status != STATUS_OK) && (response !=NULL)) {
delete [] response; response = NULL;
}
EXITING(L"TransportAgent::sendMessage");
return response;
}
// Utility function to retrieve the correspondant message for the Wininet error code passed.
// Pointer returned is allocated new, must be freed by caller.
char* Win32TransportAgent::createHttpErrorMessage(DWORD errorCode) {
char* errorMessage = new char[512];
FormatMessageA(
FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandleA("wininet.dll"),
errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT),
errorMessage,
512,
NULL);
return errorMessage;
}
<commit_msg>added safe check on error message formatted from system / safe check on invalid host.<commit_after>/*
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
How to test SSL connections on Win32
-------------------------------------
On the server:
1) create the keystore:
%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA
2) In $CATALINA_HOME/conf/server.xml uncomment the lines:
<Connector className="org.apache.catalina.connector.http.HttpConnector"
port="8443" minProcessors="5" maxProcessors="75"
enableLookups="true"
acceptCount="10" debug="0" scheme="https" secure="true">
<Factory className="org.apache.catalina.net.SSLServerSocketFactory" clientAuth="false" protocol="TLS"/>
</Connector>
2) Export the certificate from the key store:
%JAVA_HOME%\bin\keytool -export -alias tomcat -file myroot.cer
On the client:
1) Connect (via https) to the server using a web-browser (type "https://<server_address>:8443)
2) Accept and install the certificate sent from the server
**/
#include "base/Log.h"
#include "base/messages.h"
#include "base/util/utils.h"
#include "http/constants.h"
#include "http/errors.h"
#include "http/Win32TransportAgent.h"
#include "event/FireEvent.h"
#define ENTERING(func) // LOG.debug("Entering %ls", func);
#define EXITING(func) // LOG.debug("Exiting %ls", func);
/*
* Constructor.
* In this implementation newProxy is ignored, since proxy configuration
* is taken from the WinInet subsystem.
*
* @param url the url where messages will be sent with sendMessage()
* @param proxy proxy information or NULL if no proxy should be used
*/
Win32TransportAgent::Win32TransportAgent(URL& newURL, Proxy& newProxy,
unsigned int maxResponseTimeout,
unsigned int maxmsgsize) : TransportAgent(){
url = newURL;
proxy.setProxy(newProxy);
if (maxResponseTimeout == 0) {
setTimeout(DEFAULT_MAX_TIMEOUT);
} else {
setTimeout(maxResponseTimeout);
}
}
Win32TransportAgent::~Win32TransportAgent(){}
/*
* Sends the given SyncML message to the server specified
* by the instal property 'url'. Returns the response status code or -1
* if it was not possible initialize the connection.
*
*/
char* Win32TransportAgent::sendMessage(const char* msg) {
ENTERING(L"TransportAgent::sendMessage");
char bufferA[5000+1];
int status = -1;
unsigned int contentLength = 0;
WCHAR* wurlHost;
WCHAR* wurlResource;
char* response = NULL;
char* p = NULL;
HINTERNET inet = NULL,
connection = NULL,
request = NULL;
// Check sending msg and host.
if (!msg) {
lastErrorCode = ERR_NETWORK_INIT;
sprintf(lastErrorMsg, "TransportAgent::sendMessage error: NULL message.");
goto exit;
}
if (!(url.host) || strlen(url.host) == 0) {
lastErrorCode = ERR_HOST_NOT_FOUND;
sprintf(lastErrorMsg, "TransportAgent::sendMessage error: %s.", ERRMSG_HOST_NOT_FOUND);
goto exit;
}
DWORD size = 0,
read = 0,
flags = INTERNET_FLAG_RELOAD |
INTERNET_FLAG_NO_CACHE_WRITE |
INTERNET_FLAG_KEEP_CONNECTION | // This is necessary if authentication is required.
INTERNET_FLAG_NO_COOKIES; // This is used to avoid possible server errors on successive sessions.
LPCWSTR acceptTypes[2] = {TEXT("*/*"), NULL};
// Set flags for secure connection (https).
if (url.isSecure()) {
flags = flags
| INTERNET_FLAG_SECURE
| INTERNET_FLAG_IGNORE_CERT_CN_INVALID
| INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
;
}
//
// Open Internet connection.
//
WCHAR* ua = toWideChar(userAgent);
inet = InternetOpen (ua, INTERNET_OPEN_TYPE_PRECONFIG, NULL, 0, 0);
if (ua) {delete [] ua; ua = NULL; }
if (!inet) {
lastErrorCode = ERR_NETWORK_INIT;
DWORD code = GetLastError();
char* tmp = createHttpErrorMessage(code);
sprintf (lastErrorMsg, "InternetOpen Error: %d - %s", code, tmp);
delete [] tmp;
goto exit;
}
LOG.debug("Connecting to %s:%d", url.host, url.port);
//
// Open an HTTP session for a specified site by using lpszServer.
//
wurlHost = toWideChar(url.host);
if (!(connection = InternetConnect (inet,
wurlHost,
url.port,
NULL, // username
NULL, // password
INTERNET_SERVICE_HTTP,
0,
0))) {
lastErrorCode = ERR_CONNECT;
DWORD code = GetLastError();
char* tmp = createHttpErrorMessage(code);
sprintf (lastErrorMsg, "InternetConnect Error: %d - %s", code, tmp);
delete [] tmp;
goto exit;
}
LOG.debug("Requesting resource %s", url.resource);
//
// Open an HTTP request handle.
//
wurlResource = toWideChar(url.resource);
if (!(request = HttpOpenRequest (connection,
METHOD_POST,
wurlResource,
HTTP_VERSION,
NULL,
acceptTypes,
flags, 0))) {
lastErrorCode = ERR_CONNECT;
DWORD code = GetLastError();
char* tmp = createHttpErrorMessage(code);
sprintf (lastErrorMsg, "HttpOpenRequest Error: %d - %s", code, tmp);
delete [] tmp;
goto exit;
}
//
// Prepares headers
//
WCHAR headers[512];
contentLength = strlen(msg);
wsprintf(headers, TEXT("Content-Type: %s\r\nContent-Length: %d"), SYNCML_CONTENT_TYPE, contentLength);
//
// Try 5 times to send http request: used to retry sending request in case
// of authentication (proxy/server).
//
for (int i=0;; i++) {
// Fire Send Data Begin Transport Event
fireTransportEvent(contentLength, SEND_DATA_BEGIN);
// Send a request to the HTTP server.
if (!HttpSendRequest (request, headers, wcslen(headers), (void*)msg, contentLength)) {
DWORD code = GetLastError();
if (code == ERROR_INTERNET_CONNECTION_RESET) {
// Fire Send Data Begin Transport Event
fireTransportEvent(contentLength, SEND_DATA_BEGIN);
// Retry: some proxy need to resend the http request.
if (!HttpSendRequest (request, headers, wcslen(headers), (void*)msg, contentLength)) {
lastErrorCode = ERR_CONNECT;
char* tmp = createHttpErrorMessage(code);
sprintf (lastErrorMsg, "HttpSendRequest Error: %d - %s", code, tmp);
delete [] tmp;
goto exit;
}
}
// This is another type of error (e.g. cannot find server) -> exit
else {
lastErrorCode = ERR_CONNECT;
char* tmp = createHttpErrorMessage(code);
sprintf (lastErrorMsg, "HttpSendRequest Error: %d - %s", code, tmp);
delete [] tmp;
goto exit;
}
}
LOG.debug(MESSAGE_SENT);
// Fire Send Data End Transport Event
fireTransportEvent(contentLength, SEND_DATA_END);
// Check the status code.
size = sizeof(status);
HttpQueryInfo (request,
HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
(LPDWORD)&status,
(LPDWORD)&size,
NULL);
//
// OK (200) -> OUT
//
if (status == HTTP_STATUS_OK) {
break;
}
//
// 5th error -> OUT
//
if (i == MAX_AUTH_ATTEMPT) {
LOG.error("HTTP Authentication failed: bad username or password.");
break;
}
//
// Proxy Authentication Required (407) / Server Authentication Required (401).
// Need to set username/password.
//
else if(status == HTTP_STATUS_PROXY_AUTH_REQ ||
status == HTTP_STATUS_DENIED) {
LOG.debug("HTTP Authentication required.");
DWORD dwError;
// Automatic authentication (user/pass stored in win reg key).
if (strcmp(proxy.user, "") && strcmp(proxy.password, "")) {
WCHAR* wUser = toWideChar(proxy.user);
WCHAR* wPwd = toWideChar(proxy.password);
InternetSetOption(request, INTERNET_OPTION_PROXY_USERNAME, wUser, wcslen(wUser)+1);
InternetSetOption(request, INTERNET_OPTION_PROXY_PASSWORD, wPwd, wcslen(wPwd)+1);
delete [] wUser;
delete [] wPwd;
dwError = ERROR_INTERNET_FORCE_RETRY;
}
// Prompt dialog box.
else {
dwError = InternetErrorDlg(GetDesktopWindow(), request, NULL,
FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS |
FLAGS_ERROR_UI_FLAGS_GENERATE_DATA,
NULL);
}
if (dwError == ERROR_INTERNET_FORCE_RETRY) {
continue;
}
else {
LOG.error("HTTP Authentication failed.");
break;
}
}
//
// Other HTTP errors -> OUT
//
else {
break;
}
}
// If wrong status, exit immediately.
if (status != HTTP_STATUS_OK) {
lastErrorCode = ERR_HTTP;
sprintf(lastErrorMsg, "HTTP request error: %d", status);
LOG.error("%s", lastErrorMsg);
goto exit;
}
HttpQueryInfo (request,
HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
(LPDWORD)&contentLength,
(LPDWORD)&size,
NULL);
// ====================== Reading Response ==============================
LOG.debug(READING_RESPONSE);
LOG.debug("Content-length: %d", contentLength);
if (contentLength <= 0) {
lastErrorCode = ERR_READING_CONTENT;
sprintf(lastErrorMsg, "Invalid content-length: %d", contentLength);
LOG.error(lastErrorMsg);
goto exit;
}
// Fire Data Received Transport Event
fireTransportEvent(contentLength, RECEIVE_DATA_BEGIN);
// Allocate a block of memory for lpHeadersW.
response = new char[contentLength+1];
p = response;
(*p) = 0;
do {
if (!InternetReadFile (request, (LPVOID)bufferA, 5000, &read)) {
DWORD code = GetLastError();
lastErrorCode = ERR_READING_CONTENT;
char* tmp = createHttpErrorMessage(code);
sprintf(lastErrorMsg, "InternetReadFile Error: %d - %s", code, tmp);
delete [] tmp;
goto exit;
}
// Sanity check: some proxy could send additional bytes...
if ( (strlen(response) + read) > contentLength) {
// Correct 'read' value to be sure we won't overflow the 'rensponse' buffer.
read = contentLength - strlen(response);
}
if (read > 0) {
bufferA[read] = 0;
strcpy(p, bufferA); // here copy also the last '0' byte -> strlen(rensponse) make sense.
p += strlen(bufferA);
// Fire Data Received Transport Event
fireTransportEvent(read, DATA_RECEIVED);
}
} while (read);
// Fire Receive Data End Transport Event
fireTransportEvent(contentLength, RECEIVE_DATA_END);
LOG.debug("Response read");
LOG.debug("%s", response);
exit:
// Close the Internet handles.
if (inet) {
InternetCloseHandle (inet);
}
if (connection) {
InternetCloseHandle (connection);
}
if (request) {
InternetCloseHandle (request);
}
if ((status != STATUS_OK) && (response !=NULL)) {
delete [] response; response = NULL;
}
EXITING(L"TransportAgent::sendMessage");
return response;
}
// Utility function to retrieve the correspondant message for the Wininet error code passed.
// Pointer returned is allocated new, must be freed by caller.
char* Win32TransportAgent::createHttpErrorMessage(DWORD errorCode) {
char* errorMessage = new char[512];
memset(errorMessage, 0, 512);
FormatMessageA(
FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandleA("wininet.dll"),
errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT),
errorMessage,
512,
NULL);
if (!errorMessage || strlen(errorMessage) == 0) {
sprintf(errorMessage, "Unknown error.");
}
return errorMessage;
}
<|endoftext|> |
<commit_before>// IBM_PROLOG_BEGIN_TAG
// This is an automatically generated prolog.
//
// $Source: src/usr/testcore/lib/synctest.H $
//
// IBM CONFIDENTIAL
//
// COPYRIGHT International Business Machines Corp. 2011
//
// p1
//
// Object Code Only (OCO) source materials
// Licensed Internal Code Source Materials
// IBM HostBoot Licensed Internal Code
//
// The source code for this program is not published or other-
// wise divested of its trade secrets, irrespective of what has
// been deposited with the U.S. Copyright Office.
//
// Origin: 30
//
// IBM_PROLOG_END
#ifndef __SYNCTEST_H
#define __SYNCTEST_H
/**
* @file synctest.H
*
* @brief Test cases for the sycronization
*/
#include <cxxtest/TestSuite.H>
#include <sys/sync.h>
#include <sys/task.h>
#include <sys/time.h>
#include <utility>
#include <kernel/timemgr.H>
#include <kernel/console.H>
class SyncTest: public CxxTest::TestSuite
{
public:
void testMutex()
{
mutex_init(&mutex);
barrier_init(&barrier, 7);
task_create(func1, this);
task_create(func2, this);
task_create(func2, this);
task_create(func2, this);
task_create(func2, this);
task_create(func2, this);
barrier_wait(&barrier);
TS_TRACE("ALL THREADS ENDED");
}
void testMutexDoubleWait()
{
mutex_init(&mutex);
barrier_init(&barrier, 3);
mutex_lock(&mutex);
task_create(func2, this);
task_create(func2, this);
nanosleep(0,TEN_CTX_SWITCHES_NS);
mutex_unlock(&mutex);
barrier_wait(&barrier);
TS_TRACE("ALL THREADS ENDED");
}
void testBarrier()
{
barrier_t barrier;
barrier_init(&barrier,3);
task_create(func3,&barrier);
task_create(func4,&barrier);
barrier_wait(&barrier);
TS_TRACE("B0");
barrier_destroy(&barrier);
}
void testConditionVariable()
{
mutex_init(&mutex);
sync_cond_init(&cond_var);
counter = 0;
barrier_init(&barrier,4);
TASK_INFO t1(this,1);
TASK_INFO t2(this,2);
TASK_INFO t3(this,3);
task_create(watch_counter, &t1);
task_create(increment, &t2);
task_create(increment, &t3);
barrier_wait(&barrier);
TS_TRACE("Conditional Variable test final count = %ld",counter);
barrier_destroy(&barrier);
sync_cond_destroy(&cond_var);
mutex_destroy(&mutex);
// test is success if it completes w/o hang
}
void testConditionVariableBroadcast()
{
mutex_init(&mutex);
sync_cond_init(&cond_var);
counter = 0;
barrier_init(&barrier,5);
TASK_INFO t1(this,4);
TASK_INFO t2(this,5);
TASK_INFO t3(this,6);
TASK_INFO t4(this,7);
task_create(watch_counter, &t1);
task_create(watch_counter, &t2);
task_create(increment1, &t3);
task_create(increment1, &t4);
barrier_wait(&barrier);
TS_TRACE("Conditional Variable test final count = %ld",counter);
barrier_destroy(&barrier);
sync_cond_destroy(&cond_var);
mutex_destroy(&mutex);
// test is success if it completes w/o hang
}
private:
enum
{
TO_COUNT = 10,
COUNT_SIGNAL = 13
};
typedef std::pair<SyncTest*, size_t> TASK_INFO;
mutex_t mutex;
barrier_t barrier;
sync_cond_t cond_var;
size_t counter;
static void func1(void * i_p)
{
SyncTest * my = (SyncTest *) i_p;
mutex_t * mutex = &(my->mutex);
barrier_t * barrier = &(my->barrier);
mutex_lock(mutex);
nanosleep(0,TEN_CTX_SWITCHES_NS);
TS_TRACE("ME FIRST");
mutex_unlock(mutex);
barrier_wait(barrier);
task_end();
}
static void func2(void * i_p)
{
SyncTest * my = (SyncTest *) i_p;
mutex_t * mutex = &(my->mutex);
barrier_t * barrier = &(my->barrier);
mutex_lock(mutex);
TS_TRACE("ME NEXT");
mutex_unlock(mutex);
barrier_wait(barrier);
task_end();
}
static void func3(void * i_p)
{
barrier_t * barrier = (barrier_t *) i_p;
barrier_wait(barrier);
TS_TRACE("B1");
task_end();
}
static void func4(void * i_p)
{
barrier_t * barrier = (barrier_t *) i_p;
barrier_wait(barrier);
TS_TRACE("B2");
task_end();
}
static void watch_counter(void * i_p)
{
TASK_INFO * info = (TASK_INFO *) i_p;
SyncTest * my = info->first;
TS_TRACE("CONDVAR task %ld. Start watching counter",info->second);
mutex_lock(&(my->mutex));
while(my->counter < COUNT_SIGNAL)
{
sync_cond_wait(&(my->cond_var),&(my->mutex));
TS_TRACE("CONDVAR task %ld. Condition signal received",
info->second);
my->counter += 100;
TS_TRACE("CONDVAR task %ld. Counter = %ld",
info->second,my->counter);
}
mutex_unlock(&(my->mutex));
barrier_wait(&(my->barrier));
}
static void increment(void * i_p)
{
TASK_INFO * info = (TASK_INFO *) i_p;
SyncTest * my = info->first;
TS_TRACE("CONDVAR task %ld. start Increment counter",info->second);
for(size_t i = 0; i < TO_COUNT; ++i)
{
mutex_lock(&(my->mutex));
++(my->counter);
if(my->counter == COUNT_SIGNAL)
{
sync_cond_signal(&(my->cond_var));
TS_TRACE("CONDVAR task %ld. INCR counter = %ld Threshold"
" reached",info->second,my->counter);
}
TS_TRACE("CONDVAR task %ld INCR counter = %ld Unlocking mutex",
info->second, my->counter);
mutex_unlock(&(my->mutex));
nanosleep(0,TEN_CTX_SWITCHES_NS);
}
barrier_wait(&(my->barrier));
}
static void increment1(void * i_p)
{
TASK_INFO * info = (TASK_INFO *) i_p;
SyncTest * my = info->first;
TS_TRACE("CONDVAR task %ld. start Increment counter",info->second);
for(size_t i = 0; i < TO_COUNT; ++i)
{
mutex_lock(&(my->mutex));
++(my->counter);
if(my->counter == COUNT_SIGNAL)
{
sync_cond_broadcast(&(my->cond_var));
TS_TRACE("CONDVAR task %ld. INCR counter = %ld Threshold"
" reached",info->second,my->counter);
}
TS_TRACE("CONDVAR task %ld INCR counter = %ld Unlocking mutex",
info->second, my->counter);
mutex_unlock(&(my->mutex));
nanosleep(0,TEN_CTX_SWITCHES_NS);
}
barrier_wait(&(my->barrier));
}
};
#endif
<commit_msg>Fix deadlock in synctest.H<commit_after>// IBM_PROLOG_BEGIN_TAG
// This is an automatically generated prolog.
//
// $Source: src/usr/testcore/lib/synctest.H $
//
// IBM CONFIDENTIAL
//
// COPYRIGHT International Business Machines Corp. 2011
//
// p1
//
// Object Code Only (OCO) source materials
// Licensed Internal Code Source Materials
// IBM HostBoot Licensed Internal Code
//
// The source code for this program is not published or other-
// wise divested of its trade secrets, irrespective of what has
// been deposited with the U.S. Copyright Office.
//
// Origin: 30
//
// IBM_PROLOG_END
#ifndef __SYNCTEST_H
#define __SYNCTEST_H
/**
* @file synctest.H
*
* @brief Test cases for the sycronization
*/
#include <cxxtest/TestSuite.H>
#include <sys/sync.h>
#include <sys/task.h>
#include <sys/time.h>
#include <utility>
#include <kernel/timemgr.H>
#include <kernel/console.H>
class SyncTest: public CxxTest::TestSuite
{
public:
void testMutex()
{
mutex_init(&mutex);
barrier_init(&barrier, 7);
task_create(func1, this);
task_create(func2, this);
task_create(func2, this);
task_create(func2, this);
task_create(func2, this);
task_create(func2, this);
barrier_wait(&barrier);
TS_TRACE("ALL THREADS ENDED");
}
void testMutexDoubleWait()
{
mutex_init(&mutex);
barrier_init(&barrier, 3);
mutex_lock(&mutex);
task_create(func2, this);
task_create(func2, this);
nanosleep(0,TEN_CTX_SWITCHES_NS);
mutex_unlock(&mutex);
barrier_wait(&barrier);
TS_TRACE("ALL THREADS ENDED");
}
void testBarrier()
{
barrier_t barrier;
barrier_init(&barrier,3);
task_create(func3,&barrier);
task_create(func4,&barrier);
barrier_wait(&barrier);
TS_TRACE("B0");
barrier_destroy(&barrier);
}
void testConditionVariable()
{
mutex_init(&mutex);
sync_cond_init(&cond_var);
counter = 0;
barrier_init(&barrier,4);
TASK_INFO t1 = { this, 1, 0};
TASK_INFO t2 = { this, 2, 0};
TASK_INFO t3 = { this, 3, 0};
t1.tid = task_create(watch_counter, &t1);
t2.tid = task_create(increment, &t2);
t3.tid = task_create(increment, &t3);
barrier_wait(&barrier);
TS_TRACE("Conditional Variable test final count = %ld",counter);
task_wait_tid(t1.tid, NULL, NULL);
task_wait_tid(t2.tid, NULL, NULL);
task_wait_tid(t3.tid, NULL, NULL);
barrier_destroy(&barrier);
sync_cond_destroy(&cond_var);
mutex_destroy(&mutex);
// test is success if it completes w/o hang
}
void testConditionVariableBroadcast()
{
mutex_init(&mutex);
sync_cond_init(&cond_var);
counter = 0;
barrier_init(&barrier,5);
TASK_INFO t1 = { this, 4, 0};
TASK_INFO t2 = { this, 5, 0};
TASK_INFO t3 = { this, 6, 0};
TASK_INFO t4 = { this, 7, 0};
t1.tid = task_create(watch_counter, &t1);
t2.tid = task_create(watch_counter, &t2);
t3.tid = task_create(increment1, &t3);
t4.tid = task_create(increment1, &t4);
barrier_wait(&barrier);
TS_TRACE("Conditional Variable test final count = %ld",counter);
task_wait_tid(t1.tid, NULL, NULL);
task_wait_tid(t2.tid, NULL, NULL);
task_wait_tid(t3.tid, NULL, NULL);
task_wait_tid(t4.tid, NULL, NULL);
barrier_destroy(&barrier);
sync_cond_destroy(&cond_var);
mutex_destroy(&mutex);
// test is success if it completes w/o hang
}
private:
enum
{
TO_COUNT = 10,
COUNT_SIGNAL = 13
};
struct TASK_INFO { SyncTest* testobj; size_t id; tid_t tid; };
mutex_t mutex;
barrier_t barrier;
sync_cond_t cond_var;
size_t counter;
static void func1(void * i_p)
{
SyncTest * my = (SyncTest *) i_p;
mutex_t * mutex = &(my->mutex);
barrier_t * barrier = &(my->barrier);
mutex_lock(mutex);
nanosleep(0,TEN_CTX_SWITCHES_NS);
TS_TRACE("ME FIRST");
mutex_unlock(mutex);
barrier_wait(barrier);
task_end();
}
static void func2(void * i_p)
{
SyncTest * my = (SyncTest *) i_p;
mutex_t * mutex = &(my->mutex);
barrier_t * barrier = &(my->barrier);
mutex_lock(mutex);
TS_TRACE("ME NEXT");
mutex_unlock(mutex);
barrier_wait(barrier);
task_end();
}
static void func3(void * i_p)
{
barrier_t * barrier = (barrier_t *) i_p;
barrier_wait(barrier);
TS_TRACE("B1");
task_end();
}
static void func4(void * i_p)
{
barrier_t * barrier = (barrier_t *) i_p;
barrier_wait(barrier);
TS_TRACE("B2");
task_end();
}
static void watch_counter(void * i_p)
{
TASK_INFO * info = (TASK_INFO *) i_p;
SyncTest * my = info->testobj;
TS_TRACE("CONDVAR task %ld. Start watching counter",info->id);
mutex_lock(&(my->mutex));
while(my->counter < COUNT_SIGNAL)
{
sync_cond_wait(&(my->cond_var),&(my->mutex));
TS_TRACE("CONDVAR task %ld. Condition signal received",
info->id);
my->counter += 100;
TS_TRACE("CONDVAR task %ld. Counter = %ld",
info->id,my->counter);
}
mutex_unlock(&(my->mutex));
barrier_wait(&(my->barrier));
}
static void increment(void * i_p)
{
TASK_INFO * info = (TASK_INFO *) i_p;
SyncTest * my = info->testobj;
TS_TRACE("CONDVAR task %ld. start Increment counter",info->id);
for(size_t i = 0; i < TO_COUNT; ++i)
{
mutex_lock(&(my->mutex));
++(my->counter);
if(my->counter == COUNT_SIGNAL)
{
sync_cond_signal(&(my->cond_var));
TS_TRACE("CONDVAR task %ld. INCR counter = %ld Threshold"
" reached",info->id,my->counter);
}
TS_TRACE("CONDVAR task %ld INCR counter = %ld Unlocking mutex",
info->id, my->counter);
mutex_unlock(&(my->mutex));
nanosleep(0,TEN_CTX_SWITCHES_NS);
}
barrier_wait(&(my->barrier));
}
static void increment1(void * i_p)
{
TASK_INFO * info = (TASK_INFO *) i_p;
SyncTest * my = info->testobj;
TS_TRACE("CONDVAR task %ld. start Increment counter",info->id);
for(size_t i = 0; i < TO_COUNT; ++i)
{
mutex_lock(&(my->mutex));
++(my->counter);
if(my->counter == COUNT_SIGNAL)
{
sync_cond_broadcast(&(my->cond_var));
TS_TRACE("CONDVAR task %ld. INCR counter = %ld Threshold"
" reached",info->id,my->counter);
}
TS_TRACE("CONDVAR task %ld INCR counter = %ld Unlocking mutex",
info->id, my->counter);
mutex_unlock(&(my->mutex));
nanosleep(0,TEN_CTX_SWITCHES_NS);
}
barrier_wait(&(my->barrier));
}
};
#endif
<|endoftext|> |
<commit_before><commit_msg>WM_CHAR - CP_THREAD_ACP used instead of CP_ACP<commit_after><|endoftext|> |
<commit_before>#include "King.h"
#include "Rook.h"
#include "Board.h"
namespace Chess {
King::King(const Position& position, bool white) : Piece(position, white) {
_hasMoved = false;
}
void King::move(const Position& newPosition) {
position = newPosition;
_hasMoved = true;
}
bool King::hasMoved()const{
return _hasMoved;
}
bool King::isChecked(const Board& board) const {
if (board.getState() == GameState::WHITEPLAYS && isWhite() || board.getState() == GameState::BLACKPLAYS && !isWhite()){
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
Position tempPos;
tempPos.x = i;
tempPos.y = j;
Piece *tempPiece = board.getPiece(tempPos);
if (tempPiece != nullptr && (isWhite() != tempPiece->isWhite()) && !(tempPiece->notation() == 'k') && (tempPiece->notation() == 'K')){
std::vector<Position> moves = tempPiece->legalMoves(board);
for (Position move : moves){
if (move == position){
return true;
}
}
}
}
}
}
return false;
}
char King::notation() const {
return isWhite() ? 'K' : 'k';
}
std::vector<Position> King::legalMoves(const Board& board) const{
std::vector<Position> validPosition;
Position tempPosition;
for (int i = 0; i < 3; i++) {
tempPosition.x = this->position.x - 1 + i;
for (int j = 0; j < 3; j++) {
tempPosition.y = this->position.y - 1 + j;
if (tempPosition.valid() &&
( ( board.getPiece(tempPosition) == nullptr ) || (board.getPiece(tempPosition)->isWhite() != this->isWhite()) ) )
validPosition.push_back(tempPosition);
}
}
//Check for valid castling
if (!_hasMoved && !isChecked(board)){
Rook* leftRook = dynamic_cast<Rook *>(board.getPiece(Position(0, position.y)));
Rook* rightRook = dynamic_cast<Rook *>(board.getPiece(Position(7, position.y)));
bool leftCastling = true;
bool rightCastling = true;
King castlingKing = King(position,isWhite());
for (int l = -1; l < 2; l += 2){
if (board.getPiece(Position(position.x + 1 * l, position.y)) == nullptr
&& board.getPiece(Position(position.x + 2 * l, position.y)) == nullptr){
for (int k = 1; k < 3; k++){
Position tempPosition = position;
tempPosition.x += k*l;
castlingKing.position = tempPosition;
if (l == -1){
if (board.getPiece(Position(position.x + 3 * l, position.y)) != nullptr || leftRook->hasMoved() || castlingKing.isChecked(board)){
leftCastling = false;
}
}
else if (l == 1){
if (rightRook == nullptr || rightRook->hasMoved() || castlingKing.isChecked(board)){
rightCastling = false;
}
}
}
}
else{
if (l == 1){
rightCastling = false;
}
else if (l == -1){
leftCastling = false;
}
}
}
if (leftCastling){
validPosition.push_back(Position(position.x - 2, position.y));
}
if (rightCastling){
validPosition.push_back(Position(position.x + 2, position.y));
}
}
return validPosition;
}
}<commit_msg>Simplify King::isChecked<commit_after>#include "King.h"
#include "Rook.h"
#include "Board.h"
namespace Chess {
King::King(const Position& position, bool white) : Piece(position, white) {
_hasMoved = false;
}
void King::move(const Position& newPosition) {
position = newPosition;
_hasMoved = true;
}
bool King::hasMoved() const {
return _hasMoved;
}
bool King::isChecked(const Board& board) const {
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
Piece *piece = board.getPiece(Position(i, j));
if (piece != nullptr && isWhite() != piece->isWhite()) {
std::vector<Position> moves = piece->legalMoves(board);
for (Position move : moves) {
if (move == position)
return true;
}
}
}
}
return false;
}
char King::notation() const {
return isWhite() ? 'K' : 'k';
}
std::vector<Position> King::legalMoves(const Board& board) const {
std::vector<Position> validPosition;
Position tempPosition;
for (int i = 0; i < 3; i++) {
tempPosition.x = this->position.x - 1 + i;
for (int j = 0; j < 3; j++) {
tempPosition.y = this->position.y - 1 + j;
if (tempPosition.valid() &&
( ( board.getPiece(tempPosition) == nullptr ) || (board.getPiece(tempPosition)->isWhite() != this->isWhite()) ) )
validPosition.push_back(tempPosition);
}
}
// Check for valid castling
if (!_hasMoved && !isChecked(board)) {
Rook* leftRook = dynamic_cast<Rook *>(board.getPiece(Position(0, position.y)));
Rook* rightRook = dynamic_cast<Rook *>(board.getPiece(Position(7, position.y)));
bool leftCastling = true;
bool rightCastling = true;
King castlingKing = King(position,isWhite());
for (int l = -1; l < 2; l += 2) {
if (board.getPiece(Position(position.x + 1 * l, position.y)) == nullptr
&& board.getPiece(Position(position.x + 2 * l, position.y)) == nullptr) {
for (int k = 1; k < 3; k++) {
Position tempPosition = position;
tempPosition.x += k*l;
castlingKing.position = tempPosition;
if (l == -1) {
if (board.getPiece(Position(position.x + 3 * l, position.y)) != nullptr || leftRook->hasMoved() || castlingKing.isChecked(board)) {
leftCastling = false;
}
} else if (l == 1) {
if (rightRook == nullptr || rightRook->hasMoved() || castlingKing.isChecked(board)) {
rightCastling = false;
}
}
}
} else {
if (l == 1) {
rightCastling = false;
} else if (l == -1) {
leftCastling = false;
}
}
}
if (leftCastling){
validPosition.push_back(Position(position.x - 2, position.y));
}
if (rightCastling){
validPosition.push_back(Position(position.x + 2, position.y));
}
}
return validPosition;
}
}<|endoftext|> |
<commit_before>#include "Halide.h"
using namespace Halide;
#include <iostream>
#include <limits>
#include "benchmark.h"
#include "halide_image_io.h"
using namespace Halide::Tools;
using std::vector;
int main(int argc, char **argv) {
if (argc < 3) {
std::cerr << "Usage:\n\t./interpolate in.png out.png\n" << std::endl;
return 1;
}
ImageParam input(Float(32), 3);
const int levels = 10;
Func downsampled[levels];
Func downx[levels];
Func interpolated[levels];
Func upsampled[levels];
Func upsampledx[levels];
Var x("x"), y("y"), c("c");
Func clamped = BoundaryConditions::repeat_edge(input);
// This triggers a bug in llvm 3.3 (3.2 and trunk are fine), so we
// rewrite it in a way that doesn't trigger the bug. The rewritten
// form assumes the input alpha is zero or one.
// downsampled[0](x, y, c) = select(c < 3, clamped(x, y, c) * clamped(x, y, 3), clamped(x, y, 3));
downsampled[0](x, y, c) = clamped(x, y, c) * clamped(x, y, 3);
for (int l = 1; l < levels; ++l) {
Func prev = downsampled[l-1];
if (l == 4) {
// Also add a boundary condition at a middle pyramid level
// to prevent the footprint of the downsamplings to extend
// too far off the base image. Otherwise we look 512
// pixels off each edge.
Expr w = input.width()/(1 << l);
Expr h = input.height()/(1 << l);
prev = lambda(x, y, c, prev(clamp(x, 0, w), clamp(y, 0, h), c));
}
downx[l](x, y, c) = (prev(x*2-1, y, c) +
2.0f * prev(x*2, y, c) +
prev(x*2+1, y, c)) * 0.25f;
downsampled[l](x, y, c) = (downx[l](x, y*2-1, c) +
2.0f * downx[l](x, y*2, c) +
downx[l](x, y*2+1, c)) * 0.25f;
}
interpolated[levels-1](x, y, c) = downsampled[levels-1](x, y, c);
for (int l = levels-2; l >= 0; --l) {
upsampledx[l](x, y, c) = (interpolated[l+1](x/2, y, c) +
interpolated[l+1]((x+1)/2, y, c)) / 2.0f;
upsampled[l](x, y, c) = (upsampledx[l](x, y/2, c) +
upsampledx[l](x, (y+1)/2, c)) / 2.0f;
interpolated[l](x, y, c) = downsampled[l](x, y, c) + (1.0f - downsampled[l](x, y, 3)) * upsampled[l](x, y, c);
}
Func normalize("normalize");
normalize(x, y, c) = interpolated[0](x, y, c) / interpolated[0](x, y, 3);
Func final("final");
final(x, y, c) = normalize(x, y, c);
std::cout << "Finished function setup." << std::endl;
int sched;
Target target = get_target_from_environment();
if (target.has_gpu_feature()) {
sched = 4;
} else {
sched = 2;
}
switch (sched) {
case 0:
{
std::cout << "Flat schedule." << std::endl;
for (int l = 0; l < levels; ++l) {
downsampled[l].compute_root();
interpolated[l].compute_root();
}
final.compute_root();
break;
}
case 1:
{
std::cout << "Flat schedule with vectorization." << std::endl;
for (int l = 0; l < levels; ++l) {
downsampled[l].compute_root().vectorize(x,4);
interpolated[l].compute_root().vectorize(x,4);
}
final.compute_root();
break;
}
case 2:
{
Var xi, yi;
std::cout << "Flat schedule with parallelization + vectorization." << std::endl;
for (int l = 1; l < levels-1; ++l) {
if (l > 0) downsampled[l].compute_root().parallel(y).reorder(c, x, y).reorder_storage(c, x, y).vectorize(c, 4);
interpolated[l].compute_root().parallel(y).reorder(c, x, y).reorder_storage(c, x, y).vectorize(c, 4);
interpolated[l].unroll(x, 2).unroll(y, 2);
}
final.reorder(c, x, y).bound(c, 0, 3).parallel(y);
final.tile(x, y, xi, yi, 2, 2).unroll(xi).unroll(yi);
final.bound(x, 0, input.width());
final.bound(y, 0, input.height());
break;
}
case 3:
{
std::cout << "Flat schedule with vectorization sometimes." << std::endl;
for (int l = 0; l < levels; ++l) {
if (l + 4 < levels) {
Var yo,yi;
downsampled[l].compute_root().vectorize(x,4);
interpolated[l].compute_root().vectorize(x,4);
} else {
downsampled[l].compute_root();
interpolated[l].compute_root();
}
}
final.compute_root();
break;
}
case 4:
{
std::cout << "GPU schedule." << std::endl;
// Some gpus don't have enough memory to process the entire
// image, so we process the image in tiles.
Var yo, yi, xo, xi;
final.reorder(c, x, y).bound(c, 0, 3).vectorize(x, 4);
final.tile(x, y, xo, yo, xi, yi, input.width()/8, input.height()/8);
normalize.compute_at(final, xo).reorder(c, x, y).gpu_tile(x, y, 16, 16, DeviceAPI::Default_GPU).unroll(c);
// Start from level 1 to save memory - level zero will be computed on demand
for (int l = 1; l < levels; ++l) {
int tile_size = 32 >> l;
if (tile_size < 1) tile_size = 1;
if (tile_size > 8) tile_size = 8;
downsampled[l].compute_root();
if (false) {
// Outer loop on CPU for the larger ones.
downsampled[l].tile(x, y, xo, yo, x, y, 256, 256);
}
downsampled[l].gpu_tile(x, y, c, tile_size, tile_size, 4, DeviceAPI::Default_GPU);
interpolated[l].compute_at(final, xo).gpu_tile(x, y, c, tile_size, tile_size, 4, DeviceAPI::Default_GPU);
}
break;
}
default:
assert(0 && "No schedule with this number.");
}
// JIT compile the pipeline eagerly, so we don't interfere with timing
final.compile_jit(target);
Image<float> in_png = load_image(argv[1]);
Image<float> out(in_png.width(), in_png.height(), 3);
assert(in_png.channels() == 4);
input.set(in_png);
std::cout << "Running... " << std::endl;
double best = benchmark(20, 1, [&]() { final.realize(out); });
std::cout << " took " << best * 1e3 << " msec." << std::endl;
vector<Argument> args;
args.push_back(input);
final.compile_to_assembly("test.s", args, target);
save_image(out, argv[2]);
}
<commit_msg>Clean up interpolate schedule<commit_after>#include "Halide.h"
using namespace Halide;
#include <iostream>
#include <limits>
#include "benchmark.h"
#include "halide_image_io.h"
using namespace Halide::Tools;
using std::vector;
int main(int argc, char **argv) {
if (argc < 3) {
std::cerr << "Usage:\n\t./interpolate in.png out.png\n" << std::endl;
return 1;
}
ImageParam input(Float(32), 3);
// Input must have four color channels - rgba
input.set_bounds(2, 0, 4);
const int levels = 10;
Func downsampled[levels];
Func downx[levels];
Func interpolated[levels];
Func upsampled[levels];
Func upsampledx[levels];
Var x("x"), y("y"), c("c");
Func clamped = BoundaryConditions::repeat_edge(input);
// This triggers a bug in llvm 3.3 (3.2 and trunk are fine), so we
// rewrite it in a way that doesn't trigger the bug. The rewritten
// form assumes the input alpha is zero or one.
// downsampled[0](x, y, c) = select(c < 3, clamped(x, y, c) * clamped(x, y, 3), clamped(x, y, 3));
downsampled[0](x, y, c) = clamped(x, y, c) * clamped(x, y, 3);
for (int l = 1; l < levels; ++l) {
Func prev = downsampled[l-1];
if (l == 4) {
// Also add a boundary condition at a middle pyramid level
// to prevent the footprint of the downsamplings to extend
// too far off the base image. Otherwise we look 512
// pixels off each edge.
Expr w = input.width()/(1 << l);
Expr h = input.height()/(1 << l);
prev = lambda(x, y, c, prev(clamp(x, 0, w), clamp(y, 0, h), c));
}
downx[l](x, y, c) = (prev(x*2-1, y, c) +
2.0f * prev(x*2, y, c) +
prev(x*2+1, y, c)) * 0.25f;
downsampled[l](x, y, c) = (downx[l](x, y*2-1, c) +
2.0f * downx[l](x, y*2, c) +
downx[l](x, y*2+1, c)) * 0.25f;
}
interpolated[levels-1](x, y, c) = downsampled[levels-1](x, y, c);
for (int l = levels-2; l >= 0; --l) {
upsampledx[l](x, y, c) = (interpolated[l+1](x/2, y, c) +
interpolated[l+1]((x+1)/2, y, c)) / 2.0f;
upsampled[l](x, y, c) = (upsampledx[l](x, y/2, c) +
upsampledx[l](x, (y+1)/2, c)) / 2.0f;
interpolated[l](x, y, c) = downsampled[l](x, y, c) + (1.0f - downsampled[l](x, y, 3)) * upsampled[l](x, y, c);
}
Func normalize("normalize");
normalize(x, y, c) = interpolated[0](x, y, c) / interpolated[0](x, y, 3);
Func final("final");
final(x, y, c) = normalize(x, y, c);
std::cout << "Finished function setup." << std::endl;
int sched;
Target target = get_target_from_environment();
if (target.has_gpu_feature()) {
sched = 4;
} else {
sched = 2;
}
switch (sched) {
case 0:
{
std::cout << "Flat schedule." << std::endl;
for (int l = 0; l < levels; ++l) {
downsampled[l].compute_root();
interpolated[l].compute_root();
}
final.compute_root();
break;
}
case 1:
{
std::cout << "Flat schedule with vectorization." << std::endl;
for (int l = 0; l < levels; ++l) {
downsampled[l].compute_root().vectorize(x,4);
interpolated[l].compute_root().vectorize(x,4);
}
final.compute_root();
break;
}
case 2:
{
Var xi, yi;
std::cout << "Flat schedule with parallelization + vectorization." << std::endl;
for (int l = 1; l < levels-1; ++l) {
downsampled[l]
.compute_root()
.parallel(y, 8)
.vectorize(x, 4);
interpolated[l]
.compute_root()
.parallel(y, 8)
.unroll(x, 2)
.unroll(y, 2)
.vectorize(x, 8);
}
final
.reorder(c, x, y)
.bound(c, 0, 3)
.unroll(c)
.tile(x, y, xi, yi, 2, 2)
.unroll(xi)
.unroll(yi)
.parallel(y, 8)
.vectorize(x, 8)
.bound(x, 0, input.width())
.bound(y, 0, input.height());
break;
}
case 3:
{
std::cout << "Flat schedule with vectorization sometimes." << std::endl;
for (int l = 0; l < levels; ++l) {
if (l + 4 < levels) {
Var yo,yi;
downsampled[l].compute_root().vectorize(x,4);
interpolated[l].compute_root().vectorize(x,4);
} else {
downsampled[l].compute_root();
interpolated[l].compute_root();
}
}
final.compute_root();
break;
}
case 4:
{
std::cout << "GPU schedule." << std::endl;
// Some gpus don't have enough memory to process the entire
// image, so we process the image in tiles.
Var yo, yi, xo, xi;
final.reorder(c, x, y).bound(c, 0, 3).vectorize(x, 4);
final.tile(x, y, xo, yo, xi, yi, input.width()/8, input.height()/8);
normalize.compute_at(final, xo).reorder(c, x, y).gpu_tile(x, y, 16, 16, DeviceAPI::Default_GPU).unroll(c);
// Start from level 1 to save memory - level zero will be computed on demand
for (int l = 1; l < levels; ++l) {
int tile_size = 32 >> l;
if (tile_size < 1) tile_size = 1;
if (tile_size > 8) tile_size = 8;
downsampled[l].compute_root();
if (false) {
// Outer loop on CPU for the larger ones.
downsampled[l].tile(x, y, xo, yo, x, y, 256, 256);
}
downsampled[l].gpu_tile(x, y, c, tile_size, tile_size, 4, DeviceAPI::Default_GPU);
interpolated[l].compute_at(final, xo).gpu_tile(x, y, c, tile_size, tile_size, 4, DeviceAPI::Default_GPU);
}
break;
}
default:
assert(0 && "No schedule with this number.");
}
// JIT compile the pipeline eagerly, so we don't interfere with timing
final.compile_jit(target);
Image<float> in_png = load_image(argv[1]);
Image<float> out(in_png.width(), in_png.height(), 3);
assert(in_png.channels() == 4);
input.set(in_png);
std::cout << "Running... " << std::endl;
double best = benchmark(20, 1, [&]() { final.realize(out); });
std::cout << " took " << best * 1e3 << " msec." << std::endl;
vector<Argument> args;
args.push_back(input);
final.compile_to_assembly("test.s", args, target);
save_image(out, argv[2]);
}
<|endoftext|> |
<commit_before>#include "pch.h"
#include "android_http_request.h"
#include <httpClient/httpClient.h>
#include <vector>
HttpRequest::HttpRequest(AsyncBlock* asyncBlock, JavaVM* javaVm, jobject applicationContext, jclass httpRequestClass, jclass httpResponseClass) :
m_httpRequestInstance(nullptr),
m_asyncBlock(asyncBlock),
m_javaVm(javaVm),
m_applicationContext(applicationContext),
m_httpRequestClass(httpRequestClass),
m_httpResponseClass(httpResponseClass)
{
assert(m_javaVm);
}
HttpRequest::~HttpRequest()
{
}
HRESULT HttpRequest::Initialize()
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (SUCCEEDED(result))
{
jmethodID networkAvailabilityFunc = jniEnv->GetStaticMethodID(m_httpRequestClass, "isNetworkAvailable", "(Landroid/content/Context;)Z");
if (networkAvailabilityFunc == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not find isNetworkAvailable static method");
return E_FAIL;
}
jboolean isNetworkAvailable = jniEnv->CallStaticBooleanMethod(m_httpRequestClass, networkAvailabilityFunc, m_applicationContext);
if (!isNetworkAvailable)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not initialize HttpRequest - no network available");
return E_HC_NO_NETWORK;
}
jmethodID httpRequestCtor = jniEnv->GetMethodID(m_httpRequestClass, "<init>", "()V");
if (httpRequestCtor == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not find HttpClientRequest constructor");
return E_FAIL;
}
m_httpRequestInstance = jniEnv->NewObject(m_httpRequestClass, httpRequestCtor);
return S_OK;
}
return result;
}
HRESULT HttpRequest::GetJniEnv(JNIEnv** jniEnv)
{
if (m_javaVm == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "javaVm is null");
return E_HC_NOT_INITIALISED;
}
jint jniResult = m_javaVm->GetEnv(reinterpret_cast<void**>(jniEnv), JNI_VERSION_1_6);
if (jniResult != JNI_OK)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not initialize HTTP request object, JavaVM is not attached to a java thread. %d", jniResult);
return E_FAIL;
}
return S_OK;
}
HRESULT HttpRequest::SetUrl(const char* url)
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (!SUCCEEDED(result))
{
return result;
}
jmethodID httpRequestSetUrlMethod = jniEnv->GetMethodID(m_httpRequestClass, "setHttpUrl", "(Ljava/lang/String;)V");
if (httpRequestSetUrlMethod == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not find HttpClientRequest.setHttpUrl");
return E_FAIL;
}
jstring urlJstr = jniEnv->NewStringUTF(url);
jniEnv->CallVoidMethod(m_httpRequestInstance, httpRequestSetUrlMethod, urlJstr);
jniEnv->DeleteLocalRef(urlJstr);
return S_OK;
}
HRESULT HttpRequest::AddHeader(const char* headerName, const char* headerValue)
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (!SUCCEEDED(result))
{
return result;
}
jmethodID httpRequestAddHeaderMethod = jniEnv->GetMethodID(m_httpRequestClass, "setHttpHeader", "(Ljava/lang/String;Ljava/lang/String;)V");
if (httpRequestAddHeaderMethod == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not find HttpClientRequest.setHttpHeader");
return E_FAIL;
}
jstring nameJstr = jniEnv->NewStringUTF(headerName);
jstring valueJstr = jniEnv->NewStringUTF(headerValue);
jniEnv->CallVoidMethod(m_httpRequestInstance, httpRequestAddHeaderMethod, nameJstr, valueJstr);
jniEnv->DeleteLocalRef(nameJstr);
jniEnv->DeleteLocalRef(valueJstr);
return S_OK;
}
HRESULT HttpRequest::SetMethodAndBody(const char* method, const char* contentType, const uint8_t* body, uint32_t bodySize)
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (!SUCCEEDED(result))
{
return result;
}
jmethodID httpRequestSetBody = jniEnv->GetMethodID(m_httpRequestClass, "setHttpMethodAndBody", "(Ljava/lang/String;Ljava/lang/String;[B)V");
if (httpRequestSetBody == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not find HttpClientRequest.setHttpMethodAndBody");
return E_FAIL;
}
jstring methodJstr = jniEnv->NewStringUTF(method);
jstring contentTypeJstr = jniEnv->NewStringUTF(contentType);
jbyteArray bodyArray = nullptr;
if (bodySize > 0)
{
bodyArray = jniEnv->NewByteArray(bodySize);
void *tempPrimitive = jniEnv->GetPrimitiveArrayCritical(bodyArray, 0);
memcpy(tempPrimitive, body, bodySize);
jniEnv->ReleasePrimitiveArrayCritical(bodyArray, tempPrimitive, 0);
}
jniEnv->CallVoidMethod(m_httpRequestInstance, httpRequestSetBody, methodJstr, contentTypeJstr, bodyArray);
jniEnv->DeleteLocalRef(methodJstr);
if (contentTypeJstr != nullptr)
{
jniEnv->DeleteLocalRef(contentTypeJstr);
}
return S_OK;
}
HRESULT HttpRequest::ExecuteAsync(hc_call_handle_t call)
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (SUCCEEDED(result))
{
jmethodID httpRequestExecuteAsyncMethod = jniEnv->GetMethodID(m_httpRequestClass, "doRequestAsync", "(J)V");
if (httpRequestExecuteAsyncMethod == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not find HttpClient.doRequestAsync");
return E_FAIL;
}
jniEnv->CallVoidMethod(m_httpRequestInstance, httpRequestExecuteAsyncMethod, reinterpret_cast<jlong>(call));
}
return result;
}
HRESULT HttpRequest::ProcessResponse(hc_call_handle_t call, jobject response)
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (!SUCCEEDED(result))
{
return result;
}
jmethodID httpResponseStatusMethod = jniEnv->GetMethodID(m_httpResponseClass, "getResponseCode", "()I");
jint responseStatus = jniEnv->CallIntMethod(response, httpResponseStatusMethod);
HCHttpCallResponseSetStatusCode(call, (uint32_t)responseStatus);
jmethodID httpRepsonseGetHeaderName = jniEnv->GetMethodID(m_httpResponseClass, "getHeaderNameAtIndex", "(I)Ljava/lang/String;");
jmethodID httpRepsonseGetHeaderValue = jniEnv->GetMethodID(m_httpResponseClass, "getHeaderValueAtIndex", "(I)Ljava/lang/String;");
for (uint32_t i = 0; i < GetResponseHeaderCount(response); i++)
{
jstring headerName = (jstring)jniEnv->CallObjectMethod(response, httpRepsonseGetHeaderName, i);
jstring headerValue = (jstring)jniEnv->CallObjectMethod(response, httpRepsonseGetHeaderValue, i);
const char* nameCstr = jniEnv->GetStringUTFChars(headerName, NULL);
const char* valueCstr = jniEnv->GetStringUTFChars(headerValue, NULL);
HCHttpCallResponseSetHeader(call, nameCstr, valueCstr);
jniEnv->ReleaseStringUTFChars(headerName, nameCstr);
jniEnv->ReleaseStringUTFChars(headerValue, valueCstr);
}
return ProcessResponseBody(call, response);
}
HRESULT HttpRequest::ProcessResponseBody(hc_call_handle_t call, jobject repsonse)
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (!SUCCEEDED(result))
{
return result;
}
jmethodID httpResponseBodyMethod = jniEnv->GetMethodID(m_httpResponseClass, "getResponseBodyBytes", "()[B");
if (httpResponseBodyMethod == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not find HttpClientRequest.getResponseBodyBytes");
return E_FAIL;
}
jbyteArray responseBody = (jbyteArray)jniEnv->CallObjectMethod(repsonse, httpResponseBodyMethod);
if (responseBody != nullptr)
{
int bodySize = jniEnv->GetArrayLength(responseBody);
if (bodySize > 0)
{
http_internal_vector<uint8_t> bodyBuffer(bodySize);
jniEnv->GetByteArrayRegion(responseBody, 0, bodySize, reinterpret_cast<jbyte*>(bodyBuffer.data()));
HCHttpCallResponseSetResponseBodyBytes(call, bodyBuffer.data(), bodyBuffer.size());
}
}
return S_OK;
}
uint32_t HttpRequest::GetResponseHeaderCount(jobject response)
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (!SUCCEEDED(result))
{
return result;
}
jmethodID httpResponssNumHeadersMethod = jniEnv->GetMethodID(m_httpResponseClass, "getNumHeaders", "()I");
jint numHeaders = jniEnv->CallIntMethod(response, httpResponssNumHeadersMethod);
return (uint32_t)numHeaders;
}
<commit_msg>Ensure local java resources are cleaned up when no longer used to prevent leaks (#261)<commit_after>#include "pch.h"
#include "android_http_request.h"
#include <httpClient/httpClient.h>
#include <vector>
HttpRequest::HttpRequest(AsyncBlock* asyncBlock, JavaVM* javaVm, jobject applicationContext, jclass httpRequestClass, jclass httpResponseClass) :
m_httpRequestInstance(nullptr),
m_asyncBlock(asyncBlock),
m_javaVm(javaVm),
m_applicationContext(applicationContext),
m_httpRequestClass(httpRequestClass),
m_httpResponseClass(httpResponseClass)
{
assert(m_javaVm);
}
HttpRequest::~HttpRequest()
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (SUCCEEDED(result) && m_httpRequestInstance != nullptr)
{
jniEnv->DeleteGlobalRef(m_httpRequestInstance);
m_httpRequestInstance = nullptr;
}
}
HRESULT HttpRequest::Initialize()
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (SUCCEEDED(result))
{
jmethodID networkAvailabilityFunc = jniEnv->GetStaticMethodID(m_httpRequestClass, "isNetworkAvailable", "(Landroid/content/Context;)Z");
if (networkAvailabilityFunc == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not find isNetworkAvailable static method");
return E_FAIL;
}
jboolean isNetworkAvailable = jniEnv->CallStaticBooleanMethod(m_httpRequestClass, networkAvailabilityFunc, m_applicationContext);
if (!isNetworkAvailable)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not initialize HttpRequest - no network available");
return E_HC_NO_NETWORK;
}
jmethodID httpRequestCtor = jniEnv->GetMethodID(m_httpRequestClass, "<init>", "()V");
if (httpRequestCtor == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not find HttpClientRequest constructor");
return E_FAIL;
}
jobject requestInstance = jniEnv->NewObject(m_httpRequestClass, httpRequestCtor);
m_httpRequestInstance = jniEnv->NewGlobalRef(requestInstance);
jniEnv->DeleteLocalRef(requestInstance);
return S_OK;
}
return result;
}
HRESULT HttpRequest::GetJniEnv(JNIEnv** jniEnv)
{
if (m_javaVm == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "javaVm is null");
return E_HC_NOT_INITIALISED;
}
jint jniResult = m_javaVm->GetEnv(reinterpret_cast<void**>(jniEnv), JNI_VERSION_1_6);
if (jniResult != JNI_OK)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not initialize HTTP request object, JavaVM is not attached to a java thread. %d", jniResult);
return E_FAIL;
}
return S_OK;
}
HRESULT HttpRequest::SetUrl(const char* url)
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (!SUCCEEDED(result))
{
return result;
}
jmethodID httpRequestSetUrlMethod = jniEnv->GetMethodID(m_httpRequestClass, "setHttpUrl", "(Ljava/lang/String;)V");
if (httpRequestSetUrlMethod == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not find HttpClientRequest.setHttpUrl");
return E_FAIL;
}
jstring urlJstr = jniEnv->NewStringUTF(url);
jniEnv->CallVoidMethod(m_httpRequestInstance, httpRequestSetUrlMethod, urlJstr);
jniEnv->DeleteLocalRef(urlJstr);
return S_OK;
}
HRESULT HttpRequest::AddHeader(const char* headerName, const char* headerValue)
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (!SUCCEEDED(result))
{
return result;
}
jmethodID httpRequestAddHeaderMethod = jniEnv->GetMethodID(m_httpRequestClass, "setHttpHeader", "(Ljava/lang/String;Ljava/lang/String;)V");
if (httpRequestAddHeaderMethod == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not find HttpClientRequest.setHttpHeader");
return E_FAIL;
}
jstring nameJstr = jniEnv->NewStringUTF(headerName);
jstring valueJstr = jniEnv->NewStringUTF(headerValue);
jniEnv->CallVoidMethod(m_httpRequestInstance, httpRequestAddHeaderMethod, nameJstr, valueJstr);
jniEnv->DeleteLocalRef(nameJstr);
jniEnv->DeleteLocalRef(valueJstr);
return S_OK;
}
HRESULT HttpRequest::SetMethodAndBody(const char* method, const char* contentType, const uint8_t* body, uint32_t bodySize)
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (!SUCCEEDED(result))
{
return result;
}
jmethodID httpRequestSetBody = jniEnv->GetMethodID(m_httpRequestClass, "setHttpMethodAndBody", "(Ljava/lang/String;Ljava/lang/String;[B)V");
if (httpRequestSetBody == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not find HttpClientRequest.setHttpMethodAndBody");
return E_FAIL;
}
jstring methodJstr = jniEnv->NewStringUTF(method);
jstring contentTypeJstr = jniEnv->NewStringUTF(contentType);
jbyteArray bodyArray = nullptr;
if (bodySize > 0)
{
bodyArray = jniEnv->NewByteArray(bodySize);
void *tempPrimitive = jniEnv->GetPrimitiveArrayCritical(bodyArray, 0);
memcpy(tempPrimitive, body, bodySize);
jniEnv->ReleasePrimitiveArrayCritical(bodyArray, tempPrimitive, 0);
}
jniEnv->CallVoidMethod(m_httpRequestInstance, httpRequestSetBody, methodJstr, contentTypeJstr, bodyArray);
jniEnv->DeleteLocalRef(methodJstr);
if (bodyArray != nullptr)
{
jniEnv->DeleteLocalRef(bodyArray);
}
if (contentTypeJstr != nullptr)
{
jniEnv->DeleteLocalRef(contentTypeJstr);
}
return S_OK;
}
HRESULT HttpRequest::ExecuteAsync(hc_call_handle_t call)
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (SUCCEEDED(result))
{
jmethodID httpRequestExecuteAsyncMethod = jniEnv->GetMethodID(m_httpRequestClass, "doRequestAsync", "(J)V");
if (httpRequestExecuteAsyncMethod == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not find HttpClient.doRequestAsync");
return E_FAIL;
}
jniEnv->CallVoidMethod(m_httpRequestInstance, httpRequestExecuteAsyncMethod, reinterpret_cast<jlong>(call));
}
return result;
}
HRESULT HttpRequest::ProcessResponse(hc_call_handle_t call, jobject response)
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (!SUCCEEDED(result))
{
return result;
}
jmethodID httpResponseStatusMethod = jniEnv->GetMethodID(m_httpResponseClass, "getResponseCode", "()I");
jint responseStatus = jniEnv->CallIntMethod(response, httpResponseStatusMethod);
HCHttpCallResponseSetStatusCode(call, (uint32_t)responseStatus);
jmethodID httpRepsonseGetHeaderName = jniEnv->GetMethodID(m_httpResponseClass, "getHeaderNameAtIndex", "(I)Ljava/lang/String;");
jmethodID httpRepsonseGetHeaderValue = jniEnv->GetMethodID(m_httpResponseClass, "getHeaderValueAtIndex", "(I)Ljava/lang/String;");
for (uint32_t i = 0; i < GetResponseHeaderCount(response); i++)
{
jstring headerName = (jstring)jniEnv->CallObjectMethod(response, httpRepsonseGetHeaderName, i);
jstring headerValue = (jstring)jniEnv->CallObjectMethod(response, httpRepsonseGetHeaderValue, i);
const char* nameCstr = jniEnv->GetStringUTFChars(headerName, NULL);
const char* valueCstr = jniEnv->GetStringUTFChars(headerValue, NULL);
HCHttpCallResponseSetHeader(call, nameCstr, valueCstr);
jniEnv->ReleaseStringUTFChars(headerName, nameCstr);
jniEnv->ReleaseStringUTFChars(headerValue, valueCstr);
}
return ProcessResponseBody(call, response);
}
HRESULT HttpRequest::ProcessResponseBody(hc_call_handle_t call, jobject repsonse)
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (!SUCCEEDED(result))
{
return result;
}
jmethodID httpResponseBodyMethod = jniEnv->GetMethodID(m_httpResponseClass, "getResponseBodyBytes", "()[B");
if (httpResponseBodyMethod == nullptr)
{
HC_TRACE_ERROR(HTTPCLIENT, "Could not find HttpClientRequest.getResponseBodyBytes");
return E_FAIL;
}
jbyteArray responseBody = (jbyteArray)jniEnv->CallObjectMethod(repsonse, httpResponseBodyMethod);
if (responseBody != nullptr)
{
int bodySize = jniEnv->GetArrayLength(responseBody);
if (bodySize > 0)
{
http_internal_vector<uint8_t> bodyBuffer(bodySize);
jniEnv->GetByteArrayRegion(responseBody, 0, bodySize, reinterpret_cast<jbyte*>(bodyBuffer.data()));
HCHttpCallResponseSetResponseBodyBytes(call, bodyBuffer.data(), bodyBuffer.size());
}
}
jniEnv->DeleteLocalRef(responseBody);
return S_OK;
}
uint32_t HttpRequest::GetResponseHeaderCount(jobject response)
{
JNIEnv* jniEnv = nullptr;
HRESULT result = GetJniEnv(&jniEnv);
if (!SUCCEEDED(result))
{
return result;
}
jmethodID httpResponssNumHeadersMethod = jniEnv->GetMethodID(m_httpResponseClass, "getNumHeaders", "()I");
jint numHeaders = jniEnv->CallIntMethod(response, httpResponssNumHeadersMethod);
return (uint32_t)numHeaders;
}
<|endoftext|> |
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2014 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <gtest/gtest.h>
#include <map>
#include "assoc_vector.hpp"
namespace jubatus {
namespace core {
namespace common {
TEST(assoc_vector, trivial) {
assoc_vector<int, int> m;
m[10] = 5;
m[4] = 2;
m[12] = 6;
m[10] = 4;
EXPECT_EQ(3u, m.size());
ASSERT_EQ(4, m[10]);
ASSERT_EQ(2, m[4]);
m.erase(4);
ASSERT_EQ(0u, m.count(4));
}
TEST(assoc_vector, replace) {
assoc_vector<int, int> m;
m[1] = -1;
m[1] = 3;
ASSERT_EQ(1u, m.size());
ASSERT_EQ(1u, m.count(1));
EXPECT_EQ(3, m[1]);
}
TEST(assoc_vector, pack) {
// Pack format of assoc_vector must to be same as std::map
assoc_vector<std::string, int> v;
v["saitama"] = 1;
msgpack::sbuffer buf;
msgpack::pack(buf, v);
msgpack::unpacked unpacked;
msgpack::unpack(&unpacked, buf.data(), buf.size());
msgpack::object obj = unpacked.get();
std::map<std::string, int> m;
m["saitama"] = 1;
obj.convert(&m);
ASSERT_EQ(1u, m.size());
ASSERT_EQ(1u, m.count("saitama"));
EXPECT_EQ(1, m["saitama"]);
}
TEST(assoc_vector, unpack) {
// Pack format of assoc_vector must to be same as std::map
std::map<std::string, int> m;
m["saitama"] = 1;
msgpack::sbuffer buf;
msgpack::pack(buf, m);
msgpack::unpacked unpacked;
msgpack::unpack(&unpacked, buf.data(), buf.size());
msgpack::object obj = unpacked.get();
assoc_vector<std::string, int> v;
obj.convert(&v);
ASSERT_EQ(1u, v.size());
ASSERT_EQ(1u, v.count("saitama"));
EXPECT_EQ(1, v["saitama"]);
}
} // namespace common
} // namespace core
} // namespace jubatus
<commit_msg>Add random test for assoc_vector<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2014 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <gtest/gtest.h>
#include <map>
#include "assoc_vector.hpp"
namespace jubatus {
namespace core {
namespace common {
TEST(assoc_vector, trivial) {
assoc_vector<int, int> m;
m[10] = 5;
m[4] = 2;
m[12] = 6;
m[10] = 4;
EXPECT_EQ(3u, m.size());
ASSERT_EQ(4, m[10]);
ASSERT_EQ(2, m[4]);
m.erase(4);
ASSERT_EQ(0u, m.count(4));
}
TEST(assoc_vector, replace) {
assoc_vector<int, int> m;
m[1] = -1;
m[1] = 3;
ASSERT_EQ(1u, m.size());
ASSERT_EQ(1u, m.count(1));
EXPECT_EQ(3, m[1]);
}
TEST(assoc_vector, random) {
std::map<int, int> map;
assoc_vector<int, int> vec;
srand(0);
for (int i = 0; i < 1000; ++i) {
int k = rand() % 1000 * (rand() % 2 == 0 ? 1 : -1);
int v = rand() % 1000 * (rand() % 2 == 0 ? 1 : -1);
map[k] = v;
vec[k] = v;
}
EXPECT_EQ(map.size(), vec.size());
for (std::map<int, int>::const_iterator it = map.begin();
it != map.end(); ++it) {
ASSERT_EQ(1u, vec.count(it->first));
EXPECT_EQ(it->second, vec[it->first]);
}
}
TEST(assoc_vector, pack) {
// Pack format of assoc_vector must to be same as std::map
assoc_vector<std::string, int> v;
v["saitama"] = 1;
msgpack::sbuffer buf;
msgpack::pack(buf, v);
msgpack::unpacked unpacked;
msgpack::unpack(&unpacked, buf.data(), buf.size());
msgpack::object obj = unpacked.get();
std::map<std::string, int> m;
m["saitama"] = 1;
obj.convert(&m);
ASSERT_EQ(1u, m.size());
ASSERT_EQ(1u, m.count("saitama"));
EXPECT_EQ(1, m["saitama"]);
}
TEST(assoc_vector, unpack) {
// Pack format of assoc_vector must to be same as std::map
std::map<std::string, int> m;
m["saitama"] = 1;
msgpack::sbuffer buf;
msgpack::pack(buf, m);
msgpack::unpacked unpacked;
msgpack::unpack(&unpacked, buf.data(), buf.size());
msgpack::object obj = unpacked.get();
assoc_vector<std::string, int> v;
obj.convert(&v);
ASSERT_EQ(1u, v.size());
ASSERT_EQ(1u, v.count("saitama"));
EXPECT_EQ(1, v["saitama"]);
}
} // namespace common
} // namespace core
} // namespace jubatus
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "CoreContextTest.h"
#include <set>
class Foo{};
class Bar{};
TEST_F(CoreContextTest, TestEnumerateChildren) {
// Create a few anonymous children:
AutoCreateContext child1;
AutoCreateContext child2;
AutoCreateContext child3;
// Enumerate and see what we get back:
std::set<std::shared_ptr<CoreContext>> allChildren;
m_create->EnumerateChildContexts(
[&allChildren](std::shared_ptr<CoreContext> ctxt){
allChildren.insert(ctxt);
}
);
// Verify we get exactly four back:
ASSERT_EQ(4UL, allChildren.size()) << "Failed to enumerate the correct number of child contexts";
// Verify full membership:
ASSERT_EQ(1UL, allChildren.count(m_create)) << "Failed to find the root context in the returned context collection";
const char* childMissing = "Failed to find a child context in the set of children";
ASSERT_EQ(1UL, allChildren.count(child1)) << childMissing;
ASSERT_EQ(1UL, allChildren.count(child2)) << childMissing;
ASSERT_EQ(1UL, allChildren.count(child3)) << childMissing;
//Check if filtering by sigil works
AutoCreateContextT<Foo> fooCtxt;
AutoCreateContextT<Bar> barCtxt;
auto childFoo = barCtxt->Create<Foo>();
auto onlyFoos = m_create->EnumerateChildContexts<Foo>();
ASSERT_EQ(2UL, onlyFoos.size()) << "Didn't collect only contexts with 'Foo' sigil";
ASSERT_NE(std::find(onlyFoos.begin(), onlyFoos.end(), fooCtxt), onlyFoos.end()) << "Context not enumerated";
ASSERT_NE(std::find(onlyFoos.begin(), onlyFoos.end(), childFoo), onlyFoos.end()) << "Context not enumerated";
}
TEST_F(CoreContextTest, TestEarlyLambdaReturn) {
// Create three children:
AutoCreateContext child1;
AutoCreateContext child2;
AutoCreateContext child3;
// Enumerate, but stop after three:
std::set<std::shared_ptr<CoreContext>> allChildren;
size_t totalSoFar = 0;
m_create->EnumerateChildContexts(
[&allChildren, &totalSoFar](std::shared_ptr<CoreContext> ctxt) -> bool {
if(totalSoFar++ == 3)
return false;
allChildren.insert(ctxt);
return true;
}
);
ASSERT_EQ(3UL, allChildren.size()) << "Enumeration routine failed to quit early";
// Verify that the root context isn't in the set--needed to assure that we are running a depth-first search.
ASSERT_EQ(0UL, allChildren.count(m_create)) << "EnumerateChildContexts did not execute depth-first";
}
TEST_F(CoreContextTest, ChildEnumerationIsCorrect) {
// Create a few child contexts:
AutoCreateContext v, w;
// Shouldn't find any contexts at this point:
auto vec = AutoCurrentContext()->EnumerateChildContexts<Object>();
ASSERT_TRUE(vec.empty()) << "Sigil-restricted child enumeration incorrectly detected at least one sigil-bearing child context";
// Create one sigil-bearing context:
AutoCreateContextT<Object> sigilContext;
// Verify that we only enumerate one child context:
vec = AutoCurrentContext()->EnumerateChildContexts<Object>();
ASSERT_EQ(1UL, vec.size()) << "Sigil-restricted child enumeration returned too many contexts";
}
<commit_msg>Include test that doesn't expect any enumerated children context<commit_after>#include "stdafx.h"
#include "CoreContextTest.h"
#include <set>
class Foo{};
class Bar{};
class Baz{};
TEST_F(CoreContextTest, TestEnumerateChildren) {
// Create a few anonymous children:
AutoCreateContext child1;
AutoCreateContext child2;
AutoCreateContext child3;
// Enumerate and see what we get back:
std::set<std::shared_ptr<CoreContext>> allChildren;
m_create->EnumerateChildContexts(
[&allChildren](std::shared_ptr<CoreContext> ctxt){
allChildren.insert(ctxt);
}
);
// Verify we get exactly four back:
ASSERT_EQ(4UL, allChildren.size()) << "Failed to enumerate the correct number of child contexts";
// Verify full membership:
ASSERT_EQ(1UL, allChildren.count(m_create)) << "Failed to find the root context in the returned context collection";
const char* childMissing = "Failed to find a child context in the set of children";
ASSERT_EQ(1UL, allChildren.count(child1)) << childMissing;
ASSERT_EQ(1UL, allChildren.count(child2)) << childMissing;
ASSERT_EQ(1UL, allChildren.count(child3)) << childMissing;
//Check if filtering by sigil works
AutoCreateContextT<Foo> fooCtxt;
AutoCreateContextT<Bar> barCtxt;
auto childFoo = barCtxt->Create<Foo>();
auto onlyFoos = m_create->EnumerateChildContexts<Foo>();
ASSERT_EQ(2UL, onlyFoos.size()) << "Didn't collect only contexts with 'Foo' sigil";
ASSERT_NE(std::find(onlyFoos.begin(), onlyFoos.end(), fooCtxt), onlyFoos.end()) << "Context not enumerated";
ASSERT_NE(std::find(onlyFoos.begin(), onlyFoos.end(), childFoo), onlyFoos.end()) << "Context not enumerated";
auto onlyBars = m_create->EnumerateChildContexts<Bar>();
ASSERT_EQ(1UL, onlyBars.size()) << "Didn't collect only contexts with 'Bar' sigil";
ASSERT_NE(std::find(onlyBars.begin(), onlyBars.end(), barCtxt), onlyBars.end()) << "Context not enumerated";
auto noBaz = m_create->EnumerateChildContexts<Baz>();
ASSERT_TRUE(noBaz.empty()) << "Incorrectly collected contexts with 'Baz' sigil";
}
TEST_F(CoreContextTest, TestEarlyLambdaReturn) {
// Create three children:
AutoCreateContext child1;
AutoCreateContext child2;
AutoCreateContext child3;
// Enumerate, but stop after three:
std::set<std::shared_ptr<CoreContext>> allChildren;
size_t totalSoFar = 0;
m_create->EnumerateChildContexts(
[&allChildren, &totalSoFar](std::shared_ptr<CoreContext> ctxt) -> bool {
if(totalSoFar++ == 3)
return false;
allChildren.insert(ctxt);
return true;
}
);
ASSERT_EQ(3UL, allChildren.size()) << "Enumeration routine failed to quit early";
// Verify that the root context isn't in the set--needed to assure that we are running a depth-first search.
ASSERT_EQ(0UL, allChildren.count(m_create)) << "EnumerateChildContexts did not execute depth-first";
}
TEST_F(CoreContextTest, ChildEnumerationIsCorrect) {
// Create a few child contexts:
AutoCreateContext v, w;
// Shouldn't find any contexts at this point:
auto vec = AutoCurrentContext()->EnumerateChildContexts<Object>();
ASSERT_TRUE(vec.empty()) << "Sigil-restricted child enumeration incorrectly detected at least one sigil-bearing child context";
// Create one sigil-bearing context:
AutoCreateContextT<Object> sigilContext;
// Verify that we only enumerate one child context:
vec = AutoCurrentContext()->EnumerateChildContexts<Object>();
ASSERT_EQ(1UL, vec.size()) << "Sigil-restricted child enumeration returned too many contexts";
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
* Copyright (C) 2013 Google Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "config.h"
#include "core/dom/MainThreadTaskRunner.h"
#include "core/dom/ExecutionContext.h"
#include "core/dom/ExecutionContextTask.h"
#include "core/events/EventQueue.h"
#include "core/testing/UnitTestHelpers.h"
#include <gtest/gtest.h>
using namespace WebCore;
namespace {
class NullEventQueue : public EventQueue {
public:
NullEventQueue() { }
virtual ~NullEventQueue() { }
virtual bool enqueueEvent(PassRefPtr<Event>) OVERRIDE { return true; }
virtual bool cancelEvent(Event*) OVERRIDE { return true; }
virtual void close() OVERRIDE { }
};
class NullExecutionContext : public ExecutionContext, public RefCounted<NullExecutionContext> {
public:
using RefCounted<NullExecutionContext>::ref;
using RefCounted<NullExecutionContext>::deref;
virtual void refExecutionContext() OVERRIDE { ref(); }
virtual void derefExecutionContext() OVERRIDE { deref(); }
virtual EventQueue* eventQueue() const OVERRIDE { return m_queue.get(); }
virtual bool tasksNeedSuspension() { return m_tasksNeedSuspension; }
void setTasksNeedSuspention(bool flag) { m_tasksNeedSuspension = flag; }
NullExecutionContext();
private:
bool m_tasksNeedSuspension;
OwnPtr<EventQueue> m_queue;
};
NullExecutionContext::NullExecutionContext()
: m_tasksNeedSuspension(false)
, m_queue(adoptPtr(new NullEventQueue()))
{
}
class MarkingBooleanTask FINAL : public ExecutionContextTask {
public:
static PassOwnPtr<MarkingBooleanTask> create(bool* toBeMarked)
{
return adoptPtr(new MarkingBooleanTask(toBeMarked));
}
virtual ~MarkingBooleanTask() { }
private:
MarkingBooleanTask(bool* toBeMarked) : m_toBeMarked(toBeMarked) { }
virtual void performTask(ExecutionContext* context) OVERRIDE
{
*m_toBeMarked = true;
}
bool* m_toBeMarked;
};
TEST(MainThreadTaskRunnerTest, PostTask)
{
RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext());
OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get());
bool isMarked = false;
runner->postTask(MarkingBooleanTask::create(&isMarked));
EXPECT_FALSE(isMarked);
WebCore::testing::runPendingTasks();
EXPECT_TRUE(isMarked);
}
TEST(MainThreadTaskRunnerTest, SuspendTask)
{
RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext());
OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get());
bool isMarked = false;
context->setTasksNeedSuspention(true);
runner->postTask(MarkingBooleanTask::create(&isMarked));
runner->suspend();
WebCore::testing::runPendingTasks();
EXPECT_FALSE(isMarked);
context->setTasksNeedSuspention(false);
runner->resume();
WebCore::testing::runPendingTasks();
EXPECT_TRUE(isMarked);
}
TEST(MainThreadTaskRunnerTest, RemoveRunner)
{
RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext());
OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get());
bool isMarked = false;
context->setTasksNeedSuspention(true);
runner->postTask(MarkingBooleanTask::create(&isMarked));
runner.clear();
WebCore::testing::runPendingTasks();
EXPECT_FALSE(isMarked);
}
}
<commit_msg>Remove wrong overload.<commit_after>/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
* Copyright (C) 2013 Google Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "config.h"
#include "core/dom/MainThreadTaskRunner.h"
#include "core/dom/ExecutionContext.h"
#include "core/dom/ExecutionContextTask.h"
#include "core/events/EventQueue.h"
#include "core/testing/UnitTestHelpers.h"
#include <gtest/gtest.h>
using namespace WebCore;
namespace {
class NullEventQueue : public EventQueue {
public:
NullEventQueue() { }
virtual ~NullEventQueue() { }
virtual bool enqueueEvent(PassRefPtr<Event>) OVERRIDE { return true; }
virtual bool cancelEvent(Event*) OVERRIDE { return true; }
virtual void close() OVERRIDE { }
};
class NullExecutionContext : public ExecutionContext, public RefCounted<NullExecutionContext> {
public:
using RefCounted<NullExecutionContext>::ref;
using RefCounted<NullExecutionContext>::deref;
virtual EventQueue* eventQueue() const OVERRIDE { return m_queue.get(); }
virtual bool tasksNeedSuspension() { return m_tasksNeedSuspension; }
void setTasksNeedSuspention(bool flag) { m_tasksNeedSuspension = flag; }
NullExecutionContext();
private:
bool m_tasksNeedSuspension;
OwnPtr<EventQueue> m_queue;
};
NullExecutionContext::NullExecutionContext()
: m_tasksNeedSuspension(false)
, m_queue(adoptPtr(new NullEventQueue()))
{
}
class MarkingBooleanTask FINAL : public ExecutionContextTask {
public:
static PassOwnPtr<MarkingBooleanTask> create(bool* toBeMarked)
{
return adoptPtr(new MarkingBooleanTask(toBeMarked));
}
virtual ~MarkingBooleanTask() { }
private:
MarkingBooleanTask(bool* toBeMarked) : m_toBeMarked(toBeMarked) { }
virtual void performTask(ExecutionContext* context) OVERRIDE
{
*m_toBeMarked = true;
}
bool* m_toBeMarked;
};
TEST(MainThreadTaskRunnerTest, PostTask)
{
RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext());
OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get());
bool isMarked = false;
runner->postTask(MarkingBooleanTask::create(&isMarked));
EXPECT_FALSE(isMarked);
WebCore::testing::runPendingTasks();
EXPECT_TRUE(isMarked);
}
TEST(MainThreadTaskRunnerTest, SuspendTask)
{
RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext());
OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get());
bool isMarked = false;
context->setTasksNeedSuspention(true);
runner->postTask(MarkingBooleanTask::create(&isMarked));
runner->suspend();
WebCore::testing::runPendingTasks();
EXPECT_FALSE(isMarked);
context->setTasksNeedSuspention(false);
runner->resume();
WebCore::testing::runPendingTasks();
EXPECT_TRUE(isMarked);
}
TEST(MainThreadTaskRunnerTest, RemoveRunner)
{
RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext());
OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get());
bool isMarked = false;
context->setTasksNeedSuspention(true);
runner->postTask(MarkingBooleanTask::create(&isMarked));
runner.clear();
WebCore::testing::runPendingTasks();
EXPECT_FALSE(isMarked);
}
}
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2012-2013, SimQuest Solutions 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.
/// \file
/// Tests for the OsgCamera class.
#include "SurgSim/Graphics/UnitTests/MockObjects.h"
#include "SurgSim/Graphics/UnitTests/MockOsgObjects.h"
#include "SurgSim/Framework/BasicSceneElement.h"
#include "SurgSim/Framework/FrameworkConvert.h"
#include "SurgSim/Graphics/OsgCamera.h"
#include "SurgSim/Graphics/OsgGroup.h"
#include "SurgSim/Graphics/OsgMatrixConversions.h"
#include "SurgSim/Graphics/OsgTexture2d.h"
#include "SurgSim/Graphics/OsgRenderTarget.h"
#include "SurgSim/Math/Quaternion.h"
#include <osg/Camera>
#include <osg/ref_ptr>
#include <gtest/gtest.h>
#include <random>
using SurgSim::Framework::BasicSceneElement;
using SurgSim::Math::Matrix44d;
using SurgSim::Math::Quaterniond;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Vector3d;
using SurgSim::Math::makeRigidTransform;
namespace SurgSim
{
namespace Graphics
{
TEST(OsgCameraTests, InitTest)
{
ASSERT_NO_THROW({std::shared_ptr<Camera> camera = std::make_shared<OsgCamera>("test name");});
std::shared_ptr<OsgCamera> osgCamera = std::make_shared<OsgCamera>("test name");
std::shared_ptr<Camera> camera = osgCamera;
EXPECT_EQ("test name", camera->getName());
EXPECT_TRUE(camera->isActive());
EXPECT_TRUE(camera->getPose().matrix().isApprox(
fromOsg(osgCamera->getOsgCamera()->getViewMatrix()).inverse())) <<
"Camera's pose should be initialized to the inverse of the osg::Camera's view matrix!";
EXPECT_TRUE(camera->getViewMatrix().isApprox(fromOsg(osgCamera->getOsgCamera()->getViewMatrix()))) <<
"Camera's view matrix should be initialized to the osg::Camera's view matrix!";
EXPECT_TRUE(camera->getProjectionMatrix().isApprox(fromOsg(osgCamera->getOsgCamera()->getProjectionMatrix()))) <<
"Camera's projection matrix should be initialized to the osg::Camera's projection matrix!";
EXPECT_EQ(nullptr, camera->getRenderGroup());
}
TEST(OsgCameraTests, OsgNodesTest)
{
std::shared_ptr<OsgCamera> osgCamera = std::make_shared<OsgCamera>("test name");
std::shared_ptr<OsgRepresentation> osgRepresentation = osgCamera;
/// Check that the OSG nodes of the camera are built correctly
osg::ref_ptr<osg::Node> node = osgRepresentation->getOsgNode();
osg::ref_ptr<osg::Switch> switchNode = dynamic_cast<osg::Switch*>(node.get());
EXPECT_TRUE(switchNode.valid());
EXPECT_EQ(1u, switchNode->getNumChildren());
osg::ref_ptr<osg::Camera> camera = osgCamera->getOsgCamera();
EXPECT_EQ(camera.get(), switchNode->getChild(0));
}
TEST(OsgCameraTests, GroupTest)
{
std::shared_ptr<OsgCamera> osgCamera = std::make_shared<OsgCamera>("test name");
std::shared_ptr<Camera> camera = osgCamera;
EXPECT_EQ(nullptr, camera->getRenderGroup());
/// Adding an OsgGroup should succeed
std::shared_ptr<OsgGroup> osgGroup = std::make_shared<OsgGroup>(camera->getRenderGroupReference());
std::shared_ptr<Group> group = osgGroup;
EXPECT_TRUE(camera->setRenderGroup(group));
EXPECT_EQ(group, camera->getRenderGroup());
/// Check that the OSG node of the group is added to the OSG camera correctly
EXPECT_EQ(osgGroup->getOsgGroup(), osgCamera->getOsgCamera()->getChild(0)->asGroup()->getChild(0));
/// Adding a group that does not derive from OsgGroup should fail
std::shared_ptr<Group> mockGroup = std::make_shared<MockGroup>(camera->getRenderGroupReference());
EXPECT_FALSE(camera->setRenderGroup(mockGroup));
EXPECT_EQ(group, camera->getRenderGroup());
EXPECT_EQ(osgGroup->getOsgGroup(), osgCamera->getOsgCamera()->getChild(0)->asGroup()->getChild(0));
}
TEST(OsgCameraTests, PoseTest)
{
std::shared_ptr<OsgCamera> osgCamera = std::make_shared<OsgCamera>("test name");
std::shared_ptr<Camera> camera = osgCamera;
camera->setRenderGroupReference("Test");
std::shared_ptr<BasicSceneElement> element = std::make_shared<BasicSceneElement>("element");
element->addComponent(camera);
element->initialize();
camera->wakeUp();
RigidTransform3d elementPose = SurgSim::Math::makeRigidTransform(
Quaterniond(SurgSim::Math::Vector4d::Random()).normalized(), Vector3d::Random());
RigidTransform3d localPose = SurgSim::Math::makeRigidTransform(
Quaterniond(SurgSim::Math::Vector4d::Random()).normalized(), Vector3d::Random());
RigidTransform3d pose = elementPose * localPose;
{
SCOPED_TRACE("Check Initial Pose");
EXPECT_TRUE(camera->getLocalPose().isApprox(RigidTransform3d::Identity()));
EXPECT_TRUE(camera->getPose().isApprox(RigidTransform3d::Identity()));
}
{
SCOPED_TRACE("Set Local Pose");
camera->setLocalPose(localPose);
EXPECT_TRUE(camera->getLocalPose().isApprox(localPose));
EXPECT_TRUE(camera->getPose().isApprox(localPose));
EXPECT_TRUE(camera->getViewMatrix().isApprox(localPose.matrix().inverse()));
EXPECT_TRUE(camera->getViewMatrix().inverse().isApprox(camera->getInverseViewMatrix()));
camera->update(0.01);
EXPECT_TRUE(fromOsg(osgCamera->getOsgCamera()->getViewMatrix()).isApprox(localPose.matrix().inverse()));
}
{
SCOPED_TRACE("Set Element Pose");
element->setPose(elementPose);
EXPECT_TRUE(camera->getLocalPose().isApprox(localPose));
EXPECT_TRUE(camera->getPose().isApprox(pose));
EXPECT_TRUE(camera->getViewMatrix().isApprox(pose.matrix().inverse()));
EXPECT_TRUE(camera->getViewMatrix().inverse().isApprox(camera->getInverseViewMatrix()));
camera->update(0.01);
EXPECT_TRUE(fromOsg(osgCamera->getOsgCamera()->getViewMatrix()).isApprox(pose.matrix().inverse()));
}
}
TEST(OsgCameraTests, MatricesTest)
{
std::shared_ptr<OsgCamera> osgCamera = std::make_shared<OsgCamera>("test name");
std::shared_ptr<Camera> camera = osgCamera;
Matrix44d projectionMatrix = Matrix44d::Random();
camera->setProjectionMatrix(projectionMatrix);
EXPECT_TRUE(camera->getProjectionMatrix().isApprox(projectionMatrix));
}
TEST(OsgCameraTests, RenderTargetTest)
{
auto osgCamera = std::make_shared<OsgCamera>("test camera");
std::shared_ptr<Camera> camera = osgCamera;
std::shared_ptr<RenderTarget> renderTarget = std::make_shared<OsgRenderTarget2d>(256, 256, 1.0, 2, true);
EXPECT_NO_THROW(camera->setRenderTarget(renderTarget));
EXPECT_TRUE(osgCamera->getOsgCamera()->isRenderToTextureCamera());
}
TEST(OsgCameraTests, CameraGroupTest)
{
std::shared_ptr<Camera> camera = std::make_shared<OsgCamera>("TestRepresentation");
camera->clearGroupReferences();
camera->addGroupReference("test1");
camera->addGroupReference("test2");
EXPECT_EQ(2u, camera->getGroupReferences().size());
camera->setRenderGroupReference("otherTest");
EXPECT_EQ(2u, camera->getGroupReferences().size());
// Setting the render group of a camera to the group that it is in should remove the group
// from the set
camera->setRenderGroupReference("test1");
EXPECT_EQ(1u, camera->getGroupReferences().size());
// Should not be able to set group reference to the current render group
EXPECT_FALSE(camera->addGroupReference("test1"));
EXPECT_EQ(1u, camera->getGroupReferences().size());
}
TEST(OsgCameraTests, Serialization)
{
std::shared_ptr<OsgCamera> camera = std::make_shared<OsgCamera>("TestOsgCamera");
// Set values.
SurgSim::Math::Matrix44d projection = SurgSim::Math::Matrix44d::Random();
camera->setValue("ProjectionMatrix", projection);
camera->setValue("AmbientColor", SurgSim::Math::Vector4d(0.1, 0.2, 0.3, 0.4));
// Serialize.
YAML::Node node;
EXPECT_NO_THROW(node = YAML::convert<SurgSim::Framework::Component>::encode(*camera););
// Deserialize.
std::shared_ptr<Camera> newCamera;
newCamera = std::dynamic_pointer_cast<OsgCamera>(node.as<std::shared_ptr<SurgSim::Framework::Component>>());
EXPECT_NE(nullptr, newCamera);
// Verify.
EXPECT_TRUE(boost::any_cast<SurgSim::Math::Matrix44d>(camera->getValue("ProjectionMatrix")).isApprox(
boost::any_cast<SurgSim::Math::Matrix44d>(newCamera->getValue("ProjectionMatrix"))));
EXPECT_TRUE(boost::any_cast<SurgSim::Math::Vector4d>(camera->getValue("AmbientColor")).isApprox(
boost::any_cast<SurgSim::Math::Vector4d>(newCamera->getValue("AmbientColor"))));
}
} // namespace Graphics
} // namespace SurgSim
<commit_msg>Keep ActivenessTest in OsgCameraTests<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2012-2013, SimQuest Solutions 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.
/// \file
/// Tests for the OsgCamera class.
#include "SurgSim/Graphics/UnitTests/MockObjects.h"
#include "SurgSim/Graphics/UnitTests/MockOsgObjects.h"
#include "SurgSim/Framework/BasicSceneElement.h"
#include "SurgSim/Framework/FrameworkConvert.h"
#include "SurgSim/Graphics/OsgCamera.h"
#include "SurgSim/Graphics/OsgGroup.h"
#include "SurgSim/Graphics/OsgMatrixConversions.h"
#include "SurgSim/Graphics/OsgTexture2d.h"
#include "SurgSim/Graphics/OsgRenderTarget.h"
#include "SurgSim/Math/Quaternion.h"
#include <osg/Camera>
#include <osg/ref_ptr>
#include <gtest/gtest.h>
#include <random>
using SurgSim::Framework::BasicSceneElement;
using SurgSim::Math::Matrix44d;
using SurgSim::Math::Quaterniond;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Vector3d;
using SurgSim::Math::makeRigidTransform;
namespace SurgSim
{
namespace Graphics
{
TEST(OsgCameraTests, InitTest)
{
ASSERT_NO_THROW({std::shared_ptr<Camera> camera = std::make_shared<OsgCamera>("test name");});
std::shared_ptr<OsgCamera> osgCamera = std::make_shared<OsgCamera>("test name");
std::shared_ptr<Camera> camera = osgCamera;
EXPECT_EQ("test name", camera->getName());
EXPECT_TRUE(camera->isActive());
EXPECT_TRUE(camera->getPose().matrix().isApprox(
fromOsg(osgCamera->getOsgCamera()->getViewMatrix()).inverse())) <<
"Camera's pose should be initialized to the inverse of the osg::Camera's view matrix!";
EXPECT_TRUE(camera->getViewMatrix().isApprox(fromOsg(osgCamera->getOsgCamera()->getViewMatrix()))) <<
"Camera's view matrix should be initialized to the osg::Camera's view matrix!";
EXPECT_TRUE(camera->getProjectionMatrix().isApprox(fromOsg(osgCamera->getOsgCamera()->getProjectionMatrix()))) <<
"Camera's projection matrix should be initialized to the osg::Camera's projection matrix!";
EXPECT_EQ(nullptr, camera->getRenderGroup());
}
TEST(OsgCameraTests, OsgNodesTest)
{
std::shared_ptr<OsgCamera> osgCamera = std::make_shared<OsgCamera>("test name");
std::shared_ptr<OsgRepresentation> osgRepresentation = osgCamera;
/// Check that the OSG nodes of the camera are built correctly
osg::ref_ptr<osg::Node> node = osgRepresentation->getOsgNode();
osg::ref_ptr<osg::Switch> switchNode = dynamic_cast<osg::Switch*>(node.get());
EXPECT_TRUE(switchNode.valid());
EXPECT_EQ(1u, switchNode->getNumChildren());
osg::ref_ptr<osg::Camera> camera = osgCamera->getOsgCamera();
EXPECT_EQ(camera.get(), switchNode->getChild(0));
}
TEST(OsgCameraTests, ActivenessTest)
{
std::shared_ptr<OsgCamera> osgCamera = std::make_shared<OsgCamera>("test name");
std::shared_ptr<OsgRepresentation> osgRepresentation = osgCamera;
std::shared_ptr<Camera> camera = osgCamera;
// Get the osg::Switch from the OsgRepresentation so that we can make sure that the osg::Camera has the
// correct visibility.
osg::ref_ptr<osg::Switch> switchNode = dynamic_cast<osg::Switch*>(osgRepresentation->getOsgNode().get());
EXPECT_TRUE(switchNode.valid());
EXPECT_TRUE(camera->isActive());
EXPECT_TRUE(switchNode->getChildValue(osgCamera->getOsgCamera()));
camera->setLocalActive(false);
EXPECT_FALSE(camera->isActive());
EXPECT_FALSE(switchNode->getChildValue(osgCamera->getOsgCamera()));
camera->setLocalActive(true);
EXPECT_TRUE(camera->isActive());
EXPECT_TRUE(switchNode->getChildValue(osgCamera->getOsgCamera()));
}
TEST(OsgCameraTests, GroupTest)
{
std::shared_ptr<OsgCamera> osgCamera = std::make_shared<OsgCamera>("test name");
std::shared_ptr<Camera> camera = osgCamera;
EXPECT_EQ(nullptr, camera->getRenderGroup());
/// Adding an OsgGroup should succeed
std::shared_ptr<OsgGroup> osgGroup = std::make_shared<OsgGroup>(camera->getRenderGroupReference());
std::shared_ptr<Group> group = osgGroup;
EXPECT_TRUE(camera->setRenderGroup(group));
EXPECT_EQ(group, camera->getRenderGroup());
/// Check that the OSG node of the group is added to the OSG camera correctly
EXPECT_EQ(osgGroup->getOsgGroup(), osgCamera->getOsgCamera()->getChild(0)->asGroup()->getChild(0));
/// Adding a group that does not derive from OsgGroup should fail
std::shared_ptr<Group> mockGroup = std::make_shared<MockGroup>(camera->getRenderGroupReference());
EXPECT_FALSE(camera->setRenderGroup(mockGroup));
EXPECT_EQ(group, camera->getRenderGroup());
EXPECT_EQ(osgGroup->getOsgGroup(), osgCamera->getOsgCamera()->getChild(0)->asGroup()->getChild(0));
}
TEST(OsgCameraTests, PoseTest)
{
std::shared_ptr<OsgCamera> osgCamera = std::make_shared<OsgCamera>("test name");
std::shared_ptr<Camera> camera = osgCamera;
camera->setRenderGroupReference("Test");
std::shared_ptr<BasicSceneElement> element = std::make_shared<BasicSceneElement>("element");
element->addComponent(camera);
element->initialize();
camera->wakeUp();
RigidTransform3d elementPose = SurgSim::Math::makeRigidTransform(
Quaterniond(SurgSim::Math::Vector4d::Random()).normalized(), Vector3d::Random());
RigidTransform3d localPose = SurgSim::Math::makeRigidTransform(
Quaterniond(SurgSim::Math::Vector4d::Random()).normalized(), Vector3d::Random());
RigidTransform3d pose = elementPose * localPose;
{
SCOPED_TRACE("Check Initial Pose");
EXPECT_TRUE(camera->getLocalPose().isApprox(RigidTransform3d::Identity()));
EXPECT_TRUE(camera->getPose().isApprox(RigidTransform3d::Identity()));
}
{
SCOPED_TRACE("Set Local Pose");
camera->setLocalPose(localPose);
EXPECT_TRUE(camera->getLocalPose().isApprox(localPose));
EXPECT_TRUE(camera->getPose().isApprox(localPose));
EXPECT_TRUE(camera->getViewMatrix().isApprox(localPose.matrix().inverse()));
EXPECT_TRUE(camera->getViewMatrix().inverse().isApprox(camera->getInverseViewMatrix()));
camera->update(0.01);
EXPECT_TRUE(fromOsg(osgCamera->getOsgCamera()->getViewMatrix()).isApprox(localPose.matrix().inverse()));
}
{
SCOPED_TRACE("Set Element Pose");
element->setPose(elementPose);
EXPECT_TRUE(camera->getLocalPose().isApprox(localPose));
EXPECT_TRUE(camera->getPose().isApprox(pose));
EXPECT_TRUE(camera->getViewMatrix().isApprox(pose.matrix().inverse()));
EXPECT_TRUE(camera->getViewMatrix().inverse().isApprox(camera->getInverseViewMatrix()));
camera->update(0.01);
EXPECT_TRUE(fromOsg(osgCamera->getOsgCamera()->getViewMatrix()).isApprox(pose.matrix().inverse()));
}
}
TEST(OsgCameraTests, MatricesTest)
{
std::shared_ptr<OsgCamera> osgCamera = std::make_shared<OsgCamera>("test name");
std::shared_ptr<Camera> camera = osgCamera;
Matrix44d projectionMatrix = Matrix44d::Random();
camera->setProjectionMatrix(projectionMatrix);
EXPECT_TRUE(camera->getProjectionMatrix().isApprox(projectionMatrix));
}
TEST(OsgCameraTests, RenderTargetTest)
{
auto osgCamera = std::make_shared<OsgCamera>("test camera");
std::shared_ptr<Camera> camera = osgCamera;
std::shared_ptr<RenderTarget> renderTarget = std::make_shared<OsgRenderTarget2d>(256, 256, 1.0, 2, true);
EXPECT_NO_THROW(camera->setRenderTarget(renderTarget));
EXPECT_TRUE(osgCamera->getOsgCamera()->isRenderToTextureCamera());
}
TEST(OsgCameraTests, CameraGroupTest)
{
std::shared_ptr<Camera> camera = std::make_shared<OsgCamera>("TestRepresentation");
camera->clearGroupReferences();
camera->addGroupReference("test1");
camera->addGroupReference("test2");
EXPECT_EQ(2u, camera->getGroupReferences().size());
camera->setRenderGroupReference("otherTest");
EXPECT_EQ(2u, camera->getGroupReferences().size());
// Setting the render group of a camera to the group that it is in should remove the group
// from the set
camera->setRenderGroupReference("test1");
EXPECT_EQ(1u, camera->getGroupReferences().size());
// Should not be able to set group reference to the current render group
EXPECT_FALSE(camera->addGroupReference("test1"));
EXPECT_EQ(1u, camera->getGroupReferences().size());
}
TEST(OsgCameraTests, Serialization)
{
std::shared_ptr<OsgCamera> camera = std::make_shared<OsgCamera>("TestOsgCamera");
// Set values.
SurgSim::Math::Matrix44d projection = SurgSim::Math::Matrix44d::Random();
camera->setValue("ProjectionMatrix", projection);
camera->setValue("AmbientColor", SurgSim::Math::Vector4d(0.1, 0.2, 0.3, 0.4));
// Serialize.
YAML::Node node;
EXPECT_NO_THROW(node = YAML::convert<SurgSim::Framework::Component>::encode(*camera););
// Deserialize.
std::shared_ptr<Camera> newCamera;
newCamera = std::dynamic_pointer_cast<OsgCamera>(node.as<std::shared_ptr<SurgSim::Framework::Component>>());
EXPECT_NE(nullptr, newCamera);
// Verify.
EXPECT_TRUE(boost::any_cast<SurgSim::Math::Matrix44d>(camera->getValue("ProjectionMatrix")).isApprox(
boost::any_cast<SurgSim::Math::Matrix44d>(newCamera->getValue("ProjectionMatrix"))));
EXPECT_TRUE(boost::any_cast<SurgSim::Math::Vector4d>(camera->getValue("AmbientColor")).isApprox(
boost::any_cast<SurgSim::Math::Vector4d>(newCamera->getValue("AmbientColor"))));
}
} // namespace Graphics
} // namespace SurgSim
<|endoftext|> |
<commit_before>#include "BottomUpTW.hh"
#include <algorithm>
#include <iostream>
#include <string>
#include <sstream> // for ostringstream
#include <cassert>
int bottomUpTW(Graph G)
{
VSet S(G);
//Remove elements in the max-clique of G
VSet maxClique = exactMaxClique(G);
std::vector<Vertex> cliqueVec(maxClique.size());
maxClique.members(cliqueVec);
for (auto iter = cliqueVec.begin(); iter != cliqueVec.end(); ++iter)
{
S.erase(*iter);
}
int upperBound = calcUpperBound(G, S);
return bottomUpTWFromSet(maxClique, G, S, upperBound);
}
int calcUpperBound(Graph G, VSet S)
{
//Optimiation: set the golbal upper-bound to the TW from some linear ordering
//First try: default ordering
std::vector<Vertex> Svec(S.size());
S.members(Svec);
int globalUpperBound = permutTW(S, Svec, G);
//Second try: order by degree ascending
std::sort(Svec.begin(), Svec.end(), [G](Vertex u, Vertex v)
{
auto ud = boost::degree(u, G);
auto vd = boost::degree(v, G);
return ud < vd;
});
globalUpperBound = std::min(globalUpperBound, permutTW(S, Svec, G));
//Third try: order by degree descending
//Svec = S.members();
std::sort(Svec.begin(), Svec.end(), [G](Vertex u, Vertex v)
{
auto ud = boost::degree(u, G);
auto vd = boost::degree(v, G);
return ud > vd;
});
globalUpperBound = std::min(globalUpperBound, permutTW(S, Svec, G));
std::cout << "Found global upper bound " << globalUpperBound << "\n";
return globalUpperBound;
}
std::string showLayer(std::unordered_map<VSet, int> TW)
{
std::ostringstream out;
for (auto iter = TW.begin(); iter != TW.end(); ++iter)
{
out << "{" << showSet(iter->first) << "=" << iter->second << "}, ";
}
return out.str();
}
/*
#if defined (__GNUC__) && ( __GNUC__ >= 3 )
typedef __gnu_cxx::hash_map< HashKey,
#else
typedef std::hash_map< HashKey,
#endif
unsigned,
hash_compare_for_pairs,
hash_equalkey_for_pairs > VertexSetHashMap;
*/
int maybeMin(int x, int y)
{
if (x == -1)
{
return y;
}
if (y == -1)
{
return x;
}
return std::min(x, y);
}
int bottomUpTWFromSet(VSet clique, const Graph& G, const VSet& SStart, int globalUpperBound)
{
std::unordered_map<VSet, int> TW[MAX_NUM_VERTICES];
VSet emptySet;
TW[0][emptySet] = NO_WIDTH;
//TODO remove
//globalUpperBound = 26;
int n = SStart.size();// boost::num_vertices(G);
int nGraph = boost::num_vertices(G);
std::vector<Vertex> vertInfo;
SStart.members(vertInfo); // boost::vertices(G);
auto vertInfoStart = vertInfo.begin();
auto vertInfoEnd = vertInfo.end();
int upperBound = globalUpperBound;
for (int i = 1; i < SStart.size(); ++i)
{
std::cout << "Level " << i << "\n";
//std::cout << "Num Q " << numQCalled << "\n";
//TODO what is this? Taken from Java version
int minTW = upperBound;
std::unordered_map<VSet, int> currentTW;
auto twLoopEnd = TW[i - 1].end();
for (auto pair = TW[i - 1].begin(); pair != twLoopEnd; ++pair)
{
VSet S = pair->first;
int r = pair->second;
//std::cout << "On set " << showSet(S);
//Vertex firstSet = S.first();
std::vector<int> qSizes(nGraph);
findQvalues(nGraph, S, G, qSizes); //TODO n or nGraph?
for (auto x = vertInfoStart; x != vertInfoEnd; ++x)
{
Vertex v = *x;
if ( (!S.contains(v)) && (!clique.contains(v)) /*&& v < firstSet*/ ) //TODO check if in clique here?
{
VSet SUx = S;
SUx.insert(v);
int q = qSizes[v];
//int trueQ = qCheck(nGraph, S, v, G);
//int qOld = sizeQ(nGraph, S, v, G);
//assert(q == trueQ);
int rr = std::max(r, q);
if (rr >= nGraph - i - 1 && rr < minTW) {
minTW = rr;
}
if (rr < upperBound)
{
auto searchInfo = currentTW.find(SUx);
if (searchInfo == currentTW.end() || rr < r )
{
//std::vector<Vertex> newSeq(oldSeq);
//newSeq.push_back(v);
currentTW[SUx] = rr;
}
}
}
}
}
//TODO right place in loop?
upperBound = std::min(upperBound, std::max(minTW, nGraph - i - 1));
//Delete any that we falsely added, that are above our new upper bound
auto loopEnd = currentTW.end();
for (auto pair = currentTW.begin(); pair != loopEnd; ++pair)
{
if (pair->second < upperBound)
{
TW[i][pair->first] = pair->second;
}
}
std::cout << "TW i size: " << i << " " << TW[i].size() << "\n";
if (i < 3)
{
//std::cout << "TW i: " << i << " " << showLayer(TW[i]) << "\n";
}
//std::cout << "TW i: " << i << " " << TW[i].size() << "\n";
}
auto searchInfo = TW[SStart.size()].find(SStart);
if (searchInfo == TW[SStart.size()].end())
{
return upperBound;
}
//std::cout << "Found sequence: " << showSet(searchInfo->second.second) << "\n";
return searchInfo->second;
}
<commit_msg>Try to diagnose correctness issues<commit_after>#include "BottomUpTW.hh"
#include <algorithm>
#include <iostream>
#include <string>
#include <sstream> // for ostringstream
#include <cassert>
int bottomUpTW(Graph G)
{
VSet S(G);
//Remove elements in the max-clique of G
VSet maxClique = exactMaxClique(G);
std::vector<Vertex> cliqueVec(maxClique.size());
maxClique.members(cliqueVec);
for (auto iter = cliqueVec.begin(); iter != cliqueVec.end(); ++iter)
{
S.erase(*iter);
}
int upperBound = calcUpperBound(G, S);
return bottomUpTWFromSet(maxClique, G, S, upperBound);
}
int calcUpperBound(Graph G, VSet S)
{
//Optimiation: set the golbal upper-bound to the TW from some linear ordering
//First try: default ordering
std::vector<Vertex> Svec(S.size());
S.members(Svec);
int globalUpperBound = permutTW(S, Svec, G);
//Second try: order by degree ascending
std::sort(Svec.begin(), Svec.end(), [G](Vertex u, Vertex v)
{
auto ud = boost::degree(u, G);
auto vd = boost::degree(v, G);
return ud < vd;
});
globalUpperBound = std::min(globalUpperBound, permutTW(S, Svec, G));
//Third try: order by degree descending
//Svec = S.members();
std::sort(Svec.begin(), Svec.end(), [G](Vertex u, Vertex v)
{
auto ud = boost::degree(u, G);
auto vd = boost::degree(v, G);
return ud > vd;
});
globalUpperBound = std::min(globalUpperBound, permutTW(S, Svec, G));
std::cout << "Found global upper bound " << globalUpperBound << "\n";
return globalUpperBound;
}
std::string showLayer(std::unordered_map<VSet, int> TW)
{
std::ostringstream out;
for (auto iter = TW.begin(); iter != TW.end(); ++iter)
{
out << "{" << showSet(iter->first) << "=" << iter->second << "}, ";
}
return out.str();
}
/*
#if defined (__GNUC__) && ( __GNUC__ >= 3 )
typedef __gnu_cxx::hash_map< HashKey,
#else
typedef std::hash_map< HashKey,
#endif
unsigned,
hash_compare_for_pairs,
hash_equalkey_for_pairs > VertexSetHashMap;
*/
int maybeMin(int x, int y)
{
if (x == -1)
{
return y;
}
if (y == -1)
{
return x;
}
return std::min(x, y);
}
int bottomUpTWFromSet(VSet clique, const Graph& G, const VSet& SStart, int globalUpperBound)
{
std::unordered_map<VSet, int> TW[MAX_NUM_VERTICES];
VSet emptySet;
TW[0][emptySet] = NO_WIDTH;
//TODO remove
//globalUpperBound = 26;
int n = SStart.size();// boost::num_vertices(G);
int nGraph = boost::num_vertices(G);
std::vector<Vertex> vertInfo;
SStart.members(vertInfo); // boost::vertices(G);
auto vertInfoStart = vertInfo.begin();
auto vertInfoEnd = vertInfo.end();
int upperBound = globalUpperBound;
for (int i = 1; i < SStart.size(); ++i)
{
std::cout << "Level " << i << "\n";
//std::cout << "Num Q " << numQCalled << "\n";
//TODO what is this? Taken from Java version
int minTW = upperBound;
std::unordered_map<VSet, int> currentTW;
auto twLoopEnd = TW[i - 1].end();
for (auto pair = TW[i - 1].begin(); pair != twLoopEnd; ++pair)
{
VSet S = pair->first;
int r = pair->second;
//std::cout << "On set " << showSet(S);
//Vertex firstSet = S.first();
std::vector<int> qSizes(nGraph);
findQvalues(nGraph, S, G, qSizes); //TODO n or nGraph?
for (auto x = vertInfoStart; x != vertInfoEnd; ++x)
{
Vertex v = *x;
if ( (!S.contains(v)) && (!clique.contains(v)) /*&& v < firstSet*/ ) //TODO check if in clique here?
{
VSet SUx = S;
SUx.insert(v);
int q = qSizes[v];
//int trueQ = qCheck(nGraph, S, v, G);
//int qOld = sizeQ(nGraph, S, v, G);
//assert(q == trueQ);
int rr = std::max(r, q);
if (rr >= nGraph - i - 1 && rr < minTW) {
minTW = rr;
}
if (rr < upperBound)
{
auto searchInfo = currentTW.find(SUx);
if (searchInfo == currentTW.end() || rr < r )
{
//std::vector<Vertex> newSeq(oldSeq);
//newSeq.push_back(v);
currentTW[SUx] = rr;
}
}
}
}
}
//TODO right place in loop?
//upperBound = std::min(upperBound, std::max(minTW, nGraph - i - 1));
//std::cout << "New upper bound " << upperBound << "\n";
//Delete any that we falsely added, that are above our new upper bound
auto loopEnd = currentTW.end();
for (auto pair = currentTW.begin(); pair != loopEnd; ++pair)
{
if (pair->second < upperBound)
{
TW[i][pair->first] = pair->second;
}
}
std::cout << "TW i size: " << i << " " << TW[i].size() << "\n";
if (i < 3)
{
//std::cout << "TW i: " << i << " " << showLayer(TW[i]) << "\n";
}
//std::cout << "TW i: " << i << " " << TW[i].size() << "\n";
}
auto searchInfo = TW[SStart.size()].find(SStart);
if (searchInfo == TW[SStart.size()].end())
{
return upperBound;
}
//std::cout << "Found sequence: " << showSet(searchInfo->second.second) << "\n";
return searchInfo->second;
}
<|endoftext|> |
<commit_before>/*
* Vulkan Samples Kit
*
* Copyright (C) 2015 LunarG, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/*
VULKAN_SAMPLE_SHORT_DESCRIPTION
Create Vulkan command buffer
*/
#include <util_init.hpp>
#include <assert.h>
#include <cstdlib>
int main(int argc, char **argv)
{
VkResult U_ASSERT_ONLY res;
struct sample_info info = {};
char sample_title[] = "Depth Buffer Sample";
init_global_layer_properties(info);
info.instance_extension_names.push_back(VK_WSI_SWAPCHAIN_EXTENSION_NAME);
info.device_extension_names.push_back(VK_WSI_DEVICE_SWAPCHAIN_EXTENSION_NAME);
init_instance(info, sample_title);
init_enumerate_device(info);
init_device(info);
info.width = info.height = 500;
init_connection(info);
init_window(info);
init_wsi(info);
/* VULKAN_KEY_START */
/* Create a command pool to allocate our command buffer from */
VkCmdPoolCreateInfo cmd_pool_info = {};
cmd_pool_info.sType = VK_STRUCTURE_TYPE_CMD_POOL_CREATE_INFO;
cmd_pool_info.pNext = NULL;
cmd_pool_info.queueFamilyIndex = info.graphics_queue_family_index;
cmd_pool_info.flags = 0;
res = vkCreateCommandPool(info.device, &cmd_pool_info, &info.cmd_pool);
assert(!res);
/* Create the command buffer from the command pool */
VkCmdBufferCreateInfo cmd = {};
cmd.sType = VK_STRUCTURE_TYPE_CMD_BUFFER_CREATE_INFO;
cmd.pNext = NULL;
cmd.cmdPool = info.cmd_pool;
cmd.level = VK_CMD_BUFFER_LEVEL_PRIMARY;
cmd.flags = 0;
res = vkCreateCommandBuffer(info.device, &cmd, &info.cmd);
assert(!res);
/* VULKAN_KEY_END */
vkDestroyCommandBuffer(info.device, info.cmd);
vkDestroyCommandPool(info.device, info.cmd_pool);
vkDestroyDevice(info.device);
vkDestroyInstance(info.inst);
destroy_window(info);
}
<commit_msg>Fix command buffer sample title<commit_after>/*
* Vulkan Samples Kit
*
* Copyright (C) 2015 LunarG, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/*
VULKAN_SAMPLE_SHORT_DESCRIPTION
Create Vulkan command buffer
*/
#include <util_init.hpp>
#include <assert.h>
#include <cstdlib>
int main(int argc, char **argv)
{
VkResult U_ASSERT_ONLY res;
struct sample_info info = {};
char sample_title[] = "Command Buffer Sample";
init_global_layer_properties(info);
info.instance_extension_names.push_back(VK_WSI_SWAPCHAIN_EXTENSION_NAME);
info.device_extension_names.push_back(VK_WSI_DEVICE_SWAPCHAIN_EXTENSION_NAME);
init_instance(info, sample_title);
init_enumerate_device(info);
init_device(info);
info.width = info.height = 500;
init_connection(info);
init_window(info);
init_wsi(info);
/* VULKAN_KEY_START */
/* Create a command pool to allocate our command buffer from */
VkCmdPoolCreateInfo cmd_pool_info = {};
cmd_pool_info.sType = VK_STRUCTURE_TYPE_CMD_POOL_CREATE_INFO;
cmd_pool_info.pNext = NULL;
cmd_pool_info.queueFamilyIndex = info.graphics_queue_family_index;
cmd_pool_info.flags = 0;
res = vkCreateCommandPool(info.device, &cmd_pool_info, &info.cmd_pool);
assert(!res);
/* Create the command buffer from the command pool */
VkCmdBufferCreateInfo cmd = {};
cmd.sType = VK_STRUCTURE_TYPE_CMD_BUFFER_CREATE_INFO;
cmd.pNext = NULL;
cmd.cmdPool = info.cmd_pool;
cmd.level = VK_CMD_BUFFER_LEVEL_PRIMARY;
cmd.flags = 0;
res = vkCreateCommandBuffer(info.device, &cmd, &info.cmd);
assert(!res);
/* VULKAN_KEY_END */
vkDestroyCommandBuffer(info.device, info.cmd);
vkDestroyCommandPool(info.device, info.cmd_pool);
vkDestroyDevice(info.device);
vkDestroyInstance(info.inst);
destroy_window(info);
}
<|endoftext|> |
<commit_before>/*
* reconfigureVLIW.cpp
*
* Created on: 9 févr. 2017
* Author: simon
*/
#include <isa/vexISA.h>
#include <transformation/reconfigureVLIW.h>
unsigned int schedulerConfigurations[16] = {0x00005e00,0x0000546c,0x00005ec4,0x046c50c4,0x00005ecc,0x040c5ec4,0,0,
0x00005e64,0x44605e04,0x00005e6c,0x40605ec4,0x006c5ec4,0x446c5ec4,0,0};
char validConfigurations[12] = {0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12 ,13};
char getIssueWidth(char configuration){
//This function returns the issue width of each configuration code
//We extract variables
char regCode = (configuration >> 4) & 0x1;
char memCode = (configuration >> 3) & 0x1;
char multCode = (configuration >> 1) & 0x3;
char boostCode = configuration & 0x1;
//Sum resources of mem and mult and round to the upper even number (this is the or)
char issueWidth = (memCode + multCode + 2);
if (issueWidth & 0x1)
issueWidth++;
//If boost code then it is the version with increased issue width
if (boostCode)
issueWidth += 2;
return issueWidth;
}
unsigned int getConfigurationForScheduler(char configuration){
return schedulerConfigurations[configuration % 16];
}
unsigned int getReconfigurationInstruction(char configuration){
unsigned int schedulerConf = getConfigurationForScheduler(configuration);
char mux6 = (((schedulerConf>>8) & 0xf) & 4) == 0;
char mux7 = (((schedulerConf>>4) & 0xf) & 2) != 0;
char mux8 = (((schedulerConf>>0) & 0xf) & 8) != 0;
char activations[8];
activations[0] = ((schedulerConf>>(4*3)) & 0xf) != 0;
activations[1] = ((schedulerConf>>(4*2)) & 0xf) != 0 && !mux6;
activations[2] = ((schedulerConf>>(4*1)) & 0xf) != 0 && !mux7;
activations[3] = ((schedulerConf>>(4*0)) & 0xf) != 0 && !mux8;
activations[4] = ((schedulerConf>>(4*7)) & 0xf) != 0;
activations[5] = ((schedulerConf>>(4*6)) & 0xf) != 0 || mux6;
activations[6] = ((schedulerConf>>(4*5)) & 0xf) != 0 || mux7;
activations[7] = ((schedulerConf>>(4*4)) & 0xf) != 0 || mux8;
char issueWidth = getIssueWidth(configuration);
char regFileControlBit = configuration>>4;
unsigned int immediateValue = activations[0]
+ (activations[1]<<1)
+ (activations[2]<<2)
+ (activations[3]<<3)
+ (activations[4]<<4)
+ (activations[5]<<5)
+ (activations[6]<<6)
+ (activations[7]<<7)
+ (mux6<<8)
+ (mux7<<9)
+ (mux8<<10)
+ (issueWidth<<11)
+ (regFileControlBit<<15);
return assembleIInstruction(VEX_RECONFFS, immediateValue, configuration);
}
char getNbMem(char configuration){
char memCode = (configuration >> 3) & 0x1;
return memCode + 1;
}
char getNbMult(char configuration){
char multCode = (configuration >> 1) & 0x3;
return multCode + 1;
}
float getPowerConsumption(char configuration){
char nbMem = getNbMem(configuration);
char nbMult = getNbMult(configuration);
char issueWidh = getIssueWidth(configuration);
float coef = 1;
if (configuration>=16)
coef = 1.5;
float powerConsumption = coef*issueWidh + (nbMem*2) + (nbMult);
return powerConsumption;
}
void setVLIWConfiguration(VexSimulator *simulator, char configuration){
unsigned int schedulerConf = getConfigurationForScheduler(configuration);
simulator->muxValues[0] = (((schedulerConf>>8) & 0xf) & 2) == 0;
simulator->muxValues[1] = (((schedulerConf>>4) & 0xf) & 2) != 0;
simulator->muxValues[2] = (((schedulerConf>>0) & 0xf) & 8) != 0;
simulator->unitActivation[0] = ((schedulerConf>>(4*3)) & 0xf) != 0;
simulator->unitActivation[1] = ((schedulerConf>>(4*2)) & 0xf) != 0 && !simulator->muxValues[0];
simulator->unitActivation[2] = ((schedulerConf>>(4*1)) & 0xf) != 0 && !simulator->muxValues[1];
simulator->unitActivation[3] = ((schedulerConf>>(4*0)) & 0xf) != 0 && !simulator->muxValues[2];
simulator->unitActivation[4] = ((schedulerConf>>(4*7)) & 0xf) != 0;
simulator->unitActivation[5] = ((schedulerConf>>(4*6)) & 0xf) != 0 || simulator->muxValues[0];
simulator->unitActivation[6] = ((schedulerConf>>(4*5)) & 0xf) != 0 || simulator->muxValues[1];
simulator->unitActivation[7] = ((schedulerConf>>(4*4)) & 0xf) != 0 || simulator->muxValues[2];
simulator->issueWidth = getIssueWidth(configuration);
char regFileControlBit = configuration>>4;
simulator->currentConfig = configuration;
}
void changeConfiguration(IRProcedure *procedure){
for (int oneValidConfiguration = 0; oneValidConfiguration < 12; oneValidConfiguration++){
char oneConfiguration = validConfigurations[oneValidConfiguration];
if (procedure->configurationScores[oneConfiguration] == 0){
fprintf(stderr, "Changing configuration from %d to %d\n", procedure->configuration, oneConfiguration);
procedure->previousConfiguration = procedure->configuration;
procedure->configuration = oneConfiguration;
return;
}
}
procedure->state = 1;
}
int computeScore(IRProcedure *procedure){
float result = 0;
for (int oneBlock = 0; oneBlock<procedure->nbBlock; oneBlock++){
IRBlock *block = procedure->blocks[oneBlock];
result += block->vliwEndAddress - block->vliwStartAddress;
}
if (getIssueWidth(procedure->configuration) > 4)
result = result/2;
result = 100000 / (result*getPowerConsumption(procedure->configuration));
fprintf(stderr, "Configuration with %x is %f\n", procedure->configuration, result);
return (int) result;
}
int suggestConfiguration(IRProcedure *originalProc, IRProcedure *newlyScheduledProc){
char currentConf = newlyScheduledProc->configuration;
int nbInstr = getNbInstr(originalProc);
int nbMult = getNbInstr(originalProc, 3);
int nbMem = getNbInstr(originalProc, 1);
fprintf(stderr, "\n\nConfiguration with %x \n", newlyScheduledProc->configuration);
int size = 0;
for (int oneBlock = 0; oneBlock<newlyScheduledProc->nbBlock; oneBlock++){
IRBlock *block = newlyScheduledProc->blocks[oneBlock];
size += block->vliwEndAddress - block->vliwStartAddress;
}
if (getIssueWidth(newlyScheduledProc->configuration) > 4)
size = size / 2;
int ressourceMult = getNbMult(newlyScheduledProc->configuration);
int ressourceMem = getNbMult(newlyScheduledProc->configuration);
int ressourceInstr = getIssueWidth(newlyScheduledProc->configuration);
fprintf(stderr, "schedule size is %d procedure has %d insructions, %d mem, %d mult\n", size, nbInstr,nbMem, nbMult);
float scoreMult = 1.0 * nbMult / (size * ressourceMult);
float scoreMem = 1.0 * nbMem / (size * ressourceMem);
float scoreSimple = 1.0 * nbInstr / (size * ressourceInstr);
fprintf(stderr, "Scores for suggestion are %f %f %f\n", scoreMult, scoreMem, scoreSimple);
char confLowerPerf = -1, confHigherPerf = -1;
if (scoreMult < scoreMem && scoreMult < scoreSimple){
//score mult is the minimal
if (nbMult > 1)
confLowerPerf = currentConf - 2;
else if (scoreMem < scoreSimple){
if (nbMem > 1)
confLowerPerf = currentConf - 8;
}
else{
if (currentConf & 0x1)
confLowerPerf = currentConf & 0x1e;
}
}
else if (scoreMem < scoreMult && scoreMem < scoreSimple){
//score mem is the minimal
if (nbMem > 1)
confLowerPerf = currentConf - 8;
else if (scoreMult < scoreSimple){
if (nbMult > 1)
confLowerPerf = currentConf - 2;
}
else{
if (currentConf & 0x1)
confLowerPerf = currentConf & 0x1e;
}
}
else {
//Score simple is the minimal
if (currentConf & 0x1)
confLowerPerf = currentConf & 0x1e;
}
fprintf(stderr, "Conf %x goes to %x\n", currentConf, confLowerPerf);
}
<commit_msg>Remove prints and corrected a configuration for scheduler<commit_after>/*
* reconfigureVLIW.cpp
*
* Created on: 9 févr. 2017
* Author: simon
*/
#include <isa/vexISA.h>
#include <transformation/reconfigureVLIW.h>
unsigned int schedulerConfigurations[16] = {0x00005e00,0x0000546c,0x00005ec4,0x006c54c4,0x00005ecc,0x040c5ec4,0,0,
0x00005e64,0x44605e04,0x00005e6c,0x40605ec4,0x006c5ec4,0x446c5ec4,0,0};
char validConfigurations[12] = {0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12 ,13};
char getIssueWidth(char configuration){
//This function returns the issue width of each configuration code
//We extract variables
char regCode = (configuration >> 4) & 0x1;
char memCode = (configuration >> 3) & 0x1;
char multCode = (configuration >> 1) & 0x3;
char boostCode = configuration & 0x1;
//Sum resources of mem and mult and round to the upper even number (this is the or)
char issueWidth = (memCode + multCode + 2);
if (issueWidth & 0x1)
issueWidth++;
//If boost code then it is the version with increased issue width
if (boostCode)
issueWidth += 2;
return issueWidth;
}
unsigned int getConfigurationForScheduler(char configuration){
return schedulerConfigurations[configuration % 16];
}
unsigned int getReconfigurationInstruction(char configuration){
unsigned int schedulerConf = getConfigurationForScheduler(configuration);
char mux6 = (((schedulerConf>>8) & 0xf) & 4) == 0;
char mux7 = (((schedulerConf>>4) & 0xf) & 2) != 0;
char mux8 = (((schedulerConf>>0) & 0xf) & 8) != 0;
char activations[8];
activations[0] = ((schedulerConf>>(4*3)) & 0xf) != 0;
activations[1] = ((schedulerConf>>(4*2)) & 0xf) != 0 && !mux6;
activations[2] = ((schedulerConf>>(4*1)) & 0xf) != 0 && !mux7;
activations[3] = ((schedulerConf>>(4*0)) & 0xf) != 0 && !mux8;
activations[4] = ((schedulerConf>>(4*7)) & 0xf) != 0;
activations[5] = ((schedulerConf>>(4*6)) & 0xf) != 0 || mux6;
activations[6] = ((schedulerConf>>(4*5)) & 0xf) != 0 || mux7;
activations[7] = ((schedulerConf>>(4*4)) & 0xf) != 0 || mux8;
char issueWidth = getIssueWidth(configuration);
char regFileControlBit = configuration>>4;
unsigned int immediateValue = activations[0]
+ (activations[1]<<1)
+ (activations[2]<<2)
+ (activations[3]<<3)
+ (activations[4]<<4)
+ (activations[5]<<5)
+ (activations[6]<<6)
+ (activations[7]<<7)
+ (mux6<<8)
+ (mux7<<9)
+ (mux8<<10)
+ (issueWidth<<11)
+ (regFileControlBit<<15);
return assembleIInstruction(VEX_RECONFFS, immediateValue, configuration);
}
char getNbMem(char configuration){
char memCode = (configuration >> 3) & 0x1;
return memCode + 1;
}
char getNbMult(char configuration){
char multCode = (configuration >> 1) & 0x3;
return multCode + 1;
}
float getPowerConsumption(char configuration){
char nbMem = getNbMem(configuration);
char nbMult = getNbMult(configuration);
char issueWidh = getIssueWidth(configuration);
float coef = 1;
if (configuration>=16)
coef = 1.5;
float powerConsumption = coef*issueWidh + (nbMem*2) + (nbMult);
return powerConsumption;
}
void setVLIWConfiguration(VexSimulator *simulator, char configuration){
unsigned int schedulerConf = getConfigurationForScheduler(configuration);
simulator->muxValues[0] = (((schedulerConf>>8) & 0xf) & 2) == 0;
simulator->muxValues[1] = (((schedulerConf>>4) & 0xf) & 2) != 0;
simulator->muxValues[2] = (((schedulerConf>>0) & 0xf) & 8) != 0;
simulator->unitActivation[0] = ((schedulerConf>>(4*3)) & 0xf) != 0;
simulator->unitActivation[1] = ((schedulerConf>>(4*2)) & 0xf) != 0 && !simulator->muxValues[0];
simulator->unitActivation[2] = ((schedulerConf>>(4*1)) & 0xf) != 0 && !simulator->muxValues[1];
simulator->unitActivation[3] = ((schedulerConf>>(4*0)) & 0xf) != 0 && !simulator->muxValues[2];
simulator->unitActivation[4] = ((schedulerConf>>(4*7)) & 0xf) != 0;
simulator->unitActivation[5] = ((schedulerConf>>(4*6)) & 0xf) != 0 || simulator->muxValues[0];
simulator->unitActivation[6] = ((schedulerConf>>(4*5)) & 0xf) != 0 || simulator->muxValues[1];
simulator->unitActivation[7] = ((schedulerConf>>(4*4)) & 0xf) != 0 || simulator->muxValues[2];
simulator->issueWidth = getIssueWidth(configuration);
char regFileControlBit = configuration>>4;
simulator->currentConfig = configuration;
}
void changeConfiguration(IRProcedure *procedure){
for (int oneValidConfiguration = 0; oneValidConfiguration < 12; oneValidConfiguration++){
char oneConfiguration = validConfigurations[oneValidConfiguration];
if (procedure->configurationScores[oneConfiguration] == 0){
fprintf(stderr, "Changing configuration from %d to %d\n", procedure->configuration, oneConfiguration);
procedure->previousConfiguration = procedure->configuration;
procedure->configuration = oneConfiguration;
return;
}
}
procedure->state = 1;
}
int computeScore(IRProcedure *procedure){
float result = 0;
for (int oneBlock = 0; oneBlock<procedure->nbBlock; oneBlock++){
IRBlock *block = procedure->blocks[oneBlock];
result += block->vliwEndAddress - block->vliwStartAddress;
}
if (getIssueWidth(procedure->configuration) > 4)
result = result/2;
result = 100000 / result;
fprintf(stderr, "Configuration with %x is %f\n", procedure->configuration, result);
return (int) result;
}
int suggestConfiguration(IRProcedure *originalProc, IRProcedure *newlyScheduledProc){
char currentConf = newlyScheduledProc->configuration;
int nbInstr = getNbInstr(originalProc);
int nbMult = getNbInstr(originalProc, 3);
int nbMem = getNbInstr(originalProc, 1);
int size = 0;
for (int oneBlock = 0; oneBlock<newlyScheduledProc->nbBlock; oneBlock++){
IRBlock *block = newlyScheduledProc->blocks[oneBlock];
size += block->vliwEndAddress - block->vliwStartAddress;
}
if (getIssueWidth(newlyScheduledProc->configuration) > 4)
size = size / 2;
int ressourceMult = getNbMult(newlyScheduledProc->configuration);
int ressourceMem = getNbMult(newlyScheduledProc->configuration);
int ressourceInstr = getIssueWidth(newlyScheduledProc->configuration);
float scoreMult = 1.0 * nbMult / (size * ressourceMult);
float scoreMem = 1.0 * nbMem / (size * ressourceMem);
float scoreSimple = 1.0 * nbInstr / (size * ressourceInstr);
//fprintf(stderr, "Scores for suggestion are %f %f %f\n", scoreMult, scoreMem, scoreSimple);
char confLowerPerf = -1, confHigherPerf = -1;
if (scoreMult < scoreMem && scoreMult < scoreSimple){
//score mult is the minimal
if (nbMult > 1)
confLowerPerf = currentConf - 2;
else if (scoreMem < scoreSimple){
if (nbMem > 1)
confLowerPerf = currentConf - 8;
}
else{
if (currentConf & 0x1)
confLowerPerf = currentConf & 0x1e;
}
}
else if (scoreMem < scoreMult && scoreMem < scoreSimple){
//score mem is the minimal
if (nbMem > 1)
confLowerPerf = currentConf - 8;
else if (scoreMult < scoreSimple){
if (nbMult > 1)
confLowerPerf = currentConf - 2;
}
else{
if (currentConf & 0x1)
confLowerPerf = currentConf & 0x1e;
}
}
else {
//Score simple is the minimal
if (currentConf & 0x1)
confLowerPerf = currentConf & 0x1e;
}
//fprintf(stderr, "Conf %x goes to %x\n", currentConf, confLowerPerf);
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2002-2010 The ANGLE 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.
//
//
// This file contains the posix specific functions
//
#include "compiler/osinclude.h"
#if !defined(ANGLE_OS_POSIX)
#error Trying to build a posix specific file in a non-posix build.
#endif
//
// Thread Local Storage Operations
//
OS_TLSIndex OS_AllocTLSIndex()
{
pthread_key_t pPoolIndex;
//
// Create global pool key.
//
if ((pthread_key_create(&pPoolIndex, NULL)) != 0) {
assert(0 && "OS_AllocTLSIndex(): Unable to allocate Thread Local Storage");
return false;
}
else {
return pPoolIndex;
}
}
bool OS_SetTLSValue(OS_TLSIndex nIndex, void *lpvValue)
{
if (nIndex == OS_INVALID_TLS_INDEX) {
assert(0 && "OS_SetTLSValue(): Invalid TLS Index");
return false;
}
if (pthread_setspecific(nIndex, lpvValue) == 0)
return true;
else
return false;
}
bool OS_FreeTLSIndex(OS_TLSIndex nIndex)
{
if (nIndex == OS_INVALID_TLS_INDEX) {
assert(0 && "OS_SetTLSValue(): Invalid TLS Index");
return false;
}
//
// Delete the global pool key.
//
if (pthread_key_delete(nIndex) == 0)
return true;
else
return false;
}
<commit_msg>Fix incorrect include on posix systems.<commit_after>//
// Copyright (c) 2002-2010 The ANGLE 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.
//
//
// This file contains the posix specific functions
//
#include "compiler/translator/osinclude.h"
#if !defined(ANGLE_OS_POSIX)
#error Trying to build a posix specific file in a non-posix build.
#endif
//
// Thread Local Storage Operations
//
OS_TLSIndex OS_AllocTLSIndex()
{
pthread_key_t pPoolIndex;
//
// Create global pool key.
//
if ((pthread_key_create(&pPoolIndex, NULL)) != 0) {
assert(0 && "OS_AllocTLSIndex(): Unable to allocate Thread Local Storage");
return false;
}
else {
return pPoolIndex;
}
}
bool OS_SetTLSValue(OS_TLSIndex nIndex, void *lpvValue)
{
if (nIndex == OS_INVALID_TLS_INDEX) {
assert(0 && "OS_SetTLSValue(): Invalid TLS Index");
return false;
}
if (pthread_setspecific(nIndex, lpvValue) == 0)
return true;
else
return false;
}
bool OS_FreeTLSIndex(OS_TLSIndex nIndex)
{
if (nIndex == OS_INVALID_TLS_INDEX) {
assert(0 && "OS_SetTLSValue(): Invalid TLS Index");
return false;
}
//
// Delete the global pool key.
//
if (pthread_key_delete(nIndex) == 0)
return true;
else
return false;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* 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 <znc/User.h>
#include <znc/IRCNetwork.h>
#include <time.h>
#define SIMPLE_AWAY_DEFAULT_REASON "Auto away at %awaytime%"
#define SIMPLE_AWAY_DEFAULT_TIME 60
class CSimpleAway;
class CSimpleAwayJob : public CTimer {
public:
CSimpleAwayJob(CModule* pModule, unsigned int uInterval,
unsigned int uCycles, const CString& sLabel,
const CString& sDescription)
: CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {}
~CSimpleAwayJob() override {}
protected:
void RunJob() override;
};
class CSimpleAway : public CModule {
private:
CString m_sReason;
unsigned int m_iAwayWait;
unsigned int m_iMinClients;
bool m_bClientSetAway;
bool m_bWeSetAway;
public:
MODCONSTRUCTOR(CSimpleAway) {
m_sReason = SIMPLE_AWAY_DEFAULT_REASON;
m_iAwayWait = SIMPLE_AWAY_DEFAULT_TIME;
m_iMinClients = 1;
m_bClientSetAway = false;
m_bWeSetAway = false;
AddHelpCommand();
AddCommand("Reason", t_d("[<text>]"),
t_d("Prints or sets the away reason (%awaytime% is replaced "
"with the time you were set away, supports "
"substitutions using ExpandString)"),
[=](const CString& sLine) { OnReasonCommand(sLine); });
AddCommand(
"Timer", "",
t_d("Prints the current time to wait before setting you away"),
[=](const CString& sLine) { OnTimerCommand(sLine); });
AddCommand("SetTimer", t_d("<seconds>"),
t_d("Sets the time to wait before setting you away"),
[=](const CString& sLine) { OnSetTimerCommand(sLine); });
AddCommand("DisableTimer", "",
t_d("Disables the wait time before setting you away"),
[=](const CString& sLine) { OnDisableTimerCommand(sLine); });
AddCommand(
"MinClients", "",
t_d("Get or set the minimum number of clients before going away"),
[=](const CString& sLine) { OnMinClientsCommand(sLine); });
}
~CSimpleAway() override {}
bool OnLoad(const CString& sArgs, CString& sMessage) override {
CString sReasonArg;
// Load AwayWait
CString sFirstArg = sArgs.Token(0);
if (sFirstArg.Equals("-notimer")) {
SetAwayWait(0);
sReasonArg = sArgs.Token(1, true);
} else if (sFirstArg.Equals("-timer")) {
SetAwayWait(sArgs.Token(1).ToUInt());
sReasonArg = sArgs.Token(2, true);
} else {
CString sAwayWait = GetNV("awaywait");
if (!sAwayWait.empty()) SetAwayWait(sAwayWait.ToUInt(), false);
sReasonArg = sArgs;
}
// Load Reason
if (!sReasonArg.empty()) {
SetReason(sReasonArg);
} else {
CString sSavedReason = GetNV("reason");
if (!sSavedReason.empty()) SetReason(sSavedReason, false);
}
// MinClients
CString sMinClients = GetNV("minclients");
if (!sMinClients.empty()) SetMinClients(sMinClients.ToUInt(), false);
// Set away on load, required if loaded via webadmin
if (GetNetwork()->IsIRCConnected() && MinClientsConnected())
SetAway(false);
return true;
}
void OnIRCConnected() override {
if (MinClientsConnected())
SetBack();
else
SetAway(false);
}
void OnClientLogin() override {
if (MinClientsConnected()) SetBack();
}
void OnClientDisconnect() override {
/* There might still be other clients */
if (!MinClientsConnected()) SetAway();
}
void OnReasonCommand(const CString& sLine) {
CString sReason = sLine.Token(1, true);
if (!sReason.empty()) {
SetReason(sReason);
PutModule(t_s("Away reason set"));
} else {
PutModule(t_f("Away reason: {1}")(m_sReason));
PutModule(t_f("Current away reason would be: {1}")(ExpandReason()));
}
}
void OnTimerCommand(const CString& sLine) {
PutModule(t_p("Current timer setting: 1 second",
"Current timer setting: {1} seconds",
m_iAwayWait)(m_iAwayWait));
}
void OnSetTimerCommand(const CString& sLine) {
SetAwayWait(sLine.Token(1).ToUInt());
if (m_iAwayWait == 0)
PutModule(t_s("Timer disabled"));
else
PutModule(t_p("Timer set to 1 second", "Timer set to: {1} seconds",
m_iAwayWait)(m_iAwayWait));
}
void OnDisableTimerCommand(const CString& sLine) {
SetAwayWait(0);
PutModule(t_s("Timer disabled"));
}
void OnMinClientsCommand(const CString& sLine) {
if (sLine.Token(1).empty()) {
PutModule(t_f("Current MinClients setting: {1}")(m_iMinClients));
} else {
SetMinClients(sLine.Token(1).ToUInt());
PutModule(t_f("MinClients set to {1}")(m_iMinClients));
}
}
EModRet OnUserRawMessage(CMessage& msg) override {
if (!msg.GetCommand().Equals("AWAY")) return CONTINUE;
// If a client set us away, we don't touch that away message
m_bClientSetAway = !msg.GetParam(0).Trim_n(" ").empty();
m_bWeSetAway = false;
return CONTINUE;
}
void SetAway(bool bTimer = true) {
if (bTimer) {
RemTimer("simple_away");
AddTimer(new CSimpleAwayJob(this, m_iAwayWait, 1, "simple_away",
"Sets you away after detach"));
} else {
if (!m_bClientSetAway) {
PutIRC("AWAY :" + ExpandReason());
m_bWeSetAway = true;
}
}
}
void SetBack() {
RemTimer("simple_away");
if (m_bWeSetAway) {
PutIRC("AWAY");
m_bWeSetAway = false;
}
}
private:
bool MinClientsConnected() {
return GetNetwork()->GetClients().size() >= m_iMinClients;
}
CString ExpandReason() {
CString sReason = m_sReason;
if (sReason.empty()) sReason = SIMPLE_AWAY_DEFAULT_REASON;
time_t iTime = time(nullptr);
CString sTime = CUtils::CTime(iTime, GetUser()->GetTimezone());
sReason.Replace("%awaytime%", sTime);
sReason = ExpandString(sReason);
sReason.Replace("%s", sTime); // Backwards compatibility with previous
// syntax, where %s was substituted with
// sTime. ZNC <= 1.6.x
return sReason;
}
/* Settings */
void SetReason(CString& sReason, bool bSave = true) {
if (bSave) SetNV("reason", sReason);
m_sReason = sReason;
}
void SetAwayWait(unsigned int iAwayWait, bool bSave = true) {
if (bSave) SetNV("awaywait", CString(iAwayWait));
m_iAwayWait = iAwayWait;
}
void SetMinClients(unsigned int iMinClients, bool bSave = true) {
if (bSave) SetNV("minclients", CString(iMinClients));
m_iMinClients = iMinClients;
}
};
void CSimpleAwayJob::RunJob() { ((CSimpleAway*)GetModule())->SetAway(false); }
template <>
void TModInfo<CSimpleAway>(CModInfo& Info) {
Info.SetWikiPage("simple_away");
Info.SetHasArgs(true);
Info.SetArgsHelpText(
Info.t_s("You might enter up to 3 arguments, like -notimer awaymessage "
"or -timer 5 awaymessage."));
}
NETWORKMODULEDEFS(CSimpleAway,
t_s("This module will automatically set you away on IRC "
"while you are disconnected from the bouncer."))
<commit_msg>simple_away: Convert to UTC time<commit_after>/*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* 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 <znc/User.h>
#include <znc/IRCNetwork.h>
#include <time.h>
#define SIMPLE_AWAY_DEFAULT_REASON "Auto away at %awaytime%"
#define SIMPLE_AWAY_DEFAULT_TIME 60
class CSimpleAway;
class CSimpleAwayJob : public CTimer {
public:
CSimpleAwayJob(CModule* pModule, unsigned int uInterval,
unsigned int uCycles, const CString& sLabel,
const CString& sDescription)
: CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {}
~CSimpleAwayJob() override {}
protected:
void RunJob() override;
};
class CSimpleAway : public CModule {
private:
CString m_sReason;
unsigned int m_iAwayWait;
unsigned int m_iMinClients;
bool m_bClientSetAway;
bool m_bWeSetAway;
public:
MODCONSTRUCTOR(CSimpleAway) {
m_sReason = SIMPLE_AWAY_DEFAULT_REASON;
m_iAwayWait = SIMPLE_AWAY_DEFAULT_TIME;
m_iMinClients = 1;
m_bClientSetAway = false;
m_bWeSetAway = false;
AddHelpCommand();
AddCommand("Reason", t_d("[<text>]"),
t_d("Prints or sets the away reason (%awaytime% is replaced "
"with the time you were set away, supports "
"substitutions using ExpandString)"),
[=](const CString& sLine) { OnReasonCommand(sLine); });
AddCommand(
"Timer", "",
t_d("Prints the current time to wait before setting you away"),
[=](const CString& sLine) { OnTimerCommand(sLine); });
AddCommand("SetTimer", t_d("<seconds>"),
t_d("Sets the time to wait before setting you away"),
[=](const CString& sLine) { OnSetTimerCommand(sLine); });
AddCommand("DisableTimer", "",
t_d("Disables the wait time before setting you away"),
[=](const CString& sLine) { OnDisableTimerCommand(sLine); });
AddCommand(
"MinClients", "",
t_d("Get or set the minimum number of clients before going away"),
[=](const CString& sLine) { OnMinClientsCommand(sLine); });
}
~CSimpleAway() override {}
bool OnLoad(const CString& sArgs, CString& sMessage) override {
CString sReasonArg;
// Load AwayWait
CString sFirstArg = sArgs.Token(0);
if (sFirstArg.Equals("-notimer")) {
SetAwayWait(0);
sReasonArg = sArgs.Token(1, true);
} else if (sFirstArg.Equals("-timer")) {
SetAwayWait(sArgs.Token(1).ToUInt());
sReasonArg = sArgs.Token(2, true);
} else {
CString sAwayWait = GetNV("awaywait");
if (!sAwayWait.empty()) SetAwayWait(sAwayWait.ToUInt(), false);
sReasonArg = sArgs;
}
// Load Reason
if (!sReasonArg.empty()) {
SetReason(sReasonArg);
} else {
CString sSavedReason = GetNV("reason");
if (!sSavedReason.empty()) SetReason(sSavedReason, false);
}
// MinClients
CString sMinClients = GetNV("minclients");
if (!sMinClients.empty()) SetMinClients(sMinClients.ToUInt(), false);
// Set away on load, required if loaded via webadmin
if (GetNetwork()->IsIRCConnected() && MinClientsConnected())
SetAway(false);
return true;
}
void OnIRCConnected() override {
if (MinClientsConnected())
SetBack();
else
SetAway(false);
}
void OnClientLogin() override {
if (MinClientsConnected()) SetBack();
}
void OnClientDisconnect() override {
/* There might still be other clients */
if (!MinClientsConnected()) SetAway();
}
void OnReasonCommand(const CString& sLine) {
CString sReason = sLine.Token(1, true);
if (!sReason.empty()) {
SetReason(sReason);
PutModule(t_s("Away reason set"));
} else {
PutModule(t_f("Away reason: {1}")(m_sReason));
PutModule(t_f("Current away reason would be: {1}")(ExpandReason()));
}
}
void OnTimerCommand(const CString& sLine) {
PutModule(t_p("Current timer setting: 1 second",
"Current timer setting: {1} seconds",
m_iAwayWait)(m_iAwayWait));
}
void OnSetTimerCommand(const CString& sLine) {
SetAwayWait(sLine.Token(1).ToUInt());
if (m_iAwayWait == 0)
PutModule(t_s("Timer disabled"));
else
PutModule(t_p("Timer set to 1 second", "Timer set to: {1} seconds",
m_iAwayWait)(m_iAwayWait));
}
void OnDisableTimerCommand(const CString& sLine) {
SetAwayWait(0);
PutModule(t_s("Timer disabled"));
}
void OnMinClientsCommand(const CString& sLine) {
if (sLine.Token(1).empty()) {
PutModule(t_f("Current MinClients setting: {1}")(m_iMinClients));
} else {
SetMinClients(sLine.Token(1).ToUInt());
PutModule(t_f("MinClients set to {1}")(m_iMinClients));
}
}
EModRet OnUserRawMessage(CMessage& msg) override {
if (!msg.GetCommand().Equals("AWAY")) return CONTINUE;
// If a client set us away, we don't touch that away message
m_bClientSetAway = !msg.GetParam(0).Trim_n(" ").empty();
m_bWeSetAway = false;
return CONTINUE;
}
void SetAway(bool bTimer = true) {
if (bTimer) {
RemTimer("simple_away");
AddTimer(new CSimpleAwayJob(this, m_iAwayWait, 1, "simple_away",
"Sets you away after detach"));
} else {
if (!m_bClientSetAway) {
PutIRC("AWAY :" + ExpandReason());
m_bWeSetAway = true;
}
}
}
void SetBack() {
RemTimer("simple_away");
if (m_bWeSetAway) {
PutIRC("AWAY");
m_bWeSetAway = false;
}
}
private:
bool MinClientsConnected() {
return GetNetwork()->GetClients().size() >= m_iMinClients;
}
CString ExpandReason() {
CString sReason = m_sReason;
if (sReason.empty()) sReason = SIMPLE_AWAY_DEFAULT_REASON;
time_t iTime = time(nullptr);
CString sTime = CUtils::CTime(iTime, "Etc/UTC") + " UTC";
sReason.Replace("%awaytime%", sTime);
sReason = ExpandString(sReason);
sReason.Replace("%s", sTime); // Backwards compatibility with previous
// syntax, where %s was substituted with
// sTime. ZNC <= 1.6.x
return sReason;
}
/* Settings */
void SetReason(CString& sReason, bool bSave = true) {
if (bSave) SetNV("reason", sReason);
m_sReason = sReason;
}
void SetAwayWait(unsigned int iAwayWait, bool bSave = true) {
if (bSave) SetNV("awaywait", CString(iAwayWait));
m_iAwayWait = iAwayWait;
}
void SetMinClients(unsigned int iMinClients, bool bSave = true) {
if (bSave) SetNV("minclients", CString(iMinClients));
m_iMinClients = iMinClients;
}
};
void CSimpleAwayJob::RunJob() { ((CSimpleAway*)GetModule())->SetAway(false); }
template <>
void TModInfo<CSimpleAway>(CModInfo& Info) {
Info.SetWikiPage("simple_away");
Info.SetHasArgs(true);
Info.SetArgsHelpText(
Info.t_s("You might enter up to 3 arguments, like -notimer awaymessage "
"or -timer 5 awaymessage."));
}
NETWORKMODULEDEFS(CSimpleAway,
t_s("This module will automatically set you away on IRC "
"while you are disconnected from the bouncer."))
<|endoftext|> |
<commit_before>//
// main.cpp
// DataLogger
//
// Created by Emmanuel Silva on 6/15/14.
// Copyright (c) 2014 Emmanuel Silva. All rights reserved.
//
#include <iostream>
#include "SchedulerReadTask.h"
int main(int argc, const char * argv[])
{
SchedulerReadTask scheduler(60, 10); //nos proximos 60 segundos de 10 em 10 segundos
scheduler.start();
return 0;
}
<commit_msg>Teste para validar git<commit_after>//
// main.cpp
// DataLogger
//
// Created by Emmanuel Silva on 6/15/14.
// Copyright (c) 2014 Emmanuel Silva. All rights reserved.
//
#include <iostream>
#include "SchedulerReadTask.h"
int main(int argc, const char * argv[])
{
SchedulerReadTask scheduler(60, 10); //nos proximos 60 segundos de 10 em 10 segundos
scheduler.start();
//teste
return 0;
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 "stdafx.h"
#include "NativeJIT/CodeGen/ExecutionBuffer.h"
#include "NativeJIT/CodeGen/FunctionBuffer.h"
#include "NativeJIT/Function.h"
#include "Temporary/Allocator.h"
#include "TestSetup.h"
namespace NativeJIT
{
namespace UnsignedUnitTest
{
TEST_FIXTURE_START(Unsigned)
TEST_FIXTURE_END_TEST_CASES_BEGIN
//
// TODO:
// Signed vs unsigned
//
//
// Immediate values
//
// TODO: cases for (signed, unsigned) x (1, 2, 4, 8), float
TEST_CASE_F(Unsigned, ImmediateU64)
{
auto setup = GetSetup();
{
Function<uint64_t> expression(setup->GetAllocator(), setup->GetCode());
uint64_t value = 0x1234ull;
auto & a = expression.Immediate(value);
auto function = expression.Compile(a);
auto expected = value;
auto observed = function();
TestAssert(observed == expected);
}
}
//
// FieldPointer
//
#pragma pack(push, 1)
class InnerClass
{
public:
uint32_t m_a;
uint64_t m_b;
};
class OuterClass
{
public:
uint16_t m_p;
InnerClass* m_innerPointer;
InnerClass m_innerEmbedded;
int64_t m_q;
};
#pragma pack(pop)
TEST_CASE_F(Unsigned, FieldPointerPrimitive)
{
auto setup = GetSetup();
{
Function<uint64_t, InnerClass*> expression(setup->GetAllocator(), setup->GetCode());
auto & a = expression.GetP1();
auto & b = expression.FieldPointer(a, &InnerClass::m_b);
auto & c = expression.Deref(b);
auto function = expression.Compile(c);
InnerClass innerClass;
innerClass.m_b = 1234ull;
InnerClass* p1 = &innerClass;
auto expected = p1->m_b;
auto observed = function(p1);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, FieldPointerEmbedded)
{
auto setup = GetSetup();
{
Function<uint64_t, OuterClass**> expression(setup->GetAllocator(), setup->GetCode());
const unsigned pointersIndex = 4;
auto & outerPtrs = expression.GetP1();
auto & outerPtr = expression.Deref(outerPtrs, pointersIndex);
auto & inner = expression.FieldPointer(outerPtr, &OuterClass::m_innerEmbedded);
auto & innerBPtr = expression.FieldPointer(inner, &InnerClass::m_b);
auto & innerB = expression.Deref(innerBPtr);
auto function = expression.Compile(innerB);
OuterClass outerClass;
outerClass.m_innerEmbedded.m_b = 2345ull;
OuterClass* p1Ptrs[pointersIndex + 1] = { nullptr };
p1Ptrs[pointersIndex] = &outerClass;
OuterClass** p1 = &p1Ptrs[0];
auto expected = p1[pointersIndex]->m_innerEmbedded.m_b;
auto observed = function(p1);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, FieldPointerEmbeddedWithCommonSubexpression)
{
auto setup = GetSetup();
{
Function<uint64_t, OuterClass*> e(setup->GetAllocator(), setup->GetCode());
// The inner variable has a single FieldPointer parent (the
// outer parameter) and it is a common parent to both innerA
// and innerB FieldPointers into the same object. Given that
// FieldPointerNode has optimization related to collapsing
// nested accesses to the same object, this test is meant
// to implicitly ensure that cache references are set correctly
// and that evaluations are done the expected number of times.
auto & inner = e.FieldPointer(e.GetP1(), &OuterClass::m_innerEmbedded);
auto & innerA = e.Deref(e.FieldPointer(inner, &InnerClass::m_a));
auto & innerB = e.Deref(e.FieldPointer(inner, &InnerClass::m_b));
auto & sum = e.Add(e.Cast<uint64_t>(innerA),
innerB);
auto function = e.Compile(sum);
OuterClass outerClass;
outerClass.m_innerEmbedded.m_a = 10;
outerClass.m_innerEmbedded.m_b = 1;
auto expected = outerClass.m_innerEmbedded.m_a
+ outerClass.m_innerEmbedded.m_b;
auto observed = function(&outerClass);
TestEqual(expected, observed);
}
}
//
// Binary operations
//
TEST_CASE_F(Unsigned, AddUnsignedInt32)
{
auto setup = GetSetup();
{
Function<uint32_t, uint32_t, uint32_t> expression(setup->GetAllocator(), setup->GetCode());
auto & a = expression.Add(expression.GetP2(), expression.GetP1());
auto function = expression.Compile(a);
uint32_t p1 = 12340000ul;
uint32_t p2 = 5678ul;
auto expected = p1 + p2;
auto observed = function(p1, p2);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, MulUnsignedInt32)
{
auto setup = GetSetup();
{
Function<uint32_t, uint32_t, uint32_t> expression(setup->GetAllocator(), setup->GetCode());
auto & a = expression.Mul(expression.GetP2(), expression.GetP1());
auto function = expression.Compile(a);
uint32_t p1 = 12340000ul;
uint32_t p2 = 5678ul;
auto expected = p1 * p2;
auto observed = function(p1, p2);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, SubUnsignedInt32)
{
auto setup = GetSetup();
{
Function<uint32_t, uint32_t, uint32_t> expression(setup->GetAllocator(), setup->GetCode());
auto & a = expression.Sub(expression.GetP2(), expression.GetP1());
auto function = expression.Compile(a);
uint32_t p1 = 12340000ul;
uint32_t p2 = 5678ul;
auto expected = p2 - p1;
auto observed = function(p1, p2);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, ShlUnsignedInt32)
{
auto setup = GetSetup();
{
Function<uint32_t, uint32_t, uint32_t> expression(setup->GetAllocator(), setup->GetCode());
uint32_t p2 = 3ul;
auto & a = expression.Shl(expression.GetP1(), p2);
auto function = expression.Compile(a);
uint32_t p1 = 1ul;
auto expected = p1 << p2;
auto observed = function(p1, p2);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, ShrUnsignedInt32)
{
auto setup = GetSetup();
{
Function<uint32_t, uint32_t, uint32_t> expression(setup->GetAllocator(), setup->GetCode());
uint32_t p2 = 3ul;
auto & a = expression.Shr(expression.GetP1(), p2);
auto function = expression.Compile(a);
uint32_t p1 = 0xffffffff;
auto expected = p1 >> p2;
auto observed = function(p1, p2);
TestAssert(observed == expected);
}
}
//
// Ternary operations
//
TEST_CASE_F(Unsigned, ShldUnsignedInt32)
{
auto setup = GetSetup();
{
Function<uint32_t, uint32_t, uint32_t, uint32_t> expression(setup->GetAllocator(), setup->GetCode());
uint32_t p3 = 4ul;
auto & a = expression.Shld(expression.GetP2(), expression.GetP1(), p3);
auto function = expression.Compile(a);
uint32_t p1 = 1ul;
uint32_t p2 = 3ul;
auto expected = p2 << p3;
auto observed = function(p1, p2, p3);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, ShldPairUnsignedInt32)
{
auto setup = GetSetup();
{
Function<uint32_t, uint32_t, uint32_t, uint32_t> expression(setup->GetAllocator(), setup->GetCode());
uint32_t p3 = 4ul;
auto & a = expression.Shld(expression.GetP2(), expression.GetP1(), p3);
auto function = expression.Compile(a);
uint32_t p1 = 0xaaaaaaaa;
uint32_t p2 = 3ul;
auto expected = p2 << p3 | (p1 & 0xf);
auto observed = function(p1, p2, p3);
TestAssert(observed == expected);
}
}
//
// Array indexing
//
TEST_CASE_F(Unsigned, ArrayOfIntAsPointer)
{
auto setup = GetSetup();
{
Function<uint64_t, uint64_t*> expression(setup->GetAllocator(), setup->GetCode());
auto & a = expression.Add(expression.GetP1(), expression.Immediate<uint64_t>(1ull));
auto & b = expression.Add(expression.GetP1(), expression.Immediate<uint64_t>(2ull));
auto & c = expression.Add(expression.Deref(a), expression.Deref(b));
auto function = expression.Compile(c);
uint64_t array[10];
array[1] = 456;
array[2] = 123000;
uint64_t * p1 = array;
auto expected = array[1] + array[2];
auto observed = function(p1);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, ArrayOfInt)
{
auto setup = GetSetup();
{
struct S
{
uint64_t m_array[10];
};
Function<uint64_t, S*> e(setup->GetAllocator(), setup->GetCode());
auto & arrayPtr = e.FieldPointer(e.GetP1(), &S::m_array);
auto & left = e.Add(arrayPtr, e.Immediate(1));
auto & right = e.Add(arrayPtr, e.Immediate(2));
auto & sum = e.Add(e.Deref(left), e.Deref(right));
auto function = e.Compile(sum);
struct S s;
s.m_array[1] = 456;
s.m_array[2] = 123000;
auto expected = s.m_array[1] + s.m_array[2];
auto observed = function(&s);
TestEqual(expected, observed);
}
}
TEST_CASE_F(Unsigned, ArrayOfClass)
{
auto setup = GetSetup();
{
Function<int64_t, OuterClass*, uint64_t> expression(setup->GetAllocator(), setup->GetCode());
auto & a = expression.Add(expression.GetP1(), expression.GetP2());
auto & b = expression.FieldPointer(a, &OuterClass::m_q);
auto & c = expression.Deref(b);
auto function = expression.Compile(c);
OuterClass array[10];
OuterClass* p1 = array;
uint64_t p2 = 3ull;
p1[p2].m_q = 0x0123456789ABCDEF;
auto expected = p1[p2].m_q;
auto observed = function(p1, p2);
TestAssert(observed == expected);
}
}
//
// Common sub expressions
//
TEST_CASE_F(Unsigned, CommonSubExpressions)
{
auto setup = GetSetup();
{
Function<int64_t, int64_t, int64_t> expression(setup->GetAllocator(), setup->GetCode());
// This tree has three common subexpressions: P1, P2, and node "a".
// Each common subexpression is referenced twice.
auto & a = expression.Add(expression.GetP1(), expression.GetP2());
auto & b = expression.Add(a, expression.GetP1());
// Perform this add after 2nd and last use of P1 to see if RCX is recycled.
auto & c = expression.Add(expression.Immediate(1ll), expression.Immediate(2ll));
auto & d = expression.Add(b, c);
auto & e = expression.Add(d, expression.GetP2());
// Perform this add after 2nd and last use of P2 to see if RDX is recycled.
auto & f = expression.Add(expression.Immediate(3ll), expression.Immediate(4ll));
auto & g = expression.Add(e, f);
auto & h = expression.Add(g, a);
// Perform this add after 2nd and last use of a to see if a's register is recycled.
auto & i = expression.Add(expression.Immediate(5ll), expression.Immediate(6ll));
auto & j = expression.Add(h, i);
auto function = expression.Compile(j);
int64_t p1 = 1ll;
int64_t p2 = 10ll;
auto expectedA = p1 + p2;
auto expectedB = expectedA + p1;
auto expectedC = 1ll + 2ll;
auto expectedD = expectedB + expectedC;
auto expectedE = expectedD + p2;
auto expectedF = 3ll + 4ll;
auto expectedG = expectedE + expectedF;
auto expectedH = expectedG + expectedA;
auto expectedI = 5ll + 6ll;
auto expected = expectedH + expectedI;
auto observed = function(p1, p2);
TestAssert(observed == expected);
}
}
TEST_CASES_END
}
}
<commit_msg>Make size match to avoid VC14 warning.<commit_after>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 "stdafx.h"
#include "NativeJIT/CodeGen/ExecutionBuffer.h"
#include "NativeJIT/CodeGen/FunctionBuffer.h"
#include "NativeJIT/Function.h"
#include "Temporary/Allocator.h"
#include "TestSetup.h"
namespace NativeJIT
{
namespace UnsignedUnitTest
{
TEST_FIXTURE_START(Unsigned)
TEST_FIXTURE_END_TEST_CASES_BEGIN
//
// TODO:
// Signed vs unsigned
//
//
// Immediate values
//
// TODO: cases for (signed, unsigned) x (1, 2, 4, 8), float
TEST_CASE_F(Unsigned, ImmediateU64)
{
auto setup = GetSetup();
{
Function<uint64_t> expression(setup->GetAllocator(), setup->GetCode());
uint64_t value = 0x1234ull;
auto & a = expression.Immediate(value);
auto function = expression.Compile(a);
auto expected = value;
auto observed = function();
TestAssert(observed == expected);
}
}
//
// FieldPointer
//
#pragma pack(push, 1)
class InnerClass
{
public:
uint32_t m_a;
uint64_t m_b;
};
class OuterClass
{
public:
uint16_t m_p;
InnerClass* m_innerPointer;
InnerClass m_innerEmbedded;
int64_t m_q;
};
#pragma pack(pop)
TEST_CASE_F(Unsigned, FieldPointerPrimitive)
{
auto setup = GetSetup();
{
Function<uint64_t, InnerClass*> expression(setup->GetAllocator(), setup->GetCode());
auto & a = expression.GetP1();
auto & b = expression.FieldPointer(a, &InnerClass::m_b);
auto & c = expression.Deref(b);
auto function = expression.Compile(c);
InnerClass innerClass;
innerClass.m_b = 1234ull;
InnerClass* p1 = &innerClass;
auto expected = p1->m_b;
auto observed = function(p1);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, FieldPointerEmbedded)
{
auto setup = GetSetup();
{
Function<uint64_t, OuterClass**> expression(setup->GetAllocator(), setup->GetCode());
const unsigned pointersIndex = 4;
auto & outerPtrs = expression.GetP1();
auto & outerPtr = expression.Deref(outerPtrs, pointersIndex);
auto & inner = expression.FieldPointer(outerPtr, &OuterClass::m_innerEmbedded);
auto & innerBPtr = expression.FieldPointer(inner, &InnerClass::m_b);
auto & innerB = expression.Deref(innerBPtr);
auto function = expression.Compile(innerB);
OuterClass outerClass;
outerClass.m_innerEmbedded.m_b = 2345ull;
OuterClass* p1Ptrs[pointersIndex + 1] = { nullptr };
p1Ptrs[pointersIndex] = &outerClass;
OuterClass** p1 = &p1Ptrs[0];
auto expected = p1[pointersIndex]->m_innerEmbedded.m_b;
auto observed = function(p1);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, FieldPointerEmbeddedWithCommonSubexpression)
{
auto setup = GetSetup();
{
Function<uint64_t, OuterClass*> e(setup->GetAllocator(), setup->GetCode());
// The inner variable has a single FieldPointer parent (the
// outer parameter) and it is a common parent to both innerA
// and innerB FieldPointers into the same object. Given that
// FieldPointerNode has optimization related to collapsing
// nested accesses to the same object, this test is meant
// to implicitly ensure that cache references are set correctly
// and that evaluations are done the expected number of times.
auto & inner = e.FieldPointer(e.GetP1(), &OuterClass::m_innerEmbedded);
auto & innerA = e.Deref(e.FieldPointer(inner, &InnerClass::m_a));
auto & innerB = e.Deref(e.FieldPointer(inner, &InnerClass::m_b));
auto & sum = e.Add(e.Cast<uint64_t>(innerA),
innerB);
auto function = e.Compile(sum);
OuterClass outerClass;
outerClass.m_innerEmbedded.m_a = 10;
outerClass.m_innerEmbedded.m_b = 1;
auto expected = outerClass.m_innerEmbedded.m_a
+ outerClass.m_innerEmbedded.m_b;
auto observed = function(&outerClass);
TestEqual(expected, observed);
}
}
//
// Binary operations
//
TEST_CASE_F(Unsigned, AddUnsignedInt32)
{
auto setup = GetSetup();
{
Function<uint32_t, uint32_t, uint32_t> expression(setup->GetAllocator(), setup->GetCode());
auto & a = expression.Add(expression.GetP2(), expression.GetP1());
auto function = expression.Compile(a);
uint32_t p1 = 12340000ul;
uint32_t p2 = 5678ul;
auto expected = p1 + p2;
auto observed = function(p1, p2);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, MulUnsignedInt32)
{
auto setup = GetSetup();
{
Function<uint32_t, uint32_t, uint32_t> expression(setup->GetAllocator(), setup->GetCode());
auto & a = expression.Mul(expression.GetP2(), expression.GetP1());
auto function = expression.Compile(a);
uint32_t p1 = 12340000ul;
uint32_t p2 = 5678ul;
auto expected = p1 * p2;
auto observed = function(p1, p2);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, SubUnsignedInt32)
{
auto setup = GetSetup();
{
Function<uint32_t, uint32_t, uint32_t> expression(setup->GetAllocator(), setup->GetCode());
auto & a = expression.Sub(expression.GetP2(), expression.GetP1());
auto function = expression.Compile(a);
uint32_t p1 = 12340000ul;
uint32_t p2 = 5678ul;
auto expected = p2 - p1;
auto observed = function(p1, p2);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, ShlUnsignedInt32)
{
auto setup = GetSetup();
{
Function<uint32_t, uint32_t, uint32_t> expression(setup->GetAllocator(), setup->GetCode());
uint32_t p2 = 3ul;
auto & a = expression.Shl(expression.GetP1(), p2);
auto function = expression.Compile(a);
uint32_t p1 = 1ul;
auto expected = p1 << p2;
auto observed = function(p1, p2);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, ShrUnsignedInt32)
{
auto setup = GetSetup();
{
Function<uint32_t, uint32_t, uint32_t> expression(setup->GetAllocator(), setup->GetCode());
uint32_t p2 = 3ul;
auto & a = expression.Shr(expression.GetP1(), p2);
auto function = expression.Compile(a);
uint32_t p1 = 0xffffffff;
auto expected = p1 >> p2;
auto observed = function(p1, p2);
TestAssert(observed == expected);
}
}
//
// Ternary operations
//
TEST_CASE_F(Unsigned, ShldUnsignedInt32)
{
auto setup = GetSetup();
{
Function<uint32_t, uint32_t, uint32_t, uint32_t> expression(setup->GetAllocator(), setup->GetCode());
uint8_t p3 = 4ul;
auto & a = expression.Shld(expression.GetP2(), expression.GetP1(), p3);
auto function = expression.Compile(a);
uint32_t p1 = 1ul;
uint32_t p2 = 3ul;
auto expected = p2 << p3;
auto observed = function(p1, p2, p3);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, ShldPairUnsignedInt32)
{
auto setup = GetSetup();
{
Function<uint32_t, uint32_t, uint32_t, uint32_t> expression(setup->GetAllocator(), setup->GetCode());
uint8_t p3 = 4ul;
auto & a = expression.Shld(expression.GetP2(), expression.GetP1(), p3);
auto function = expression.Compile(a);
uint32_t p1 = 0xaaaaaaaa;
uint32_t p2 = 3ul;
auto expected = p2 << p3 | (p1 & 0xf);
auto observed = function(p1, p2, p3);
TestAssert(observed == expected);
}
}
//
// Array indexing
//
TEST_CASE_F(Unsigned, ArrayOfIntAsPointer)
{
auto setup = GetSetup();
{
Function<uint64_t, uint64_t*> expression(setup->GetAllocator(), setup->GetCode());
auto & a = expression.Add(expression.GetP1(), expression.Immediate<uint64_t>(1ull));
auto & b = expression.Add(expression.GetP1(), expression.Immediate<uint64_t>(2ull));
auto & c = expression.Add(expression.Deref(a), expression.Deref(b));
auto function = expression.Compile(c);
uint64_t array[10];
array[1] = 456;
array[2] = 123000;
uint64_t * p1 = array;
auto expected = array[1] + array[2];
auto observed = function(p1);
TestAssert(observed == expected);
}
}
TEST_CASE_F(Unsigned, ArrayOfInt)
{
auto setup = GetSetup();
{
struct S
{
uint64_t m_array[10];
};
Function<uint64_t, S*> e(setup->GetAllocator(), setup->GetCode());
auto & arrayPtr = e.FieldPointer(e.GetP1(), &S::m_array);
auto & left = e.Add(arrayPtr, e.Immediate(1));
auto & right = e.Add(arrayPtr, e.Immediate(2));
auto & sum = e.Add(e.Deref(left), e.Deref(right));
auto function = e.Compile(sum);
struct S s;
s.m_array[1] = 456;
s.m_array[2] = 123000;
auto expected = s.m_array[1] + s.m_array[2];
auto observed = function(&s);
TestEqual(expected, observed);
}
}
TEST_CASE_F(Unsigned, ArrayOfClass)
{
auto setup = GetSetup();
{
Function<int64_t, OuterClass*, uint64_t> expression(setup->GetAllocator(), setup->GetCode());
auto & a = expression.Add(expression.GetP1(), expression.GetP2());
auto & b = expression.FieldPointer(a, &OuterClass::m_q);
auto & c = expression.Deref(b);
auto function = expression.Compile(c);
OuterClass array[10];
OuterClass* p1 = array;
uint64_t p2 = 3ull;
p1[p2].m_q = 0x0123456789ABCDEF;
auto expected = p1[p2].m_q;
auto observed = function(p1, p2);
TestAssert(observed == expected);
}
}
//
// Common sub expressions
//
TEST_CASE_F(Unsigned, CommonSubExpressions)
{
auto setup = GetSetup();
{
Function<int64_t, int64_t, int64_t> expression(setup->GetAllocator(), setup->GetCode());
// This tree has three common subexpressions: P1, P2, and node "a".
// Each common subexpression is referenced twice.
auto & a = expression.Add(expression.GetP1(), expression.GetP2());
auto & b = expression.Add(a, expression.GetP1());
// Perform this add after 2nd and last use of P1 to see if RCX is recycled.
auto & c = expression.Add(expression.Immediate(1ll), expression.Immediate(2ll));
auto & d = expression.Add(b, c);
auto & e = expression.Add(d, expression.GetP2());
// Perform this add after 2nd and last use of P2 to see if RDX is recycled.
auto & f = expression.Add(expression.Immediate(3ll), expression.Immediate(4ll));
auto & g = expression.Add(e, f);
auto & h = expression.Add(g, a);
// Perform this add after 2nd and last use of a to see if a's register is recycled.
auto & i = expression.Add(expression.Immediate(5ll), expression.Immediate(6ll));
auto & j = expression.Add(h, i);
auto function = expression.Compile(j);
int64_t p1 = 1ll;
int64_t p2 = 10ll;
auto expectedA = p1 + p2;
auto expectedB = expectedA + p1;
auto expectedC = 1ll + 2ll;
auto expectedD = expectedB + expectedC;
auto expectedE = expectedD + p2;
auto expectedF = 3ll + 4ll;
auto expectedG = expectedE + expectedF;
auto expectedH = expectedG + expectedA;
auto expectedI = 5ll + 6ll;
auto expected = expectedH + expectedI;
auto observed = function(p1, p2);
TestAssert(observed == expected);
}
}
TEST_CASES_END
}
}
<|endoftext|> |
<commit_before>void rec(Int_t runNumber = 0, const char* year = "08", const char *localFileName = NULL)
{
// Offline shifter reconstruction macro
TString filename;
if (!localFileName) {
cout << "Going to run the reconstruction for run: " << runNumber << endl;
// connect to the grid
TGrid * grid = 0x0 ;
grid = TGrid::Connect("alien://") ;
// make the file name pattern year and run number
TString pattern;
pattern.Form("%9d",runNumber);
pattern.ReplaceAll(" ", "0") ;
pattern.Prepend(year);
pattern.Append("*0.root");
// find the files associated to this run
// get the list of files from AliEn directly
TString baseDir;
baseDir.Form("/alice/data/20%s/",year);
cout << "Looking for raw-data files with pattern " << pattern << " in folder " << baseDir << endl;
TGridResult *result = grid->Query(baseDir, pattern);
TList *fileList = result->GetFileInfoList();
cout << fileList->GetEntries() << " raw-data files found" << endl;
if ( fileList->GetEntries() == 0) {
cout << "Exiting..." << endl;
return;
}
// Take the first (or last?) file...
TFileInfo *fi = (TFileInfo *)fileList->At(0);
// TFileInfo *fi = (TFileInfo *)fileList->At(fileList->GetEntries()-1);
cout << "Getting the file:" << fi->GetCurrentUrl()->GetUrl() << endl;
fi->Dump();
filename = fi->GetCurrentUrl()->GetUrl();
}
else {
// In case of local raw-data file...
filename = localFileName;
}
AliLog::Flush();
/////////////////////////////////////////////////////////////////////////////////////////
//
// First version of the reconstruction
// script for the FDR'08
// Set the CDB storage location
// AliLog::SetModuleDebugLevel("STEER",2);
AliCDBManager * man = AliCDBManager::Instance();
// man->SetDefaultStorage("local://LocalCDB");
man->SetDefaultStorage("alien://folder=/alice/data/2008/LHC08a/OCDB/");
// Files that we can not read from alien...solved
// man->SetSpecificStorage("ITS/Calib/MapsAnodeSDD","local://$ALICE_ROOT");
// man->SetSpecificStorage("ITS/Calib/MapsTimeSDD","local://$ALICE_ROOT");
// man->SetSpecificStorage("TPC/Calib/ExB","local://$ALICE_ROOT");
// Objects not found if using LHC07w database...solved
// man->SetSpecificStorage("ITS/Calib/MapsAnodeSDD","local:///afs/cern.ch/user/c/cheshkov/public/OCDB");
// man->SetSpecificStorage("GRP/GRP/Data","local://$ALICE_ROOT");
// man->SetSpecificStorage("ITS/Calib/DDLMapSDD","local://$ALICE_ROOT");
// man->SetSpecificStorage("MUON/Calib/Mapping","local://$ALICE_ROOT");
// man->SetSpecificStorage("MUON/Calib/DDLStore","local://$ALICE_ROOT");
// ITS settings
AliITSRecoParam * itsRecoParam = AliITSRecoParam::GetCosmicTestParam();
itsRecoParam->SetClusterErrorsParam(2);
itsRecoParam->SetFindV0s(kFALSE);
itsRecoParam->SetAddVirtualClustersInDeadZone(kFALSE);
itsRecoParam->SetUseAmplitudeInfo(kFALSE);
// In case we want to switch off a layer
// itsRecoParam->SetLayerToSkip(<N>);
itsRecoParam->SetLayerToSkip(4);
itsRecoParam->SetLayerToSkip(5);
itsRecoParam->SetLayerToSkip(2);
itsRecoParam->SetLayerToSkip(3);
AliITSReconstructor::SetRecoParam(itsRecoParam);
// TPC settings
AliLog::SetClassDebugLevel("AliTPCclustererMI",2);
AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE);
tpcRecoParam->SetTimeInterval(60,940);
tpcRecoParam->Dump();
AliTPCReconstructor::SetRecoParam(tpcRecoParam);
AliTPCReconstructor::SetStreamLevel(1);
// TRD setting
AliTRDrawStreamBase::SetRawStreamVersion("TB");
// PHOS settings
AliPHOSRecoParam* recEmc = new AliPHOSRecoParamEmc();
recEmc->SetSubtractPedestals(kTRUE);
recEmc->SetMinE(0.05);
recEmc->SetClusteringThreshold(0.10);
AliPHOSReconstructor::SetRecoParamEmc(recEmc);
// T0 settings
AliLog::SetModuleDebugLevel("T0", 10);
// MUON settings
AliLog::SetClassDebugLevel("AliMUONRawStreamTracker",3);
AliMUONRecoParam *muonRecoParam = AliMUONRecoParam::GetLowFluxParam();
muonRecoParam->CombineClusterTrackReco(kTRUE);
muonRecoParam->SetCalibrationMode("NOGAIN");
//muonRecoParam->SetClusteringMode("PEAKFIT");
//muonRecoParam->SetClusteringMode("PEAKCOG");
muonRecoParam->Print("FULL");
AliRecoParam::Instance()->RegisterRecoParam(muonRecoParam);
// Tracking settings
// AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., 1);
AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 0., 10., 2);
AliTracker::SetFieldMap(field,1);
Double_t mostProbPt=0.35;
AliExternalTrackParam::SetMostProbablePt(mostProbPt);
// AliReconstruction settings
AliReconstruction rec;
rec.SetUniformFieldTracking(kFALSE);
rec.SetWriteESDfriend(kTRUE);
rec.SetWriteAlignmentData();
rec.SetInput(filename.Data());
rec.SetRunReconstruction("ALL");
rec.SetUseTrackingErrorsForAlignment("ITS");
// In case some detectors have to be switched off...
// rec.SetRunLocalReconstruction("ALL");
// rec.SetRunTracking("ALL");
// rec.SetFillESD("ALL");
// Enable vertex finder - it is needed for cosmic track reco
rec.SetRunVertexFinder(kTRUE);
// To be enabled if some equipment IDs are not set correctly by DAQ
// rec.SetEquipmentIdMap("EquipmentIdMap.data");
// Detector options if any
rec.SetOption("ITS","cosmics,onlyITS");
rec.SetOption("MUON","SAVEDIGITS");
rec.SetOption("TPC","OldRCUFormat");
rec.SetOption("PHOS","OldRCUFormat");
// To be enabled when CTP readout starts
rec.SetFillTriggerESD(kFALSE);
// all events in one single file
rec.SetNumberOfEventsPerFile(-1);
// switch off cleanESD
rec.SetCleanESD(kFALSE);
// rec.SetEventRange(0,15);
// AliLog::SetGlobalDebugLevel(2);
rec.SetRunQA(kFALSE);
AliLog::Flush();
rec.Run();
//cout << "-----------------------------------------------------------------" << endl;
//cout << "-----------------------------------------------------------------" << endl;
//cout << "--------- Reconstruction Completed. Start merging QAs -----------" << endl;
//cout << "-----------------------------------------------------------------" << endl;
//cout << "-----------------------------------------------------------------" << endl;
//AliQADataMakerSteer qas;
//qas.Merge();
}
<commit_msg>T0 Option needed for cosmic run reconstruction (Alla)<commit_after>void rec(Int_t runNumber = 0, const char* year = "08", const char *localFileName = NULL)
{
// Offline shifter reconstruction macro
TString filename;
if (!localFileName) {
cout << "Going to run the reconstruction for run: " << runNumber << endl;
// connect to the grid
TGrid * grid = 0x0 ;
grid = TGrid::Connect("alien://") ;
// make the file name pattern year and run number
TString pattern;
pattern.Form("%9d",runNumber);
pattern.ReplaceAll(" ", "0") ;
pattern.Prepend(year);
pattern.Append("*0.root");
// find the files associated to this run
// get the list of files from AliEn directly
TString baseDir;
baseDir.Form("/alice/data/20%s/",year);
cout << "Looking for raw-data files with pattern " << pattern << " in folder " << baseDir << endl;
TGridResult *result = grid->Query(baseDir, pattern);
TList *fileList = result->GetFileInfoList();
cout << fileList->GetEntries() << " raw-data files found" << endl;
if ( fileList->GetEntries() == 0) {
cout << "Exiting..." << endl;
return;
}
// Take the first (or last?) file...
TFileInfo *fi = (TFileInfo *)fileList->At(0);
// TFileInfo *fi = (TFileInfo *)fileList->At(fileList->GetEntries()-1);
cout << "Getting the file:" << fi->GetCurrentUrl()->GetUrl() << endl;
fi->Dump();
filename = fi->GetCurrentUrl()->GetUrl();
}
else {
// In case of local raw-data file...
filename = localFileName;
}
AliLog::Flush();
/////////////////////////////////////////////////////////////////////////////////////////
//
// First version of the reconstruction
// script for the FDR'08
// Set the CDB storage location
// AliLog::SetModuleDebugLevel("STEER",2);
AliCDBManager * man = AliCDBManager::Instance();
// man->SetDefaultStorage("local://LocalCDB");
man->SetDefaultStorage("alien://folder=/alice/data/2008/LHC08a/OCDB/");
// Files that we can not read from alien...solved
// man->SetSpecificStorage("ITS/Calib/MapsAnodeSDD","local://$ALICE_ROOT");
// man->SetSpecificStorage("ITS/Calib/MapsTimeSDD","local://$ALICE_ROOT");
// man->SetSpecificStorage("TPC/Calib/ExB","local://$ALICE_ROOT");
// Objects not found if using LHC07w database...solved
// man->SetSpecificStorage("ITS/Calib/MapsAnodeSDD","local:///afs/cern.ch/user/c/cheshkov/public/OCDB");
// man->SetSpecificStorage("GRP/GRP/Data","local://$ALICE_ROOT");
// man->SetSpecificStorage("ITS/Calib/DDLMapSDD","local://$ALICE_ROOT");
// man->SetSpecificStorage("MUON/Calib/Mapping","local://$ALICE_ROOT");
// man->SetSpecificStorage("MUON/Calib/DDLStore","local://$ALICE_ROOT");
// ITS settings
AliITSRecoParam * itsRecoParam = AliITSRecoParam::GetCosmicTestParam();
itsRecoParam->SetClusterErrorsParam(2);
itsRecoParam->SetFindV0s(kFALSE);
itsRecoParam->SetAddVirtualClustersInDeadZone(kFALSE);
itsRecoParam->SetUseAmplitudeInfo(kFALSE);
// In case we want to switch off a layer
// itsRecoParam->SetLayerToSkip(<N>);
itsRecoParam->SetLayerToSkip(4);
itsRecoParam->SetLayerToSkip(5);
itsRecoParam->SetLayerToSkip(2);
itsRecoParam->SetLayerToSkip(3);
AliITSReconstructor::SetRecoParam(itsRecoParam);
// TPC settings
AliLog::SetClassDebugLevel("AliTPCclustererMI",2);
AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE);
tpcRecoParam->SetTimeInterval(60,940);
tpcRecoParam->Dump();
AliTPCReconstructor::SetRecoParam(tpcRecoParam);
AliTPCReconstructor::SetStreamLevel(1);
// TRD setting
AliTRDrawStreamBase::SetRawStreamVersion("TB");
// PHOS settings
AliPHOSRecoParam* recEmc = new AliPHOSRecoParamEmc();
recEmc->SetSubtractPedestals(kTRUE);
recEmc->SetMinE(0.05);
recEmc->SetClusteringThreshold(0.10);
AliPHOSReconstructor::SetRecoParamEmc(recEmc);
// T0 settings
AliLog::SetModuleDebugLevel("T0", 10);
// MUON settings
AliLog::SetClassDebugLevel("AliMUONRawStreamTracker",3);
AliMUONRecoParam *muonRecoParam = AliMUONRecoParam::GetLowFluxParam();
muonRecoParam->CombineClusterTrackReco(kTRUE);
muonRecoParam->SetCalibrationMode("NOGAIN");
//muonRecoParam->SetClusteringMode("PEAKFIT");
//muonRecoParam->SetClusteringMode("PEAKCOG");
muonRecoParam->Print("FULL");
AliRecoParam::Instance()->RegisterRecoParam(muonRecoParam);
// Tracking settings
// AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., 1);
AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 0., 10., 2);
AliTracker::SetFieldMap(field,1);
Double_t mostProbPt=0.35;
AliExternalTrackParam::SetMostProbablePt(mostProbPt);
// AliReconstruction settings
AliReconstruction rec;
rec.SetUniformFieldTracking(kFALSE);
rec.SetWriteESDfriend(kTRUE);
rec.SetWriteAlignmentData();
rec.SetInput(filename.Data());
rec.SetRunReconstruction("ALL");
rec.SetUseTrackingErrorsForAlignment("ITS");
// In case some detectors have to be switched off...
// rec.SetRunLocalReconstruction("ALL");
// rec.SetRunTracking("ALL");
// rec.SetFillESD("ALL");
// Enable vertex finder - it is needed for cosmic track reco
rec.SetRunVertexFinder(kTRUE);
// To be enabled if some equipment IDs are not set correctly by DAQ
// rec.SetEquipmentIdMap("EquipmentIdMap.data");
// Detector options if any
rec.SetOption("ITS","cosmics,onlyITS");
rec.SetOption("MUON","SAVEDIGITS");
rec.SetOption("TPC","OldRCUFormat");
rec.SetOption("PHOS","OldRCUFormat");
rec.SetOption("T0","cosmic");
// To be enabled when CTP readout starts
rec.SetFillTriggerESD(kFALSE);
// all events in one single file
rec.SetNumberOfEventsPerFile(-1);
// switch off cleanESD
rec.SetCleanESD(kFALSE);
// rec.SetEventRange(0,15);
// AliLog::SetGlobalDebugLevel(2);
rec.SetRunQA(kFALSE);
AliLog::Flush();
rec.Run();
//cout << "-----------------------------------------------------------------" << endl;
//cout << "-----------------------------------------------------------------" << endl;
//cout << "--------- Reconstruction Completed. Start merging QAs -----------" << endl;
//cout << "-----------------------------------------------------------------" << endl;
//cout << "-----------------------------------------------------------------" << endl;
//AliQADataMakerSteer qas;
//qas.Merge();
}
<|endoftext|> |
<commit_before>/** \file augment_pda.cc
* \brief Tag monographs not available for ILL as PDA
* \author Johannes Riedl
*/
/*
Copyright (C) 2017, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <unordered_map>
#include "Compiler.h"
#include "FileUtil.h"
#include "MarcReader.h"
#include "MarcRecord.h"
#include "MarcWriter.h"
#include "util.h"
static unsigned modified_count(0);
static unsigned record_count(0);
const std::string POTENTIALLY_PDA_TAG("192");
const char POTENTIALLY_PDA_SUBFIELD('a');
const int PDA_CUTOFF_YEAR(2014);
void Usage() {
std::cerr << "Usage: " << ::progname << " [--verbose] ill_list marc_input marc_output\n"
<< " Insert an additional field for monographs published after " << PDA_CUTOFF_YEAR << "\n"
<< " that are not available in SWB interlibrary loan (show up in the ill_list)\n"
<< " thus providing a set of candidates for Patron Driven Acquisition (PDA)\n";
std::exit(EXIT_FAILURE);
}
void ExtractILLPPNs(const bool verbose, const std::unique_ptr<File>& ill_list, std::unordered_set<std::string> * const ill_set) {
std::string line;
int retval;
while (retval = ill_list->getline(&line, '\n')) {
if (not retval) {
if (unlikely(ill_list->anErrorOccurred()))
Error("Error on relaind ill list " + ill_list->getPath());
if (unlikely(ill_list->eof()))
return;
}
if (verbose)
std::cerr << "Adding " << line << " to ill set";
ill_set->emplace(line);
}
}
void ProcessRecord(const bool verbose, MarcRecord * const record, const std::unordered_set<std::string> * ill_set) {
// We tag a record as potentially PDA if it is
// a) a monograph b) published after a given cutoff date c) not in the list of known SWB-ILLs
if (not record->getLeader().isMonograph())
return;
const size_t _008_index(record->getFieldIndex("008"));
if (unlikely(_008_index == MarcRecord::FIELD_NOT_FOUND))
return;
// Determine publication sort year given in Bytes 7-10 of field 008
const std::string &_008_contents(record->getFieldData(_008_index));
try {
int publication_year(boost::lexical_cast<int>(_008_contents.substr(7,4)));
if (publication_year < PDA_CUTOFF_YEAR)
return;
} catch (boost::bad_lexical_cast const&) {
if (verbose)
std::cerr << "Could not determine publication year for record " << record->getControlNumber()
<< " [ " << _008_contents.substr(7,4) << " given ]\n";
return;
}
if (ill_set->find(record->getControlNumber()) == ill_set->end()) {
if (record->getFieldIndex(POTENTIALLY_PDA_TAG) != MarcRecord::FIELD_NOT_FOUND)
Error("Field " + POTENTIALLY_PDA_TAG + " already populated for PPN " + record->getControlNumber());
record->insertSubfield(POTENTIALLY_PDA_TAG, POTENTIALLY_PDA_SUBFIELD, "1");
++modified_count;
}
}
void TagRelevantRecords(const bool verbose, MarcReader * const marc_reader, MarcWriter * const marc_writer,
const std::unordered_set<std::string> * ill_set)
{
while (MarcRecord record = marc_reader->read()) {
ProcessRecord(verbose, &record, ill_set);
marc_writer->write(record);
++record_count;
}
std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n";
}
int main(int argc, char **argv) {
::progname = argv[0];
if (argc < 2)
Usage();
bool verbose(false);
if (std::strcmp(argv[1], "--verbose") == 0) {
verbose = true;
--argc;
++argv;
}
if (argc != 4)
Usage();
const std::string ill_list_filename(argv[1]);
const std::string marc_input_filename(argv[2]);
const std::string marc_output_filename(argv[3]);
if (unlikely(marc_input_filename == marc_output_filename))
Error("Input file equals output file");
if (unlikely(marc_input_filename == ill_list_filename || marc_output_filename == ill_list_filename))
Error("ILL File equals marc input or output file");
try {
std::unordered_set<std::string> ill_set;
std::unique_ptr<File> ill_reader(FileUtil::OpenInputFileOrDie(ill_list_filename));
std::unique_ptr<MarcReader> marc_reader(MarcReader::Factory(marc_input_filename));
std::unique_ptr<MarcWriter> marc_writer(MarcWriter::Factory(marc_output_filename));
ExtractILLPPNs(verbose, ill_reader, &ill_set);
TagRelevantRecords(verbose, marc_reader.get(), marc_writer.get(), &ill_set);
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<commit_msg>I really hate the compiler!<commit_after>/** \file augment_pda.cc
* \brief Tag monographs not available for ILL as PDA
* \author Johannes Riedl
*/
/*
Copyright (C) 2017, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <unordered_map>
#include "Compiler.h"
#include "FileUtil.h"
#include "MarcReader.h"
#include "MarcRecord.h"
#include "MarcWriter.h"
#include "util.h"
static unsigned modified_count(0);
static unsigned record_count(0);
const std::string POTENTIALLY_PDA_TAG("192");
const char POTENTIALLY_PDA_SUBFIELD('a');
const int PDA_CUTOFF_YEAR(2014);
void Usage() {
std::cerr << "Usage: " << ::progname << " [--verbose] ill_list marc_input marc_output\n"
<< " Insert an additional field for monographs published after " << PDA_CUTOFF_YEAR << "\n"
<< " that are not available in SWB interlibrary loan (show up in the ill_list)\n"
<< " thus providing a set of candidates for Patron Driven Acquisition (PDA)\n";
std::exit(EXIT_FAILURE);
}
void ExtractILLPPNs(const bool verbose, const std::unique_ptr<File>& ill_list,
std::unordered_set<std::string> * const ill_set)
{
std::string line;
int line_size;
while ((line_size = ill_list->getline(&line, '\n'))) {
if (line_size == 0) {
if (unlikely(ill_list->anErrorOccurred()))
Error("Error on relaind ill list " + ill_list->getPath());
if (unlikely(ill_list->eof()))
return;
}
if (verbose)
std::cerr << "Adding " << line << " to ill set";
ill_set->emplace(line);
}
}
void ProcessRecord(const bool verbose, MarcRecord * const record, const std::unordered_set<std::string> * ill_set) {
// We tag a record as potentially PDA if it is
// a) a monograph b) published after a given cutoff date c) not in the list of known SWB-ILLs
if (not record->getLeader().isMonograph())
return;
const size_t _008_index(record->getFieldIndex("008"));
if (unlikely(_008_index == MarcRecord::FIELD_NOT_FOUND))
return;
// Determine publication sort year given in Bytes 7-10 of field 008
const std::string &_008_contents(record->getFieldData(_008_index));
try {
int publication_year(boost::lexical_cast<int>(_008_contents.substr(7,4)));
if (publication_year < PDA_CUTOFF_YEAR)
return;
} catch (boost::bad_lexical_cast const&) {
if (verbose)
std::cerr << "Could not determine publication year for record " << record->getControlNumber()
<< " [ " << _008_contents.substr(7,4) << " given ]\n";
return;
}
if (ill_set->find(record->getControlNumber()) == ill_set->end()) {
if (record->getFieldIndex(POTENTIALLY_PDA_TAG) != MarcRecord::FIELD_NOT_FOUND)
Error("Field " + POTENTIALLY_PDA_TAG + " already populated for PPN " + record->getControlNumber());
record->insertSubfield(POTENTIALLY_PDA_TAG, POTENTIALLY_PDA_SUBFIELD, "1");
++modified_count;
}
}
void TagRelevantRecords(const bool verbose, MarcReader * const marc_reader, MarcWriter * const marc_writer,
const std::unordered_set<std::string> * ill_set)
{
while (MarcRecord record = marc_reader->read()) {
ProcessRecord(verbose, &record, ill_set);
marc_writer->write(record);
++record_count;
}
std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n";
}
int main(int argc, char **argv) {
::progname = argv[0];
if (argc < 2)
Usage();
bool verbose(false);
if (std::strcmp(argv[1], "--verbose") == 0) {
verbose = true;
--argc;
++argv;
}
if (argc != 4)
Usage();
const std::string ill_list_filename(argv[1]);
const std::string marc_input_filename(argv[2]);
const std::string marc_output_filename(argv[3]);
if (unlikely(marc_input_filename == marc_output_filename))
Error("Input file equals output file");
if (unlikely(marc_input_filename == ill_list_filename || marc_output_filename == ill_list_filename))
Error("ILL File equals marc input or output file");
try {
std::unordered_set<std::string> ill_set;
std::unique_ptr<File> ill_reader(FileUtil::OpenInputFileOrDie(ill_list_filename));
std::unique_ptr<MarcReader> marc_reader(MarcReader::Factory(marc_input_filename));
std::unique_ptr<MarcWriter> marc_writer(MarcWriter::Factory(marc_output_filename));
ExtractILLPPNs(verbose, ill_reader, &ill_set);
TagRelevantRecords(verbose, marc_reader.get(), marc_writer.get(), &ill_set);
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<|endoftext|> |
<commit_before>/* Sirikata
* main.cpp
*
* Copyright (c) 2008, Daniel Reiter Horn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sirikata/oh/Platform.hpp>
#include <sirikata/core/util/Platform.hpp>
#include <sirikata/core/util/SpaceObjectReference.hpp>
#include <sirikata/core/util/PluginManager.hpp>
#include <sirikata/oh/SimulationFactory.hpp>
#include "ObjectHost.hpp"
#include <sirikata/mesh/LightInfo.hpp>
#include <sirikata/oh/HostedObject.hpp>
#include <sirikata/core/network/IOService.hpp>
#include <time.h>
#include <boost/thread.hpp>
#include <sirikata/core/options/Options.hpp>
#include <sirikata/core/options/CommonOptions.hpp>
#include "Options.hpp"
#include <sirikata/oh/Trace.hpp>
#include <sirikata/core/network/ServerIDMap.hpp>
#include <sirikata/core/network/NTPTimeSync.hpp>
#include <sirikata/core/odp/SST.hpp>
#include <sirikata/oh/ObjectHostContext.hpp>
#include <sirikata/oh/Storage.hpp>
#include <sirikata/oh/PersistedObjectSet.hpp>
#include <sirikata/oh/ObjectFactory.hpp>
#include <sirikata/oh/ObjectQueryProcessor.hpp>
#include <sirikata/mesh/Filter.hpp>
#include <sirikata/mesh/ModelsSystemFactory.hpp>
#include <sirikata/oh/ObjectScriptManagerFactory.hpp>
#ifdef __GNUC__
#include <fenv.h>
#endif
int main (int argc, char** argv) {
using namespace Sirikata;
DynamicLibrary::Initialize();
InitOptions();
Trace::Trace::InitOptions();
OHTrace::InitOptions();
InitCPPOHOptions();
ParseOptions(argc, argv, OPT_CONFIG_FILE);
PluginManager plugins;
String search_path=GetOptionValue<String>(OPT_OH_PLUGIN_SEARCH_PATHS);
if (search_path.length()) {
while (true) {
String::size_type where=search_path.find(":");
if (where==String::npos) {
DynamicLibrary::AddLoadPath(search_path);
break;
}else {
DynamicLibrary::AddLoadPath(search_path.substr(0,where));
search_path=search_path.substr(where+1);
}
}
}
plugins.loadList( GetOptionValue<String>(OPT_PLUGINS) );
plugins.loadList( GetOptionValue<String>(OPT_OH_PLUGINS) );
// Fill defaults after plugin loading to ensure plugin-added
// options get their defaults.
FillMissingOptionDefaults();
// Rerun original parse to make sure any newly added options are
// properly parsed.
ParseOptions(argc, argv, OPT_CONFIG_FILE);
ReportVersion(); // After options so log goes to the right place
String time_server = GetOptionValue<String>("time-server");
NTPTimeSync sync;
if (time_server.size() > 0)
sync.start(time_server);
#ifdef __GNUC__
#ifndef __APPLE__
if (GetOptionValue<bool>(OPT_SIGFPE)) {
feenableexcept(FE_DIVBYZERO|FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW);
}
#endif
#endif
ObjectHostID oh_id = GetOptionValue<ObjectHostID>("ohid");
String trace_file = GetPerServerFile(STATS_OH_TRACE_FILE, oh_id);
Trace::Trace* trace = new Trace::Trace(trace_file);
srand( GetOptionValue<uint32>("rand-seed") );
Network::IOService* ios = new Network::IOService("Object Host");
Network::IOStrand* mainStrand = ios->createStrand("Object Host Main");
ODPSST::ConnectionManager* sstConnMgr = new ODPSST::ConnectionManager();
OHDPSST::ConnectionManager* ohSstConnMgr = new OHDPSST::ConnectionManager();
Time start_time = Timer::now(); // Just for stats in ObjectHostContext.
Duration duration = Duration::zero(); // Indicates to run forever.
ObjectHostContext* ctx = new ObjectHostContext("cppoh", oh_id, sstConnMgr, ohSstConnMgr, ios, mainStrand, trace, start_time, duration);
String servermap_type = GetOptionValue<String>("servermap");
String servermap_options = GetOptionValue<String>("servermap-options");
ServerIDMap * server_id_map =
ServerIDMapFactory::getSingleton().getConstructor(servermap_type)(ctx, servermap_options);
String timeseries_type = GetOptionValue<String>(OPT_TRACE_TIMESERIES);
String timeseries_options = GetOptionValue<String>(OPT_TRACE_TIMESERIES_OPTIONS);
Trace::TimeSeries* time_series = Trace::TimeSeriesFactory::getSingleton().getConstructor(timeseries_type)(ctx, timeseries_options);
SpaceID mainSpace(GetOptionValue<UUID>(OPT_MAIN_SPACE));
String oh_options = GetOptionValue<String>(OPT_OH_OPTIONS);
ObjectHost *oh = new CppohObjectHost(ctx, ios, oh_options);
// Add all the spaces to the ObjectHost. We used to have SpaceIDMap and
// fill in the same ServerIDMap for all these. Now we just add the
// ServerIDMap for the main space. We need a better way of handling multiple
// spaces.
oh->addServerIDMap(mainSpace, server_id_map);
String objstorage_type = GetOptionValue<String>(OPT_OBJECT_STORAGE);
String objstorage_options = GetOptionValue<String>(OPT_OBJECT_STORAGE_OPTS);
OH::Storage* obj_storage =
OH::StorageFactory::getSingleton().getConstructor(objstorage_type)(ctx, objstorage_options);
oh->setStorage(obj_storage);
String objpersistentset_type = GetOptionValue<String>(OPT_OH_PERSISTENT_SET);
String objpersistentset_options = GetOptionValue<String>(OPT_OH_PERSISTENT_SET_OPTS);
OH::PersistedObjectSet* obj_persistent_set =
OH::PersistedObjectSetFactory::getSingleton().getConstructor(objpersistentset_type)(ctx, objpersistentset_options);
oh->setPersistentSet(obj_persistent_set);
String objfactory_type = GetOptionValue<String>(OPT_OBJECT_FACTORY);
String objfactory_options = GetOptionValue<String>(OPT_OBJECT_FACTORY_OPTS);
ObjectFactory* obj_factory = NULL;
String obj_query_type = GetOptionValue<String>(OPT_OBJECT_QUERY_PROCESSOR);
String obj_query_options = GetOptionValue<String>(OPT_OBJECT_QUERY_PROCESSOR_OPTS);
OH::ObjectQueryProcessor* obj_query_processor =
OH::ObjectQueryProcessorFactory::getSingleton().getConstructor(obj_query_type)(ctx, obj_query_options);
oh->setQueryProcessor(obj_query_processor);
///////////Go go go!! start of simulation/////////////////////
ctx->add(ctx);
ctx->add(obj_storage);
ctx->add(obj_persistent_set);
ctx->add(obj_query_processor);
ctx->add(oh);
ctx->add(sstConnMgr);
ctx->add(ohSstConnMgr);
if (!objfactory_type.empty())
{
obj_factory = ObjectFactoryFactory::getSingleton().getConstructor(objfactory_type)(ctx, oh, mainSpace, objfactory_options);
obj_factory->generate();
}
ctx->run(1);
ctx->cleanup();
if (GetOptionValue<bool>(PROFILE)) {
ctx->profiler->report();
}
trace->prepareShutdown();
Mesh::FilterFactory::destroy();
ModelsSystemFactory::destroy();
ObjectScriptManagerFactory::destroy();
delete oh;
delete obj_storage;
delete obj_persistent_set;
SimulationFactory::destroy();
delete ctx;
delete time_series;
trace->shutdown();
delete trace;
trace = NULL;
delete mainStrand;
delete ios;
delete sstConnMgr;
delete ohSstConnMgr;
plugins.gc();
sync.stop();
Sirikata::Logging::finishLog();
return 0;
}
<commit_msg>Enable Commander interface for cppoh.<commit_after>/* Sirikata
* main.cpp
*
* Copyright (c) 2008, Daniel Reiter Horn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sirikata/oh/Platform.hpp>
#include <sirikata/core/util/Platform.hpp>
#include <sirikata/core/util/SpaceObjectReference.hpp>
#include <sirikata/core/util/PluginManager.hpp>
#include <sirikata/oh/SimulationFactory.hpp>
#include "ObjectHost.hpp"
#include <sirikata/mesh/LightInfo.hpp>
#include <sirikata/oh/HostedObject.hpp>
#include <sirikata/core/network/IOService.hpp>
#include <time.h>
#include <boost/thread.hpp>
#include <sirikata/core/options/Options.hpp>
#include <sirikata/core/options/CommonOptions.hpp>
#include "Options.hpp"
#include <sirikata/oh/Trace.hpp>
#include <sirikata/core/network/ServerIDMap.hpp>
#include <sirikata/core/network/NTPTimeSync.hpp>
#include <sirikata/core/odp/SST.hpp>
#include <sirikata/oh/ObjectHostContext.hpp>
#include <sirikata/oh/Storage.hpp>
#include <sirikata/oh/PersistedObjectSet.hpp>
#include <sirikata/oh/ObjectFactory.hpp>
#include <sirikata/oh/ObjectQueryProcessor.hpp>
#include <sirikata/mesh/Filter.hpp>
#include <sirikata/mesh/ModelsSystemFactory.hpp>
#include <sirikata/oh/ObjectScriptManagerFactory.hpp>
#include <sirikata/core/command/Commander.hpp>
#ifdef __GNUC__
#include <fenv.h>
#endif
int main (int argc, char** argv) {
using namespace Sirikata;
DynamicLibrary::Initialize();
InitOptions();
Trace::Trace::InitOptions();
OHTrace::InitOptions();
InitCPPOHOptions();
ParseOptions(argc, argv, OPT_CONFIG_FILE);
PluginManager plugins;
String search_path=GetOptionValue<String>(OPT_OH_PLUGIN_SEARCH_PATHS);
if (search_path.length()) {
while (true) {
String::size_type where=search_path.find(":");
if (where==String::npos) {
DynamicLibrary::AddLoadPath(search_path);
break;
}else {
DynamicLibrary::AddLoadPath(search_path.substr(0,where));
search_path=search_path.substr(where+1);
}
}
}
plugins.loadList( GetOptionValue<String>(OPT_PLUGINS) );
plugins.loadList( GetOptionValue<String>(OPT_OH_PLUGINS) );
// Fill defaults after plugin loading to ensure plugin-added
// options get their defaults.
FillMissingOptionDefaults();
// Rerun original parse to make sure any newly added options are
// properly parsed.
ParseOptions(argc, argv, OPT_CONFIG_FILE);
ReportVersion(); // After options so log goes to the right place
String time_server = GetOptionValue<String>("time-server");
NTPTimeSync sync;
if (time_server.size() > 0)
sync.start(time_server);
#ifdef __GNUC__
#ifndef __APPLE__
if (GetOptionValue<bool>(OPT_SIGFPE)) {
feenableexcept(FE_DIVBYZERO|FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW);
}
#endif
#endif
ObjectHostID oh_id = GetOptionValue<ObjectHostID>("ohid");
String trace_file = GetPerServerFile(STATS_OH_TRACE_FILE, oh_id);
Trace::Trace* trace = new Trace::Trace(trace_file);
srand( GetOptionValue<uint32>("rand-seed") );
Network::IOService* ios = new Network::IOService("Object Host");
Network::IOStrand* mainStrand = ios->createStrand("Object Host Main");
ODPSST::ConnectionManager* sstConnMgr = new ODPSST::ConnectionManager();
OHDPSST::ConnectionManager* ohSstConnMgr = new OHDPSST::ConnectionManager();
Time start_time = Timer::now(); // Just for stats in ObjectHostContext.
Duration duration = Duration::zero(); // Indicates to run forever.
ObjectHostContext* ctx = new ObjectHostContext("cppoh", oh_id, sstConnMgr, ohSstConnMgr, ios, mainStrand, trace, start_time, duration);
String servermap_type = GetOptionValue<String>("servermap");
String servermap_options = GetOptionValue<String>("servermap-options");
ServerIDMap * server_id_map =
ServerIDMapFactory::getSingleton().getConstructor(servermap_type)(ctx, servermap_options);
String timeseries_type = GetOptionValue<String>(OPT_TRACE_TIMESERIES);
String timeseries_options = GetOptionValue<String>(OPT_TRACE_TIMESERIES_OPTIONS);
Trace::TimeSeries* time_series = Trace::TimeSeriesFactory::getSingleton().getConstructor(timeseries_type)(ctx, timeseries_options);
String commander_type = GetOptionValue<String>(OPT_COMMAND_COMMANDER);
String commander_options = GetOptionValue<String>(OPT_COMMAND_COMMANDER_OPTIONS);
Command::Commander* commander = NULL;
if (!commander_type.empty())
commander = Command::CommanderFactory::getSingleton().getConstructor(commander_type)(ctx, commander_options);
SpaceID mainSpace(GetOptionValue<UUID>(OPT_MAIN_SPACE));
String oh_options = GetOptionValue<String>(OPT_OH_OPTIONS);
ObjectHost *oh = new CppohObjectHost(ctx, ios, oh_options);
// Add all the spaces to the ObjectHost. We used to have SpaceIDMap and
// fill in the same ServerIDMap for all these. Now we just add the
// ServerIDMap for the main space. We need a better way of handling multiple
// spaces.
oh->addServerIDMap(mainSpace, server_id_map);
String objstorage_type = GetOptionValue<String>(OPT_OBJECT_STORAGE);
String objstorage_options = GetOptionValue<String>(OPT_OBJECT_STORAGE_OPTS);
OH::Storage* obj_storage =
OH::StorageFactory::getSingleton().getConstructor(objstorage_type)(ctx, objstorage_options);
oh->setStorage(obj_storage);
String objpersistentset_type = GetOptionValue<String>(OPT_OH_PERSISTENT_SET);
String objpersistentset_options = GetOptionValue<String>(OPT_OH_PERSISTENT_SET_OPTS);
OH::PersistedObjectSet* obj_persistent_set =
OH::PersistedObjectSetFactory::getSingleton().getConstructor(objpersistentset_type)(ctx, objpersistentset_options);
oh->setPersistentSet(obj_persistent_set);
String objfactory_type = GetOptionValue<String>(OPT_OBJECT_FACTORY);
String objfactory_options = GetOptionValue<String>(OPT_OBJECT_FACTORY_OPTS);
ObjectFactory* obj_factory = NULL;
String obj_query_type = GetOptionValue<String>(OPT_OBJECT_QUERY_PROCESSOR);
String obj_query_options = GetOptionValue<String>(OPT_OBJECT_QUERY_PROCESSOR_OPTS);
OH::ObjectQueryProcessor* obj_query_processor =
OH::ObjectQueryProcessorFactory::getSingleton().getConstructor(obj_query_type)(ctx, obj_query_options);
oh->setQueryProcessor(obj_query_processor);
///////////Go go go!! start of simulation/////////////////////
ctx->add(ctx);
ctx->add(obj_storage);
ctx->add(obj_persistent_set);
ctx->add(obj_query_processor);
ctx->add(oh);
ctx->add(sstConnMgr);
ctx->add(ohSstConnMgr);
if (!objfactory_type.empty())
{
obj_factory = ObjectFactoryFactory::getSingleton().getConstructor(objfactory_type)(ctx, oh, mainSpace, objfactory_options);
obj_factory->generate();
}
ctx->run(1);
ctx->cleanup();
if (GetOptionValue<bool>(PROFILE)) {
ctx->profiler->report();
}
trace->prepareShutdown();
Mesh::FilterFactory::destroy();
ModelsSystemFactory::destroy();
ObjectScriptManagerFactory::destroy();
delete oh;
delete obj_storage;
delete obj_persistent_set;
SimulationFactory::destroy();
delete ctx;
delete commander;
delete time_series;
trace->shutdown();
delete trace;
trace = NULL;
delete mainStrand;
delete ios;
delete sstConnMgr;
delete ohSstConnMgr;
plugins.gc();
sync.stop();
Sirikata::Logging::finishLog();
return 0;
}
<|endoftext|> |
<commit_before>#include <check.h>
#include <stdint.h>
#include "queue.h"
START_TEST (test_push)
{
ByteQueue queue;
queue_init(&queue);
int length = queue_length(&queue);
fail_unless(length == 0, "expected queue length of 0 but got %d", length);
bool success = queue_push(&queue, 0xEF);
fail_unless(success);
fail_unless(queue_length(&queue) == 1,
"expected queue length of 1 but got %d", length);
}
END_TEST
START_TEST (test_pop)
{
ByteQueue queue;
queue_init(&queue);
uint8_t original_value = 0xEF;
queue_push(&queue, original_value);
uint8_t value = queue_pop(&queue);
fail_unless(value == original_value);
}
END_TEST
START_TEST (test_fill_er_up)
{
ByteQueue queue;
queue_init(&queue);
for(uint8_t i = 0; i < MAX_QUEUE_LENGTH; i++) {
bool success = queue_push(&queue, i);
fail_unless(success, "wasn't able to add the %dth element", i + 1);
}
for(uint8_t i = 0; i < MAX_QUEUE_LENGTH; i++) {
uint8_t value = queue_pop(&queue);
if(i < MAX_QUEUE_LENGTH - 1) {
fail_unless(!queue_empty(&queue),
"didn't expect queue to be empty on %dth iteration", i + 1);
}
fail_unless(value == i, "expected %d but got %d out of the queue",
i, value);
}
fail_unless(queue_empty(&queue));
}
END_TEST
START_TEST (test_length)
{
ByteQueue queue;
queue_init(&queue);
fail_unless(queue_length(&queue) == 0);
for(uint8_t i = 0; i < MAX_QUEUE_LENGTH; i++) {
queue_push(&queue, i);
if(i == MAX_QUEUE_LENGTH - 1) {
break;
}
fail_unless(queue_length(&queue) == i + 1,
"expected length of %d but found %d", i + 1,
queue_length(&queue));
}
for(uint8_t i = 0; i < MAX_QUEUE_LENGTH; i++) {
queue_pop(&queue);
fail_unless(queue_length(&queue) == MAX_QUEUE_LENGTH - i - 1);
}
fail_unless(queue_length(&queue) == 0);
for(uint8_t i = 0; i < MAX_QUEUE_LENGTH; i++) {
queue_push(&queue, i);
fail_unless(queue_length(&queue) == i + 1,
"expected length of %d but found %d", i + 1,
queue_length(&queue));
}
for(uint8_t i = 0; i < MAX_QUEUE_LENGTH / 2; i++) {
queue_pop(&queue);
fail_unless(queue_length(&queue) == MAX_QUEUE_LENGTH - i - 1);
}
for(uint8_t i = 0; i < MAX_QUEUE_LENGTH / 2; i++) {
queue_push(&queue, i);
int expectedLength = i + (MAX_QUEUE_LENGTH / 2) + 1;
fail_unless(queue_length(&queue) == expectedLength,
"expected length of %d but found %d", expectedLength,
queue_length(&queue));
}
}
END_TEST
Suite* suite(void) {
Suite* s = suite_create("queue");
TCase *tc_core = tcase_create("core");
tcase_add_test(tc_core, test_push);
tcase_add_test(tc_core, test_pop);
tcase_add_test(tc_core, test_fill_er_up);
tcase_add_test(tc_core, test_length);
suite_add_tcase(s, tc_core);
return s;
}
int main(void) {
int numberFailed;
Suite* s = suite();
SRunner *sr = srunner_create(s);
// Don't fork so we can actually use gdb
srunner_set_fork_status(sr, CK_NOFORK);
srunner_run_all(sr, CK_NORMAL);
numberFailed = srunner_ntests_failed(sr);
srunner_free(sr);
return (numberFailed == 0) ? 0 : 1;
}
<commit_msg>Make sure queue tests cases still work with queue lengths > 255.<commit_after>#include <check.h>
#include <stdint.h>
#include "queue.h"
START_TEST (test_push)
{
ByteQueue queue;
queue_init(&queue);
int length = queue_length(&queue);
fail_unless(length == 0, "expected queue length of 0 but got %d", length);
bool success = queue_push(&queue, 0xEF);
fail_unless(success);
fail_unless(queue_length(&queue) == 1,
"expected queue length of 1 but got %d", length);
}
END_TEST
START_TEST (test_pop)
{
ByteQueue queue;
queue_init(&queue);
uint8_t original_value = 0xEF;
queue_push(&queue, original_value);
uint8_t value = queue_pop(&queue);
fail_unless(value == original_value);
}
END_TEST
START_TEST (test_fill_er_up)
{
ByteQueue queue;
queue_init(&queue);
for(int i = 0; i < MAX_QUEUE_LENGTH; i++) {
bool success = queue_push(&queue, (uint8_t) (i % 255));
fail_unless(success, "wasn't able to add the %dth element", i + 1);
}
for(int i = 0; i < MAX_QUEUE_LENGTH; i++) {
uint8_t value = queue_pop(&queue);
if(i < MAX_QUEUE_LENGTH - 1) {
fail_unless(!queue_empty(&queue),
"didn't expect queue to be empty on %dth iteration", i + 1);
}
uint8_t expected = i % 255;
fail_unless(value == expected,
"expected %d but got %d out of the queue", expected, value);
}
fail_unless(queue_empty(&queue));
}
END_TEST
START_TEST (test_length)
{
ByteQueue queue;
queue_init(&queue);
fail_unless(queue_length(&queue) == 0);
for(int i = 0; i < MAX_QUEUE_LENGTH; i++) {
queue_push(&queue, (uint8_t) (i % 255));
if(i == MAX_QUEUE_LENGTH - 1) {
break;
}
fail_unless(queue_length(&queue) == i + 1,
"expected length of %d but found %d", i + 1,
queue_length(&queue));
}
for(int i = 0; i < MAX_QUEUE_LENGTH; i++) {
queue_pop(&queue);
fail_unless(queue_length(&queue) == MAX_QUEUE_LENGTH - i - 1);
}
fail_unless(queue_length(&queue) == 0);
for(int i = 0; i < MAX_QUEUE_LENGTH; i++) {
queue_push(&queue, (uint8_t) (i % 255));
fail_unless(queue_length(&queue) == i + 1,
"expected length of %d but found %d", i + 1,
queue_length(&queue));
}
for(int i = 0; i < MAX_QUEUE_LENGTH / 2; i++) {
queue_pop(&queue);
fail_unless(queue_length(&queue) == MAX_QUEUE_LENGTH - i - 1);
}
for(int i = 0; i < MAX_QUEUE_LENGTH / 2; i++) {
queue_push(&queue, (uint8_t) (i % 255));
int expectedLength = i + (MAX_QUEUE_LENGTH / 2) + 1;
fail_unless(queue_length(&queue) == expectedLength,
"expected length of %d but found %d", expectedLength,
queue_length(&queue));
}
}
END_TEST
Suite* suite(void) {
Suite* s = suite_create("queue");
TCase *tc_core = tcase_create("core");
tcase_add_test(tc_core, test_push);
tcase_add_test(tc_core, test_pop);
tcase_add_test(tc_core, test_fill_er_up);
tcase_add_test(tc_core, test_length);
suite_add_tcase(s, tc_core);
return s;
}
int main(void) {
int numberFailed;
Suite* s = suite();
SRunner *sr = srunner_create(s);
// Don't fork so we can actually use gdb
srunner_set_fork_status(sr, CK_NOFORK);
srunner_run_all(sr, CK_NORMAL);
numberFailed = srunner_ntests_failed(sr);
srunner_free(sr);
return (numberFailed == 0) ? 0 : 1;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* 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: dx_bitmap.hxx,v $
* $Revision: 1.3 $
*
* 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 _DXCANVAS_DXBITMAP_HXX
#define _DXCANVAS_DXBITMAP_HXX
#include <com/sun/star/rendering/XCanvas.hpp>
#include <com/sun/star/rendering/XIntegerBitmap.hpp>
#include <canvas/rendering/isurfaceproxy.hxx>
#include <canvas/rendering/isurfaceproxymanager.hxx>
#include <boost/shared_ptr.hpp>
#include <basegfx/vector/b2ivector.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/range/b2drange.hxx>
#include "dx_canvasfont.hxx" //winstuff
#include "dx_gdiplususer.hxx"
#include "dx_rendermodule.hxx"
namespace dxcanvas
{
typedef ::boost::shared_ptr< class SurfaceGraphics > SurfaceGraphicsSharedPtr;
class DXBitmap
{
public:
DXBitmap( const ::basegfx::B2IVector& rSize,
const canvas::ISurfaceProxyManagerSharedPtr& rMgr,
const IDXRenderModuleSharedPtr& rRenderModule,
bool bWithAlpha );
bool resize( const ::basegfx::B2IVector& rSize );
void clear();
bool hasAlpha() const;
BitmapSharedPtr getBitmap();
SurfaceGraphicsSharedPtr getGraphics() const;
COMReference<surface_type> getSurface() const { return mpSurface; }
::basegfx::B2IVector getSize() { return maSize; }
bool draw( double fAlpha,
const ::basegfx::B2DPoint& rPos,
const ::basegfx::B2DHomMatrix& rTransform );
bool draw( const ::basegfx::B2IRange& rArea );
bool draw( double fAlpha,
const ::basegfx::B2DPoint& rPos,
const ::basegfx::B2DRange& rArea,
const ::basegfx::B2DHomMatrix& rTransform );
bool draw( double fAlpha,
const ::basegfx::B2DPoint& rPos,
const ::basegfx::B2DPolyPolygon& rClipPoly,
const ::basegfx::B2DHomMatrix& rTransform );
::com::sun::star::uno::Sequence< sal_Int8 > getData(
::com::sun::star::rendering::IntegerBitmapLayout& bitmapLayout,
const ::com::sun::star::geometry::IntegerRectangle2D& rect );
void setData(
const ::com::sun::star::uno::Sequence< sal_Int8 >& data,
const ::com::sun::star::rendering::IntegerBitmapLayout& bitmapLayout,
const ::com::sun::star::geometry::IntegerRectangle2D& rect );
void setPixel(
const ::com::sun::star::uno::Sequence< sal_Int8 >& color,
const ::com::sun::star::rendering::IntegerBitmapLayout& bitmapLayout,
const ::com::sun::star::geometry::IntegerPoint2D& pos );
::com::sun::star::uno::Sequence< sal_Int8 > getPixel(
::com::sun::star::rendering::IntegerBitmapLayout& bitmapLayout,
const ::com::sun::star::geometry::IntegerPoint2D& pos );
private:
#ifdef DX_DEBUG_IMAGES
void imageDebugger();
#endif
void init();
// Refcounted global GDI+ state container
GDIPlusUserSharedPtr mpGdiPlusUser;
// size of this image in pixels [integral unit]
::basegfx::B2IVector maSize;
// pointer to the rendermodule, needed to create surfaces
// which are used as container for the actual pixel data.
// generally we could use any kind of storage, but GDI+
// is not willing to render antialiased fonts unless we
// use this special kind of container, don't ask me why...
IDXRenderModuleSharedPtr mpRenderModule;
// pointer to the surface manager, needed in case clients
// want to resize the bitmap.
canvas::ISurfaceProxyManagerSharedPtr mpSurfaceManager;
// access point to the surface proxy which handles
// the hardware-dependent rendering stuff.
canvas::ISurfaceProxySharedPtr mpSurfaceProxy;
// container for pixel data, we need to use a directx
// surface since GDI+ sucks...
COMReference<surface_type> mpSurface;
// since GDI+ does not work correctly in case we
// run on a 16bit display [don't ask me why] we need
// to occasionally render to a native GDI+ bitmap.
BitmapSharedPtr mpGDIPlusBitmap;
// internal implementation of the iColorBuffer interface
canvas::IColorBufferSharedPtr mpColorBuffer;
// indicates wether the associated surface needs
// to refresh its contents or not. in other words,
// this flag is set iff both representations are
// out of sync.
mutable bool mbIsSurfaceDirty;
// true if the bitmap contains an alpha channel
bool mbAlpha;
};
typedef ::boost::shared_ptr< DXBitmap > DXBitmapSharedPtr;
}
#endif
<commit_msg>INTEGRATION: CWS canvas05 (1.2.2); FILE MERGED 2008/06/03 23:52:23 thb 1.2.2.4: Removed extra level of indirection for getting a graphics for a surface; removed some unused code 2008/04/21 07:30:26 thb 1.2.2.3: RESYNC: (1.2-1.3); FILE MERGED 2008/02/08 00:26:38 thb 1.2.2.2: #81092# Finishing cooperative canvas output stuff 2008/01/22 00:25:23 thb 1.2.2.1: #i81092# Making gdiplus and dx canvas more independent<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: dx_bitmap.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 _DXCANVAS_DXBITMAP_HXX
#define _DXCANVAS_DXBITMAP_HXX
#include <com/sun/star/rendering/XCanvas.hpp>
#include <com/sun/star/rendering/XIntegerBitmap.hpp>
#include <boost/shared_ptr.hpp>
#include <basegfx/vector/b2ivector.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/range/b2drange.hxx>
#include "dx_winstuff.hxx"
#include "dx_ibitmap.hxx"
#include "dx_graphicsprovider.hxx"
#include "dx_gdiplususer.hxx"
namespace dxcanvas
{
class DXBitmap : public IBitmap
{
public:
DXBitmap( const BitmapSharedPtr& rBitmap,
bool bWithAlpha );
DXBitmap( const ::basegfx::B2IVector& rSize,
bool bWithAlpha );
virtual GraphicsSharedPtr getGraphics();
virtual BitmapSharedPtr getBitmap() const;
virtual ::basegfx::B2IVector getSize() const;
virtual bool hasAlpha() const;
::com::sun::star::uno::Sequence< sal_Int8 > getData(
::com::sun::star::rendering::IntegerBitmapLayout& bitmapLayout,
const ::com::sun::star::geometry::IntegerRectangle2D& rect );
void setData(
const ::com::sun::star::uno::Sequence< sal_Int8 >& data,
const ::com::sun::star::rendering::IntegerBitmapLayout& bitmapLayout,
const ::com::sun::star::geometry::IntegerRectangle2D& rect );
void setPixel(
const ::com::sun::star::uno::Sequence< sal_Int8 >& color,
const ::com::sun::star::rendering::IntegerBitmapLayout& bitmapLayout,
const ::com::sun::star::geometry::IntegerPoint2D& pos );
::com::sun::star::uno::Sequence< sal_Int8 > getPixel(
::com::sun::star::rendering::IntegerBitmapLayout& bitmapLayout,
const ::com::sun::star::geometry::IntegerPoint2D& pos );
private:
// Refcounted global GDI+ state container
GDIPlusUserSharedPtr mpGdiPlusUser;
// size of this image in pixels [integral unit]
::basegfx::B2IVector maSize;
BitmapSharedPtr mpBitmap;
GraphicsSharedPtr mpGraphics;
// true if the bitmap contains an alpha channel
bool mbAlpha;
};
typedef ::boost::shared_ptr< DXBitmap > DXBitmapSharedPtr;
}
#endif
<|endoftext|> |
<commit_before>/*
This file is part of KXForms.
Copyright (c) 2007 Andre Duffeck <aduffeck@suse.de>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "changelabelaction.h"
#include "editor.h"
#include "editorwidget.h"
#include "../hints.h"
#include "../guielement.h"
#include <kinputdialog.h>
#include <kdebug.h>
#include <klocale.h>
using namespace KXForms;
ChangeLabelAction::ChangeLabelAction( Editor *e)
: EditorAction( e )
{
}
ChangeLabelAction::~ChangeLabelAction()
{
}
void ChangeLabelAction::perform( EditorWidget *w )
{
kDebug() << k_funcinfo << endl;
editor()->beginEdit();
Hint h;
QString newLabel;
bool ok;
newLabel = KInputDialog::getText( i18n("Enter the new label"), i18n("Label for %1", w->element()->ref().toString()),
QString(), &ok );
if( ok ) {
kDebug() << k_funcinfo << "New Label: " << newLabel << endl;
}
editor()->finishEdit();
}
#include "changelabelaction.moc"
<commit_msg>Generate and emit hint.<commit_after>/*
This file is part of KXForms.
Copyright (c) 2007 Andre Duffeck <aduffeck@suse.de>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "changelabelaction.h"
#include "editor.h"
#include "editorwidget.h"
#include "../hints.h"
#include "../guielement.h"
#include <kinputdialog.h>
#include <kdebug.h>
#include <klocale.h>
using namespace KXForms;
ChangeLabelAction::ChangeLabelAction( Editor *e)
: EditorAction( e )
{
}
ChangeLabelAction::~ChangeLabelAction()
{
}
void ChangeLabelAction::perform( EditorWidget *w )
{
kDebug() << k_funcinfo << endl;
editor()->beginEdit();
Hint h;
QString newLabel;
bool ok;
newLabel = KInputDialog::getText( i18n("Enter the new label"), i18n("Label for %1", w->element()->ref().toString()),
QString(), &ok );
if( ok ) {
kDebug() << k_funcinfo << "New Label: " << newLabel << endl;
h.setRef( w->element()->ref() );
h.setValue( Hint::Label, newLabel );
emit hintGenerated( h );
}
editor()->finishEdit();
}
#include "changelabelaction.moc"
<|endoftext|> |
<commit_before>#include <iostream>
#include "acmacs-base/argc-argv.hh"
#include "acmacs-base/string.hh"
#include "acmacs-base/range.hh"
#include "acmacs-base/stream.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-chart-2/chart.hh"
#include "seqdb/seqdb.hh"
#include "hidb-5/hidb.hh"
#include "hidb-5/report.hh"
// ----------------------------------------------------------------------
struct AntigenData
{
size_t no;
const hidb::HiDb* hidb = nullptr;
std::shared_ptr<acmacs::chart::Antigen> antigen_chart;
std::shared_ptr<hidb::Antigen> antigen_hidb;
seqdb::SeqdbEntrySeq antigen_seqdb;
};
inline std::ostream& operator<<(std::ostream& out, const AntigenData& ag)
{
out << ag.no << ' ' << *ag.antigen_chart;
if (ag.antigen_hidb)
hidb::report_tables(out, *ag.hidb, ag.antigen_hidb->tables(), hidb::report_tables::recent, "\n ");
if (ag.antigen_seqdb) {
if (const auto& clades = ag.antigen_seqdb.seq().clades(); !clades.empty())
out << "\n clades: " << clades;
}
return out;
}
// ----------------------------------------------------------------------
int main(int argc, char* const argv[])
{
int exit_code = 0;
try {
argc_argv args(argc, argv,
{
{"--sort-by-tables", false},
{"--clade", ""},
{"--db-dir", ""},
{"-h", false},
{"--help", false},
{"-v", false},
{"--verbose", false},
});
if (args["-h"] || args["--help"] || args.number_of_arguments() != 1) {
std::cerr << "Usage: " << args.program() << " [options] <chart-file>\n" << args.usage_options() << '\n';
exit_code = 1;
}
else {
const bool verbose = args["-v"] || args["--verbose"];
const bool sort_by_tables = args["--sort-by-tables"];
const std::string clade = args["--clade"];
seqdb::setup_dbs(args["--db-dir"], verbose ? seqdb::report::yes : seqdb::report::no);
auto chart = acmacs::chart::import_from_file(args[0], acmacs::chart::Verify::None, report_time::No);
const auto virus_type = chart->info()->virus_type(acmacs::chart::Info::Compute::Yes);
const auto& seqdb = seqdb::get();
const auto& hidb = hidb::get(virus_type, verbose ? report_time::Yes : report_time::No);
auto antigens_chart = chart->antigens();
const auto hidb_antigens = hidb.antigens()->find(*antigens_chart);
const auto seqdb_antigens = seqdb.match(*antigens_chart, virus_type);
std::vector<AntigenData> antigens(antigens_chart->size());
std::transform(acmacs::index_iterator(0UL), acmacs::index_iterator(antigens_chart->size()), antigens.begin(), [&](size_t index) -> AntigenData {
return {index, &hidb, antigens_chart->at(index), hidb_antigens[index], seqdb_antigens[index]};
});
if (!clade.empty()) {
antigens.erase(std::remove_if(antigens.begin(), antigens.end(), [&](const auto& ag) -> bool { return !ag.antigen_seqdb || !ag.antigen_seqdb.seq().has_clade(clade); }), antigens.end());
}
std::cerr << "INFO: " << antigens.size() << " antigens upon filtering\n";
if (sort_by_tables) {
auto hidb_tables = hidb.tables();
std::sort(antigens.begin(), antigens.end(), [&](const auto& e1, const auto& e2) -> bool {
if (!e1.antigen_hidb)
return false;
if (!e2.antigen_hidb)
return true;
if (const auto nt1 = e1.antigen_hidb->number_of_tables(), nt2 = e2.antigen_hidb->number_of_tables(); nt1 == nt2) {
auto mrt1 = hidb_tables->most_recent(e1.antigen_hidb->tables()), mrt2 = hidb_tables->most_recent(e2.antigen_hidb->tables());
return mrt1->date() > mrt2->date();
}
else
return nt1 > nt2;
});
}
for (const auto& ad : antigens)
std::cout << ad << '\n';
}
}
catch (std::exception& err) {
std::cerr << "ERROR: " << err.what() << '\n';
exit_code = 2;
}
return exit_code;
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>whocc-chart-hidb-seqdb-report<commit_after>#include <iostream>
#include "acmacs-base/argc-argv.hh"
#include "acmacs-base/string.hh"
#include "acmacs-base/string-split.hh"
#include "acmacs-base/range.hh"
#include "acmacs-base/stream.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-chart-2/chart.hh"
#include "seqdb/seqdb.hh"
#include "hidb-5/hidb.hh"
#include "hidb-5/report.hh"
// ----------------------------------------------------------------------
struct AntigenData
{
size_t no;
const hidb::HiDb* hidb = nullptr;
std::shared_ptr<acmacs::chart::Antigen> antigen_chart;
std::shared_ptr<hidb::Antigen> antigen_hidb;
seqdb::SeqdbEntrySeq antigen_seqdb;
};
inline std::ostream& operator<<(std::ostream& out, const AntigenData& ag)
{
out << ag.no << ' ' << *ag.antigen_chart;
if (ag.antigen_hidb)
hidb::report_tables(out, *ag.hidb, ag.antigen_hidb->tables(), hidb::report_tables::recent, "\n ");
if (ag.antigen_seqdb) {
if (const auto& clades = ag.antigen_seqdb.seq().clades(); !clades.empty())
out << "\n clades: " << clades;
}
return out;
}
// ----------------------------------------------------------------------
int main(int argc, char* const argv[])
{
int exit_code = 0;
try {
argc_argv args(argc, argv,
{
{"--sort-by-tables", false},
{"--clade", ""},
{"--aa", "", "report AA at given positions (comma separated)"},
{"--db-dir", ""},
{"-h", false},
{"--help", false},
{"-v", false},
{"--verbose", false},
});
if (args["-h"] || args["--help"] || args.number_of_arguments() != 1) {
std::cerr << "Usage: " << args.program() << " [options] <chart-file>\n" << args.usage_options() << '\n';
exit_code = 1;
}
else {
const bool verbose = args["-v"] || args["--verbose"];
const bool sort_by_tables = args["--sort-by-tables"];
const std::string clade = args["--clade"];
const auto report_aa_at_pos = acmacs::string::split_into_uint(static_cast<std::string>(args["--aa"]), ",");
seqdb::setup_dbs(args["--db-dir"], verbose ? seqdb::report::yes : seqdb::report::no);
auto chart = acmacs::chart::import_from_file(args[0], acmacs::chart::Verify::None, report_time::No);
const auto virus_type = chart->info()->virus_type(acmacs::chart::Info::Compute::Yes);
const auto& seqdb = seqdb::get();
const auto& hidb = hidb::get(virus_type, verbose ? report_time::Yes : report_time::No);
auto antigens_chart = chart->antigens();
const auto hidb_antigens = hidb.antigens()->find(*antigens_chart);
const auto seqdb_antigens = seqdb.match(*antigens_chart, virus_type);
std::vector<AntigenData> antigens(antigens_chart->size());
std::transform(acmacs::index_iterator(0UL), acmacs::index_iterator(antigens_chart->size()), antigens.begin(), [&](size_t index) -> AntigenData {
return {index, &hidb, antigens_chart->at(index), hidb_antigens[index], seqdb_antigens[index]};
});
if (!clade.empty()) {
antigens.erase(std::remove_if(antigens.begin(), antigens.end(), [&](const auto& ag) -> bool { return !ag.antigen_seqdb || !ag.antigen_seqdb.seq().has_clade(clade); }), antigens.end());
}
std::cerr << "INFO: " << antigens.size() << " antigens upon filtering\n";
if (sort_by_tables) {
auto hidb_tables = hidb.tables();
std::sort(antigens.begin(), antigens.end(), [&](const auto& e1, const auto& e2) -> bool {
if (!e1.antigen_hidb)
return false;
if (!e2.antigen_hidb)
return true;
if (const auto nt1 = e1.antigen_hidb->number_of_tables(), nt2 = e2.antigen_hidb->number_of_tables(); nt1 == nt2) {
auto mrt1 = hidb_tables->most_recent(e1.antigen_hidb->tables()), mrt2 = hidb_tables->most_recent(e2.antigen_hidb->tables());
return mrt1->date() > mrt2->date();
}
else
return nt1 > nt2;
});
}
for (const auto& ad : antigens) {
std::cout << ad << '\n';
if (!report_aa_at_pos.empty()) {
const auto aa = ad.antigen_seqdb.seq().amino_acids(true);
std::cout << " ";
for (auto pos : report_aa_at_pos) {
std::cout << ' ' << pos;
if (aa.size() >= pos)
std::cout << aa[pos - 1];
else
std::cout << '?';
}
std::cout << '\n';
}
}
}
}
catch (std::exception& err) {
std::cerr << "ERROR: " << err.what() << '\n';
exit_code = 2;
}
return exit_code;
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>using namespace std;
#include "classes.h"
/**
This is the main function of my support deck solver. From here you may enter into three different functions:
1) Brute force support deck combination solver
2) Statistics analysis
3) Print to screen info about cards
**/
int main(){
int x,i, z=0, choice, get_skill, new_search, translator, keep_adding;
int path, is_double=0, wants_max_cost=0, user_max_cost;
bool still_in_use=true, continue_with_solving;
ifstream myfile;
//the following four functions create the data used by the program
create_Database(&allsupportskills, &all_cards, &unique_affiliations, &affiliation_array);
//check if any new profiles exist
checkForNewProfiles(&unique_affiliations);
do{
cout << "Check combinations (1) or check stats (2) or print profile info (3) or Quit (0)? : ";
cin >> path;
while(!(cin.good()) || path<0 || path>3){
cin.clear();
cin.ignore(256, '\n');
cout << "Please enter a valid choice: ";
cin >> path;
}
if(path==1){
reset_support_deck(&supportdeck);
cout << "\n\nHow many skills (2 - 6) do you want in your support deck?: ";
cin >> supportdeck.number_of_skills;
while(!(cin.good()) || supportdeck.number_of_skills>6 || supportdeck.number_of_skills<2){
cin.clear();
cin.ignore(256, '\n');
cout << "Please enter a number from 2 to 6: ";
cin >>supportdeck.number_of_skills;
}
cout << "\n\nHow many total cards (" << supportdeck.number_of_skills << " - " << SUPPORTDECK << ") do you want in your support deck?: ";
cin >> supportdeck.total_cards_to_use;
while(!(cin.good()) || supportdeck.total_cards_to_use>SUPPORTDECK || supportdeck.total_cards_to_use<supportdeck.number_of_skills){
cin.clear();
cin.ignore(256, '\n');
cout << "Please enter a number from " << supportdeck.number_of_skills << " to " << SUPPORTDECK << ": ";
cin >>supportdeck.total_cards_to_use;
}
cout << "\n\nSet a maximum cap cost? (Yes = 1): ";
cin >> wants_max_cost;
if(wants_max_cost==1){
cout << "\n\tEnter the desired maximum cap cost (not less than zero): ";
cin >> user_max_cost;
while(!(cin.good()) || user_max_cost<0){
cin.clear();
cin.ignore(256, '\n');
cout << "\n\n\tInvalid entry.";
cout << "\n\tEnter the desired maximum cap cost (not less than zero): ";
cin >> user_max_cost;
}
supportdeck.user_set_max_cost=user_max_cost;
supportdeck.max_cost_set=true;
}
if(supportdeck.number_of_skills>1){
cout << "\n\nEnforce minimum skill levels? (Yes = 1): ";
cin >> choice;
supportdeck.looking_for_specific_level=1;
if(!(cin.good()) || choice!=1){
cin.clear();
cin.ignore(256, '\n');
choice=0;
supportdeck.looking_for_specific_level=0;
}
cout << endl;
for(z=0;z<allsupportskills.numberOfSkills;z++){
cout << z+1 << ") " << allsupportskills.supportskill[z].skillName << endl;
}
cout << "\n\n";
for(x=0;x<supportdeck.number_of_skills;x++){
do{
cout << "Please choose a skill: ";
cin >> get_skill;
while(!(cin.good()) ){
if( !(cin >> get_skill) ){
cin.clear();
cin.ignore(256, '\n');
}
}
if(get_skill>allsupportskills.numberOfSkills || get_skill<1){
cout << "\n\tPlease enter a number from 1 to " << allsupportskills.numberOfSkills << endl << endl;
}
is_double=0;
for(i=0;i<x;i++){
if(get_skill-1==supportdeck.skill_locator[i]){
is_double=1;
}
}
if(is_double==1){
cout << "\n\tSkill already chosen - choose a different one.\n\n";
}
}while(get_skill>allsupportskills.numberOfSkills || get_skill<1 || is_double==1);
supportdeck.skills_in_deck[x]=allsupportskills.supportskill[get_skill-1].skillName;
supportdeck.skill_locator[x]=get_skill-1;
for(i=0;i<allsupportskills.supportskill[get_skill-1].numberOfCards;i++){
cout << i+1 << ") " << allsupportskills.supportskill[get_skill-1].supportskillcard[i].rarity << "* " << allsupportskills.supportskill[get_skill-1].supportskillcard[i].charactername << "\n";
}
cout << "\nIgnore any skill cards? Enter the index of those you don't want to search - enter 0 when ready to proceed: ";
keep_adding=0;
do{
cin>>translator;
if(!(cin.good()) || translator<0 || translator>allsupportskills.supportskill[get_skill-1].numberOfCards){
cin.clear();
cin.ignore(256,'\n');
cout << "\n\tInvalid entry\n";
}else
if(translator==0){
break;
}else{
new_search=0;
for(i=0;i<keep_adding;i++){
if(supportdeck.ignore_list[x][i]!=(translator-1)){
new_search++;
}
}
if(new_search==keep_adding){
supportdeck.ignore_list[x][keep_adding]=translator-1;
keep_adding++;
}
}
if(keep_adding == (allsupportskills.supportskill[get_skill-1].numberOfCards-1) ){
break;
}
}while(1==1);
supportdeck.num_ignored_cards[x]=keep_adding;
supportdeck.num_allowed_cards[x]=allsupportskills.supportskill[get_skill-1].numberOfCards-keep_adding;
if(choice==1){
if(allsupportskills.supportskill[get_skill-1].max_level==1){
supportdeck.skill_threshold[x]=1;
}else{
cout << "\nSet minimum skill level (";
for(z=0;z<allsupportskills.supportskill[get_skill-1].max_level;z++){
cout << z+1;
if(z+1<allsupportskills.supportskill[get_skill-1].max_level){
cout << ", ";
}else{
cout << "): ";
}
}
cin >> supportdeck.skill_threshold[x];
while(!(cin.good()) || supportdeck.skill_threshold[x]>allsupportskills.supportskill[get_skill-1].max_level || supportdeck.skill_threshold[x]<1){
cout << "\nInvalid value. Enter again: ";
cin.clear();
cin.ignore(256, '\n');
cin >> supportdeck.skill_threshold[x];
}
}
}else{
supportdeck.skill_threshold[x]=1;
}
cout << "\n\n";
}
continue_with_solving=true;
if(checkIfFileExists(&supportdeck,&allsupportskills)){
cout << "\n\nA file containing combinations for these skills already exists.";
cout << "\nRunning the solver will overwrite the exisiting file.";
cout << "\n\n\tContinue with solving? (Yes = 1): ";
cin >> continue_with_solving;
if(!cin.good()){
cin.clear();
cin.ignore(256,'\n');
continue_with_solving=false;
}
}
if(continue_with_solving){
if(supportdeck.total_cards_to_use>supportdeck.number_of_skills){
cout << "Enter the minimum number of matching types per card: ";
cin >> supportdeck.type_threshold;
while(!(cin.good()) || supportdeck.type_threshold<0 || supportdeck.type_threshold>MAXTYPES){
cout << "\nInvalid value. Enter again: ";
cin.clear();
cin.ignore(256, '\n');
cin >> supportdeck.type_threshold;
}
cout << "\n\nQuery through which rarity (5 4 3 2 1)? : ";
cin >> supportdeck.using_rarity;
if( !(cin.good()) || supportdeck.using_rarity<1 || supportdeck.using_rarity>5){
cin.clear();
cin.ignore(256, '\n');
supportdeck.using_rarity=4;
}
}
cout << "\n\nStop searching after a certain number of solutions? (Yes = 1): ";
cin >> supportdeck.breaking_early;
if( !(cin.good()) || supportdeck.breaking_early!=1){
cin.clear();
cin.ignore(256, '\n');
supportdeck.breaking_early=0;
supportdeck.breaking_at_solution=0;
}else{
cout << "\n\tSearch for how many solutions?: ";
cin >> supportdeck.breaking_at_solution;
while(!(cin.good()) || supportdeck.breaking_at_solution<1){
cout << "\nInvalid value. Enter again: ";
cin.clear();
cin.ignore(256, '\n');
cin >> supportdeck.breaking_at_solution;
}
}
construct_support_deck(&supportdeck, &allsupportskills, &all_cards, &unique_affiliations);
}
}else{
cout << "\n\n\t\tThanks for using the support skill optimizer!!";
}
}else
if(path==2){
check_stats(&all_cards,&unique_affiliations,&affiliation_array, &allsupportskills);
}else
if(path==3){
print_info(&allsupportskills,&all_cards);
}else
if(path==0){
still_in_use=false;
}
if(path!=0){
cout << "\n\n\n\t\tDo something else? (Yes = 1): ";
cin >> still_in_use;
if( !(cin.good())){
cin.clear();
cin.ignore(256, '\n');
still_in_use=false;
}
}
cout << "\n\n";
}while(still_in_use);
return 0;
}
<commit_msg>Delete main.cpp<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <string>
void run_part_one() {
}
void run_part_two() {
}
int main(int argc, char* argv[]) {
if (argc > 1) {
if (std::string(argv[1]) == "--part_two") {
run_part_two();
} else {
std::cout << "Usage: day4 [--part_two]" << std::endl;
return -1;
}
} else {
run_part_one();
}
}
<commit_msg>added runtime code for first part of day4<commit_after>#include <iostream>
#include <string>
#include "md5.hpp"
void run_part_one() {
std::cout << find_lowest_zeroes_value("ckczppom") << std::endl;
}
void run_part_two() {
}
int main(int argc, char* argv[]) {
if (argc > 1) {
if (std::string(argv[1]) == "--part_two") {
run_part_two();
} else {
std::cout << "Usage: day4 [--part_two]" << std::endl;
return -1;
}
} else {
run_part_one();
}
}
<|endoftext|> |
<commit_before>// Copyright(c) Andre Caron, 2009-2010
//
// This document is covered by the Artistic License 2.0 (Open Source Initiative
// approved license). A copy of the license should have been provided alongside
// this software package (see "license.rtf"). If not, the license is available
// online at "http://www.opensource.org/licenses/artistic-license-2.0.php".
#include <w32.com.hpp>
#include <w32.shl.hpp>
#include <iomanip>
#include <iostream>
#include <w32/console-program.hpp>
namespace {
const w32::com::Guid SERVER(
0x5450A57D,0xF5A6,0x42fC,0x87,0xBD,0x7D,0x0F,0xB1,0x9F,0xE9,0xA7
); // {5450A57D-F5A6-42fC-87BD-7D0FB19FE9A7}
const w32::string FILE = "C:\\Users\\Andr\\Desktop\\foo.ftp";
int run ( int argc, wchar_t ** argv )
try
{
const w32::com::Library _;
#if 0
w32::shl::Attributes attributes;
attributes |= w32::shl::Attributes::browsable();
attributes |= w32::shl::Attributes::folder();
attributes |= w32::shl::Attributes::subfolders();
attributes |= w32::shl::Attributes::container();
std::cout << std::setw(8) << std::hex
<< attributes.value() << std::endl;
#endif
// Load the extension as an IShellFolder.
const w32::shl::Folder root =
w32::com::instantiate< ::IShellFolder >(SERVER);
// Tell the IShellFolder where it's at.
const w32::shl::Path path = FILE;
const w32::com::Ptr< ::IPersistFolder > persist =
w32::com::cast< ::IPersistFolder >(root.ptr());
persist->Initialize(path.backend());
// Request folder contents.
w32::shl::Folder::Listing listing(root);
for ( w32::shl::Path item; listing.next(item); )
{
std::wcout << L" >> " << (w32::string)item << std::endl;
}
return (EXIT_SUCCESS);
}
catch ( w32::com::Error& error )
{
std::cerr << error.what() << std::endl;
return (EXIT_FAILURE);
}
}
#include <w32/console-program.cpp>
// Link automagically.
#pragma comment ( lib, "w32.lib" )
#pragma comment ( lib, "w32.com.lib" )
#pragma comment ( lib, "w32.dbg.lib" )
#pragma comment ( lib, "w32.shl.lib" )
template<> inline w32::com::Guid
w32::com::guidof< ::IPersistFolder > ()
{
return (IID_IPersistFolder);
}
<commit_msg>Constructor is explicit.<commit_after>// Copyright(c) Andre Caron, 2009-2010
//
// This document is covered by the Artistic License 2.0 (Open Source Initiative
// approved license). A copy of the license should have been provided alongside
// this software package (see "license.rtf"). If not, the license is available
// online at "http://www.opensource.org/licenses/artistic-license-2.0.php".
#include <w32.com.hpp>
#include <w32.shl.hpp>
#include <iomanip>
#include <iostream>
#include <w32/console-program.hpp>
namespace {
const w32::com::Guid SERVER(
0x5450A57D,0xF5A6,0x42fC,0x87,0xBD,0x7D,0x0F,0xB1,0x9F,0xE9,0xA7
); // {5450A57D-F5A6-42fC-87BD-7D0FB19FE9A7}
const w32::string FILE = "C:\\Users\\Andr\\Desktop\\foo.ftp";
int run ( int argc, wchar_t ** argv )
try
{
const w32::com::Library _;
#if 0
w32::shl::Attributes attributes;
attributes |= w32::shl::Attributes::browsable();
attributes |= w32::shl::Attributes::folder();
attributes |= w32::shl::Attributes::subfolders();
attributes |= w32::shl::Attributes::container();
std::cout << std::setw(8) << std::hex
<< attributes.value() << std::endl;
#endif
// Load the extension as an IShellFolder.
const w32::shl::Folder root(
w32::com::instantiate< ::IShellFolder >(SERVER));
// Tell the IShellFolder where it's at.
const w32::shl::Path path = FILE;
const w32::com::Ptr< ::IPersistFolder > persist =
w32::com::cast< ::IPersistFolder >(root.ptr());
persist->Initialize(path.backend());
// Request folder contents.
w32::shl::Folder::Listing listing(root);
for ( w32::shl::Path item; listing.next(item); )
{
std::wcout << L" >> " << (w32::string)item << std::endl;
}
return (EXIT_SUCCESS);
}
catch ( w32::com::Error& error )
{
std::cerr << error.what() << std::endl;
return (EXIT_FAILURE);
}
}
#include <w32/console-program.cpp>
// Link automagically.
#pragma comment ( lib, "w32.lib" )
#pragma comment ( lib, "w32.com.lib" )
#pragma comment ( lib, "w32.dbg.lib" )
#pragma comment ( lib, "w32.shl.lib" )
template<> inline w32::com::Guid
w32::com::guidof< ::IPersistFolder > ()
{
return (IID_IPersistFolder);
}
<|endoftext|> |
<commit_before>// coding: utf-8
// ----------------------------------------------------------------------------
/* Copyright (c) 2012, Roboterclub Aachen e.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Roboterclub Aachen e.V. 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 ROBOTERCLUB AACHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. 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 XPCC__TLC594X_HPP
#define XPCC__TLC594X_HPP
#include <stdint.h>
#include <xpcc/architecture/driver/gpio.hpp>
#include <xpcc/architecture/driver/delay.hpp>
namespace xpcc
{
/**
* \brief TLC594* multi-channel, daisy-chainable, constant-current sink, 12bit PWM LED driver.
*
* This class does not use the DCPRG pin, as writing to the EEPROM requires
* 22V to be applied to Vprog, requiring additional external circuits.
* Use of any EEPROM functions is therefore not implemented here.
* Make sure that pin is connected to Vcc, otherwise Dot Correction does not work.
*
* This class also does not control the BLANK pin, as the setup of the timer
* to drive that pin is platform and configuration specific.
* Switching off all LEDs using one command is not implemented here.
*
* This driver can be used for the 16-channel TLC5940 and 24-channel TLC5947
* and probably similar TLC59s as well, simply by adjusting the number of
* CHANNELS.
* Therefore this class can also be used with daisy-chained TLC59s, e.g.
* to control two TLC5940s set CHANNELS to 2*16.
*
* \tparam CHANNELS Number of channels must be multiples of 4, adjust for daisy-chained chips
* \tparam Spi Spi interface
* \tparam Xlat Level triggered latch pin
* \tparam Vprog Vprog pin, use xpcc::gpio::Unused if not connected
* \tparam Xerr Error pin, use xpcc::gpio::Unused if not connected
*
* \author Niklas Hauser
* \ingroup pwm
*/
template<
uint16_t CHANNELS,
typename Spi,
typename Xlat,
typename Vprog=xpcc::gpio::Unused,
typename Xerr=xpcc::gpio::Unused>
class TLC594X
{
public:
/**
* \param channels initialize channels buffer with value, disable with -1
* \param dots initialize dot correction buffer with value, disable with -1
* \param writeCH write channels value to chip
* \param writeDC write dots value to chip
*/
static void
initialize(uint16_t channels=0, uint8_t dots=63, bool writeCH=true, bool writeDC=true);
/// set the 12bit value of a channel
/// call transfer() to update the chip
static void
setChannel(uint16_t channel, uint16_t value);
/// \param value the 12bit value of all channels
/// \param update write data to chip
static void
setAllChannels(uint16_t value, bool update=false);
/// get the stored 12bit value of a channel
/// this does reflect the actual value in the chip
static uint16_t
getChannel(uint16_t channel);
/// set the 6bit dot correction value of a channel
/// call transfer() to update the chip
static void
setDotCorrection(uint16_t channel, uint8_t value);
/// \param value the 6bit dot correction value of all channels
/// \param update write data to chip
static void
setAllDotCorrection(uint8_t value, bool update=false);
/// get the stored 6bit dot correction value of a channel
/// this does reflect the actual value in the chip
static uint8_t
getDotCorrection(uint16_t channel);
/// transfer channel data to driver chip
static bool
writeChannels(bool flush=true);
/// transfer dot correction data to driver chip
static bool
writeDotCorrection();
/// writes data from the input shift register to either GS or DC register.
inline static void
latch();
/// \return true if LOD or TEF is detected
ALWAYS_INLINE
static bool
isError()
{
return !Xerr::read();
}
ALWAYS_INLINE
static uint8_t*
getGrayscaleData()
{
return gs;
}
ALWAYS_INLINE
static uint8_t*
getDotCorrectionData()
{
return dc;
}
ALWAYS_INLINE
static uint8_t*
getStatusData()
{
return status;
}
private:
static uint8_t status[CHANNELS*3/2];
static uint8_t gs[CHANNELS*3/2];
static uint8_t dc[CHANNELS*3/4];
};
}
#include "tlc594x_impl.hpp"
#endif // XPCC__TLC594X_HPP
<commit_msg>Add warning to TLC5940 where driven but disconnected channels can significantly heat up the driver due to the internal current control loop. In extreme cases this can lead to the destruction of the chip!<commit_after>// coding: utf-8
// ----------------------------------------------------------------------------
/* Copyright (c) 2012, Roboterclub Aachen e.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Roboterclub Aachen e.V. 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 ROBOTERCLUB AACHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. 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 XPCC__TLC594X_HPP
#define XPCC__TLC594X_HPP
#include <stdint.h>
#include <xpcc/architecture/driver/gpio.hpp>
#include <xpcc/architecture/driver/delay.hpp>
namespace xpcc
{
/**
* \brief TLC594* multi-channel, daisy-chainable, constant-current sink, 12bit PWM LED driver.
*
* This class does not use the DCPRG pin, as writing to the EEPROM requires
* 22V to be applied to Vprog, requiring additional external circuits.
* Use of any EEPROM functions is therefore not implemented here.
* Make sure that pin is connected to Vcc, otherwise Dot Correction does not work.
*
* This class also does not control the BLANK pin, as the setup of the timer
* to drive that pin is platform and configuration specific.
* Switching off all LEDs using one command is not implemented here.
*
* This driver can be used for the 16-channel TLC5940 and 24-channel TLC5947
* and probably similar TLC59s as well, simply by adjusting the number of
* CHANNELS.
* Therefore this class can also be used with daisy-chained TLC59s, e.g.
* to control two TLC5940s set CHANNELS to 2*16.
*
* #### WARNING ####
*
* Each channel in the TLC594x chip drives a transistor using a feedback loop
* to make it meet a particular current requirement.
* If a channel is disconnected, the feedback loop will fully drive the transistor.
* If most of the channels are disconnected (quite common in a testing
* environment if not in production), this will end up pulling quite a bit
* of power from the chip's 3.3 or 5v supply.
* This can heat up the chip and cause power supply issues.
*
*
* \tparam CHANNELS Number of channels must be multiples of 4, adjust for daisy-chained chips
* \tparam Spi Spi interface
* \tparam Xlat Level triggered latch pin
* \tparam Vprog Vprog pin, use xpcc::gpio::Unused if not connected
* \tparam Xerr Error pin, use xpcc::gpio::Unused if not connected
*
* \author Niklas Hauser
* \ingroup pwm
*/
template<
uint16_t CHANNELS,
typename Spi,
typename Xlat,
typename Vprog=xpcc::gpio::Unused,
typename Xerr=xpcc::gpio::Unused>
class TLC594X
{
public:
/**
* \param channels initialize channels buffer with value, disable with -1
* \param dots initialize dot correction buffer with value, disable with -1
* \param writeCH write channels value to chip
* \param writeDC write dots value to chip
*/
static void
initialize(uint16_t channels=0, uint8_t dots=63, bool writeCH=true, bool writeDC=true);
/// set the 12bit value of a channel
/// call transfer() to update the chip
static void
setChannel(uint16_t channel, uint16_t value);
/// \param value the 12bit value of all channels
/// \param update write data to chip
static void
setAllChannels(uint16_t value, bool update=false);
/// get the stored 12bit value of a channel
/// this does reflect the actual value in the chip
static uint16_t
getChannel(uint16_t channel);
/// set the 6bit dot correction value of a channel
/// call transfer() to update the chip
static void
setDotCorrection(uint16_t channel, uint8_t value);
/// \param value the 6bit dot correction value of all channels
/// \param update write data to chip
static void
setAllDotCorrection(uint8_t value, bool update=false);
/// get the stored 6bit dot correction value of a channel
/// this does reflect the actual value in the chip
static uint8_t
getDotCorrection(uint16_t channel);
/// transfer channel data to driver chip
static bool
writeChannels(bool flush=true);
/// transfer dot correction data to driver chip
static bool
writeDotCorrection();
/// writes data from the input shift register to either GS or DC register.
inline static void
latch();
/// \return true if LOD or TEF is detected
ALWAYS_INLINE
static bool
isError()
{
return !Xerr::read();
}
ALWAYS_INLINE
static uint8_t*
getGrayscaleData()
{
return gs;
}
ALWAYS_INLINE
static uint8_t*
getDotCorrectionData()
{
return dc;
}
ALWAYS_INLINE
static uint8_t*
getStatusData()
{
return status;
}
private:
static uint8_t status[CHANNELS*3/2];
static uint8_t gs[CHANNELS*3/2];
static uint8_t dc[CHANNELS*3/4];
};
}
#include "tlc594x_impl.hpp"
#endif // XPCC__TLC594X_HPP
<|endoftext|> |
<commit_before>/*
* avs2wav.cpp
* extract audio data as RIFF WAV format, from avs file
* Copyright (C) 2010 janus_wel<janus.wel.3@gmail.com>
* see LICENSE for redistributing, modifying, and so on.
* */
#include "../avsutil.hpp"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <stdexcept>
using namespace std;
using namespace avsutil;
// callback function for IAudio
void progress_cl(const unsigned __int64, const unsigned __int64);
int main(const int argc, const char* argv[]) {
if (argc < 2) {
cerr << "specify file name." << endl;
exit(1);
}
string avsfile(argv[1]);
string wavfile(argv[1]);
wavfile.append(".wav");
cout << "source: " << avsfile << endl;
cout << "destination: " << wavfile << endl;
try {
IAvs* avs = CreateAvsObj(avsfile.c_str());
IAudio* audio = avs->audio();
AudioInfo ai = audio->info();
if (!ai.exists) {
cerr << "no audio in the file: " << avsfile << endl;
exit(1);
}
cout << endl;
cout << "bit depth: " << ai.bit_depth << endl;
cout << "channels: " << ai.channels << endl;
cout << "sampling rate: " << ai.sampling_rate << endl;
cout << "samples: " << ai.samples << endl;
cout << endl;
audio->progress_callback(progress_cl);
ofstream fout(wavfile.c_str(), ios::binary | ios::trunc);
fout << audio;
cout << endl;
cout << "done." << endl;
delete audio;
delete avs;
}
catch (exception& ex) {
cerr << endl << ex.what() << endl;
exit(1);
}
return 0;
}
void progress_cl(const unsigned __int64 processed, const unsigned __int64 max) {
float percentage = (static_cast<float>(processed) / static_cast<float>(max)) * 100;
cout << "\rprocessing... "
<< setw(10) << right << processed << "/" << max
<< "(" << setprecision(2) << setw(6) << right << fixed << percentage << "%)";
}
<commit_msg>Show informations more pretty<commit_after>/*
* avs2wav.cpp
* extract audio data as RIFF WAV format, from avs file
* Copyright (C) 2010 janus_wel<janus.wel.3@gmail.com>
* see LICENSE for redistributing, modifying, and so on.
* */
#include "../avsutil.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
#include <stdexcept>
using namespace std;
using namespace avsutil;
// global object
// pout is abbr of progress out
// this stream is used in progress_cl()
ostream pout(cout.rdbuf());
// functions
// callback function for IAudio::write()
void progress_cl(const unsigned __int64, const unsigned __int64);
// output audio informations
ostream& operator <<(ostream&, const AudioInfo&);
int main(const int argc, const char* argv[]) {
if (argc < 2) {
cerr << "specify file name." << endl;
exit(1);
}
string avsfile(argv[1]);
string wavfile(argv[1]);
wavfile.append(".wav");
const unsigned int header_width = 14;
cout << left
<< setw(header_width) << "source:" << avsfile << endl
<< setw(header_width) << "destination:" << wavfile << endl;
try {
IAvs* avs = CreateAvsObj(avsfile.c_str());
IAudio* audio = avs->audio();
AudioInfo ai = audio->info();
if (!ai.exists) {
cerr << "no audio in the file: " << avsfile << endl;
exit(1);
}
cout << ai;
pout << right << fixed << setprecision(2);
audio->progress_callback(progress_cl);
ofstream fout(wavfile.c_str(), ios::binary | ios::trunc);
fout << audio;
cout << endl
<< "done." << endl;
delete audio;
delete avs;
}
catch (exception& ex) {
cerr << endl << ex.what() << endl;
exit(1);
}
return 0;
}
// definitions of functions
void progress_cl(const unsigned __int64 processed, const unsigned __int64 max) {
float percentage = (static_cast<float>(processed) / static_cast<float>(max)) * 100;
pout << "\rprocessing... "
<< setw(10) << processed << "/" << max << " samples"
<< " (" << setw(6) << percentage << "%)";
}
ostream& operator <<(ostream& out, const AudioInfo& ai) {
// constants
static const unsigned int header_width = 18;
// preparations
string channels;
switch (ai.channels) {
case 1: channels = "mono"; break;
case 2: channels = "stereo"; break;
case 6: channels = "5.1ch"; break;
default:
stringstream ss;
ss << dec << ai.channels;
channels.assign(ss.str()).append("ch");
break;
}
float sampling_rate = static_cast<float>(ai.sampling_rate) / 1000;
// instantiate new ostream object and set streambuf of "out" to it
// in order to save the formattings of "out"
ostream o(out.rdbuf());
o << left << setfill('.')
<< endl
<< setw(header_width) << "bit depth " << ' ' << ai.bit_depth << "bit" << endl
<< setw(header_width) << "channels " << ' ' << channels << endl
<< setw(header_width) << "sampling rate " << ' ' << sampling_rate << "kHz" << endl
<< setw(header_width) << "samples " << ' ' << ai.samples << endl
<< endl;
return out;
}
<|endoftext|> |
<commit_before>#pragma once
#include "../updater.hpp"
#include "../gameloophelper.hpp"
#include "engine.hpp"
template <class Base>
class DWrapper : public rs::DrawableObjT<DWrapper<Base>>,
public Base,
public spn::EnableFromThis<rs::HDObj>
{
private:
using base_dt = rs::DrawableObjT<DWrapper<Base>>;
rs::IdValue _tpId;
rs::HDGroup _hDGroup;
rs::HDGroup _getDGroup() const {
return _hDGroup ? _hDGroup : mgr_scene.getSceneBase().getDraw();
}
protected:
struct St_Default : base_dt::template StateT<St_Default> {
void onConnected(DWrapper& self, rs::HGroup hGroup) override {
auto hl = self.handleFromThis();
self._getDGroup()->get()->addObj(hl);
}
void onDisconnected(DWrapper& self, rs::HGroup hGroup) override {
auto hl = self.handleFromThis();
self._getDGroup()->get()->remObj(hl);
}
void onUpdate(DWrapper& self) override {
self.refreshDrawTag();
}
void onDraw(const DWrapper& self, rs::GLEffect& e) const override {
auto& fx = static_cast<Engine&>(e);
fx.setTechPassId(self._tpId);
self.Base::draw(fx);
}
};
public:
template <class... Ts>
DWrapper(rs::IdValue tpId, rs::HDGroup hDg, Ts&&... ts):
Base(std::forward<Ts>(ts)...),
_tpId(tpId),
_hDGroup(hDg)
{
refreshDrawTag();
base_dt::_dtag.idTechPass = tpId;
base_dt::template setStateNew<St_Default>();
}
void setPriority(rs::Priority p) {
base_dt::_dtag.priority = p;
}
void refreshDrawTag() {
Base::exportDrawTag(base_dt::_dtag);
}
};
<commit_msg>test/dwrapper: 描画グループは弱参照ハンドルで持つように変更<commit_after>#pragma once
#include "../updater.hpp"
#include "../gameloophelper.hpp"
#include "engine.hpp"
template <class Base>
class DWrapper : public rs::DrawableObjT<DWrapper<Base>>,
public Base,
public spn::EnableFromThis<rs::HDObj>
{
private:
using base_dt = rs::DrawableObjT<DWrapper<Base>>;
rs::IdValue _tpId;
rs::WDGroup _wDGroup;
rs::HDGroup _getDGroup() const {
if(auto dg = _wDGroup.lock())
return dg;
return mgr_scene.getSceneBase().getDraw();
}
protected:
struct St_Default : base_dt::template StateT<St_Default> {
void onConnected(DWrapper& self, rs::HGroup hGroup) override {
auto hl = self.handleFromThis();
self._getDGroup()->get()->addObj(hl);
}
void onDisconnected(DWrapper& self, rs::HGroup hGroup) override {
auto hl = self.handleFromThis();
self._getDGroup()->get()->remObj(hl);
}
void onUpdate(DWrapper& self) override {
self.refreshDrawTag();
}
void onDraw(const DWrapper& self, rs::GLEffect& e) const override {
auto& fx = static_cast<Engine&>(e);
fx.setTechPassId(self._tpId);
self.Base::draw(fx);
}
};
public:
template <class... Ts>
DWrapper(rs::IdValue tpId, rs::HDGroup hDg, Ts&&... ts):
Base(std::forward<Ts>(ts)...),
_tpId(tpId)
{
if(hDg)
_wDGroup = hDg.weak();
refreshDrawTag();
base_dt::_dtag.idTechPass = tpId;
base_dt::template setStateNew<St_Default>();
}
void setPriority(rs::Priority p) {
base_dt::_dtag.priority = p;
}
void refreshDrawTag() {
Base::exportDrawTag(base_dt::_dtag);
}
};
<|endoftext|> |
<commit_before>#include <silicium/error_or.hpp>
#include <boost/test/unit_test.hpp>
#include <system_error>
BOOST_AUTO_TEST_CASE(error_or_from_value)
{
Si::error_or<int> value(2);
BOOST_CHECK(!value.is_error());
BOOST_REQUIRE(value.get_ptr());
BOOST_CHECK_EQUAL(2, *value.get_ptr());
BOOST_CHECK_EQUAL(2, value.get());
}
BOOST_AUTO_TEST_CASE(error_or_from_value_const)
{
Si::error_or<int> const value(2);
BOOST_CHECK(!value.is_error());
BOOST_CHECK_EQUAL(2, value.get());
BOOST_REQUIRE(value.get_ptr());
BOOST_CHECK_EQUAL(2, *value.get_ptr());
}
BOOST_AUTO_TEST_CASE(error_or_movable_only)
{
Si::error_or<std::unique_ptr<int>> value(Si::make_unique<int>(2));
BOOST_REQUIRE(value.get_ptr());
BOOST_REQUIRE(*value.get_ptr());
BOOST_CHECK_EQUAL(2, **value.get_ptr());
std::unique_ptr<int> v = std::move(value.get());
BOOST_CHECK(!value.get());
BOOST_CHECK(!value.is_error());
BOOST_CHECK_EQUAL(2, *v);
}
struct expected_exception : std::exception
{
};
struct throws_on_copy_construction
{
bool active = true;
throws_on_copy_construction()
{
}
throws_on_copy_construction(throws_on_copy_construction const &other)
: active(other.active)
{
if (active)
{
throw expected_exception();
}
}
throws_on_copy_construction &operator = (throws_on_copy_construction const &) = delete;
};
BOOST_AUTO_TEST_CASE(error_or_copy_construction_from_value_throws)
{
BOOST_CHECK_EXCEPTION(
[]()
{
throws_on_copy_construction const original;
Si::error_or<throws_on_copy_construction> e((original));
}(),
expected_exception,
[](expected_exception const &)
{
return true;
});
}
BOOST_AUTO_TEST_CASE(error_or_copy_construction_from_error_or_throws)
{
throws_on_copy_construction original;
original.active = false;
Si::error_or<throws_on_copy_construction> e(original);
e.get_ptr()->active = true;
BOOST_CHECK_EXCEPTION(
[&e]()
{
Si::error_or<throws_on_copy_construction> f((e));
}(),
expected_exception,
[](expected_exception const &)
{
return true;
});
}
struct throws_on_assignment
{
throws_on_assignment()
{
}
throws_on_assignment(throws_on_assignment const &)
{
}
throws_on_assignment &operator = (throws_on_assignment const &)
{
throw expected_exception();
}
};
BOOST_AUTO_TEST_CASE(error_or_copy_assignment_from_value_throws)
{
Si::error_or<throws_on_assignment> e((throws_on_assignment()));
BOOST_CHECK_EXCEPTION(
[&e]()
{
throws_on_assignment const original;
e = original;
}(),
expected_exception,
[](expected_exception const &)
{
return true;
});
}
BOOST_AUTO_TEST_CASE(error_or_throwing_get)
{
boost::system::error_code const ec(123, boost::system::native_ecat);
Si::error_or<int> error(ec);
BOOST_CHECK(error.is_error());
BOOST_CHECK_EXCEPTION(error.get(), boost::system::system_error, [ec](boost::system::system_error const &ex)
{
return ex.code() == ec;
});
}
BOOST_AUTO_TEST_CASE(error_or_std)
{
std::error_code const ec(123, std::system_category());
Si::error_or<int, std::error_code> error(ec);
BOOST_CHECK(error.is_error());
BOOST_CHECK_EXCEPTION(error.get(), std::system_error, [ec](std::system_error const &ex)
{
return ex.code() == ec;
});
}
struct base
{
virtual ~base()
{
}
};
struct derived : base
{
};
BOOST_AUTO_TEST_CASE(error_or_construct_from_convertible)
{
Si::error_or<long> e(2u);
BOOST_CHECK_EQUAL(2L, e.get());
Si::error_or<std::unique_ptr<base>> f(Si::make_unique<derived>());
BOOST_CHECK(f.get() != nullptr);
}
BOOST_AUTO_TEST_CASE(error_or_map_value)
{
BOOST_CHECK_EQUAL(Si::error_or<long>(3L), Si::map(Si::error_or<long>(2L), [](long value)
{
return value + 1;
}));
}
BOOST_AUTO_TEST_CASE(error_or_map_error)
{
boost::system::error_code const test_error(2, boost::system::native_ecat);
BOOST_CHECK_EQUAL(
Si::error_or<long>(test_error),
Si::map(Si::error_or<long>(test_error), [](long)
{
BOOST_FAIL("no value expected");
return 0;
}));
}
template <class T>
struct move_only_comparable
{
BOOST_STATIC_ASSERT(std::is_nothrow_default_constructible<T>::value);
BOOST_STATIC_ASSERT(std::is_nothrow_move_constructible<T>::value);
BOOST_STATIC_ASSERT(std::is_nothrow_move_assignable<T>::value);
T value;
move_only_comparable() BOOST_NOEXCEPT
{
}
move_only_comparable(T value)
: value(std::move(value))
{
}
move_only_comparable(move_only_comparable &&other) BOOST_NOEXCEPT
: value(std::move(other.value))
{
}
move_only_comparable(move_only_comparable const &other)
: value(other.value)
{
}
move_only_comparable &operator = (move_only_comparable &&other) BOOST_NOEXCEPT
{
value = std::move(other.value);
return *this;
}
move_only_comparable &operator = (move_only_comparable const &other)
{
value = other.value;
return *this;
}
};
template <class T>
bool operator == (move_only_comparable<T> const &left, move_only_comparable<T> const &right)
{
return left.value == right.value;
}
template <class T>
bool operator != (move_only_comparable<T> const &left, move_only_comparable<T> const &right)
{
return left.value != right.value;
}
template <class T>
std::ostream &operator << (std::ostream &out, move_only_comparable<T> const &value)
{
return out << value.value;
}
BOOST_AUTO_TEST_CASE(error_or_equal)
{
{
Si::error_or<move_only_comparable<int>> a(2);
Si::error_or<move_only_comparable<int>> b(2);
BOOST_CHECK_EQUAL(a, a);
BOOST_CHECK_EQUAL(a, b);
BOOST_CHECK_EQUAL(b, a);
BOOST_CHECK_EQUAL(b, b);
BOOST_CHECK_EQUAL(a, 2);
BOOST_CHECK_EQUAL(2, a);
}
{
boost::system::error_code const test_error(2, boost::system::generic_category());
Si::error_or<move_only_comparable<int>> c = test_error;
Si::error_or<move_only_comparable<int>> d = test_error;
BOOST_CHECK_EQUAL(c, c);
BOOST_CHECK_EQUAL(c, d);
BOOST_CHECK_EQUAL(d, c);
BOOST_CHECK_EQUAL(d, d);
BOOST_CHECK_EQUAL(c, test_error);
BOOST_CHECK_EQUAL(test_error, c);
}
}
BOOST_AUTO_TEST_CASE(error_or_not_equal)
{
Si::error_or<move_only_comparable<int>> a(2);
Si::error_or<move_only_comparable<int>> b(3);
Si::error_or<move_only_comparable<int>> c = boost::system::error_code(2, boost::system::generic_category());
Si::error_or<move_only_comparable<int>> d = boost::system::error_code(3, boost::system::generic_category());
BOOST_CHECK_NE(a, b);
BOOST_CHECK_NE(a, c);
BOOST_CHECK_NE(a, d);
BOOST_CHECK_NE(b, a);
BOOST_CHECK_NE(b, c);
BOOST_CHECK_NE(b, d);
BOOST_CHECK_NE(c, a);
BOOST_CHECK_NE(c, b);
BOOST_CHECK_NE(c, d);
BOOST_CHECK_NE(d, a);
BOOST_CHECK_NE(d, b);
BOOST_CHECK_NE(d, c);
BOOST_CHECK_NE(a, 3);
BOOST_CHECK_NE(a, (boost::system::error_code(2 BOOST_PP_COMMA() boost::system::generic_category())));
}
<commit_msg>more error_or tests<commit_after>#include <silicium/error_or.hpp>
#include <silicium/noexcept_string.hpp>
#include <boost/test/unit_test.hpp>
#include <system_error>
BOOST_AUTO_TEST_CASE(error_or_from_value)
{
Si::error_or<int> value(2);
BOOST_CHECK(!value.is_error());
BOOST_REQUIRE(value.get_ptr());
BOOST_CHECK_EQUAL(2, *value.get_ptr());
BOOST_CHECK_EQUAL(2, value.get());
}
BOOST_AUTO_TEST_CASE(error_or_from_value_const)
{
Si::error_or<int> const value(2);
BOOST_CHECK(!value.is_error());
BOOST_CHECK_EQUAL(2, value.get());
BOOST_REQUIRE(value.get_ptr());
BOOST_CHECK_EQUAL(2, *value.get_ptr());
}
BOOST_AUTO_TEST_CASE(error_or_convert_from_value)
{
Si::error_or<Si::noexcept_string> const value("C string literal");
BOOST_CHECK(!value.is_error());
BOOST_CHECK_EQUAL("C string literal", value.get());
}
BOOST_AUTO_TEST_CASE(error_or_movable_only)
{
Si::error_or<std::unique_ptr<int>> value(Si::make_unique<int>(2));
BOOST_REQUIRE(value.get_ptr());
BOOST_REQUIRE(*value.get_ptr());
BOOST_CHECK_EQUAL(2, **value.get_ptr());
std::unique_ptr<int> v = std::move(value.get());
BOOST_CHECK(!value.get());
BOOST_CHECK(!value.is_error());
BOOST_CHECK_EQUAL(2, *v);
}
struct expected_exception : std::exception
{
};
struct throws_on_copy_construction
{
bool active = true;
throws_on_copy_construction()
{
}
throws_on_copy_construction(throws_on_copy_construction const &other)
: active(other.active)
{
if (active)
{
throw expected_exception();
}
}
throws_on_copy_construction &operator = (throws_on_copy_construction const &) = delete;
};
BOOST_AUTO_TEST_CASE(error_or_copy_construction_from_value_throws)
{
BOOST_CHECK_EXCEPTION(
[]()
{
throws_on_copy_construction const original;
Si::error_or<throws_on_copy_construction> e((original));
}(),
expected_exception,
[](expected_exception const &)
{
return true;
});
}
BOOST_AUTO_TEST_CASE(error_or_copy_construction_from_error_or_throws)
{
throws_on_copy_construction original;
original.active = false;
Si::error_or<throws_on_copy_construction> e(original);
e.get_ptr()->active = true;
BOOST_CHECK_EXCEPTION(
[&e]()
{
Si::error_or<throws_on_copy_construction> f((e));
}(),
expected_exception,
[](expected_exception const &)
{
return true;
});
}
struct throws_on_assignment
{
throws_on_assignment()
{
}
throws_on_assignment(throws_on_assignment const &)
{
}
throws_on_assignment &operator = (throws_on_assignment const &)
{
throw expected_exception();
}
};
BOOST_AUTO_TEST_CASE(error_or_copy_assignment_from_value_to_success_throws)
{
Si::error_or<throws_on_assignment> to((throws_on_assignment()));
BOOST_CHECK_EXCEPTION(
[&to]()
{
throws_on_assignment const original;
to = original;
}(),
expected_exception,
[](expected_exception const &)
{
return true;
});
}
BOOST_AUTO_TEST_CASE(error_or_copy_assignment_from_value_to_error)
{
Si::error_or<throws_on_assignment> e(boost::system::error_code(23, boost::system::system_category()));
throws_on_assignment const original;
e = original; //should not throw because of the value is copy-constructed
}
BOOST_AUTO_TEST_CASE(error_or_throwing_get)
{
boost::system::error_code const ec(123, boost::system::native_ecat);
Si::error_or<int> error(ec);
BOOST_CHECK(error.is_error());
BOOST_CHECK_EXCEPTION(error.get(), boost::system::system_error, [ec](boost::system::system_error const &ex)
{
return ex.code() == ec;
});
}
BOOST_AUTO_TEST_CASE(error_or_std)
{
std::error_code const ec(123, std::system_category());
Si::error_or<int, std::error_code> error(ec);
BOOST_CHECK(error.is_error());
BOOST_CHECK_EXCEPTION(error.get(), std::system_error, [ec](std::system_error const &ex)
{
return ex.code() == ec;
});
}
struct base
{
virtual ~base()
{
}
};
struct derived : base
{
};
BOOST_AUTO_TEST_CASE(error_or_construct_from_convertible)
{
Si::error_or<long> e(2u);
BOOST_CHECK_EQUAL(2L, e.get());
Si::error_or<std::unique_ptr<base>> f(Si::make_unique<derived>());
BOOST_CHECK(f.get() != nullptr);
}
BOOST_AUTO_TEST_CASE(error_or_map_value)
{
BOOST_CHECK_EQUAL(Si::error_or<long>(3L), Si::map(Si::error_or<long>(2L), [](long value)
{
return value + 1;
}));
}
BOOST_AUTO_TEST_CASE(error_or_map_error)
{
boost::system::error_code const test_error(2, boost::system::native_ecat);
BOOST_CHECK_EQUAL(
Si::error_or<long>(test_error),
Si::map(Si::error_or<long>(test_error), [](long)
{
BOOST_FAIL("no value expected");
return 0;
}));
}
template <class T>
struct move_only_comparable
{
BOOST_STATIC_ASSERT(std::is_nothrow_default_constructible<T>::value);
BOOST_STATIC_ASSERT(std::is_nothrow_move_constructible<T>::value);
BOOST_STATIC_ASSERT(std::is_nothrow_move_assignable<T>::value);
T value;
move_only_comparable() BOOST_NOEXCEPT
{
}
move_only_comparable(T value)
: value(std::move(value))
{
}
move_only_comparable(move_only_comparable &&other) BOOST_NOEXCEPT
: value(std::move(other.value))
{
}
move_only_comparable(move_only_comparable const &other)
: value(other.value)
{
}
move_only_comparable &operator = (move_only_comparable &&other) BOOST_NOEXCEPT
{
value = std::move(other.value);
return *this;
}
move_only_comparable &operator = (move_only_comparable const &other)
{
value = other.value;
return *this;
}
};
template <class T>
bool operator == (move_only_comparable<T> const &left, move_only_comparable<T> const &right)
{
return left.value == right.value;
}
template <class T>
bool operator != (move_only_comparable<T> const &left, move_only_comparable<T> const &right)
{
return left.value != right.value;
}
template <class T>
std::ostream &operator << (std::ostream &out, move_only_comparable<T> const &value)
{
return out << value.value;
}
BOOST_AUTO_TEST_CASE(error_or_equal)
{
{
Si::error_or<move_only_comparable<int>> a(2);
Si::error_or<move_only_comparable<int>> b(2);
BOOST_CHECK_EQUAL(a, a);
BOOST_CHECK_EQUAL(a, b);
BOOST_CHECK_EQUAL(b, a);
BOOST_CHECK_EQUAL(b, b);
BOOST_CHECK_EQUAL(a, 2);
BOOST_CHECK_EQUAL(2, a);
}
{
boost::system::error_code const test_error(2, boost::system::generic_category());
Si::error_or<move_only_comparable<int>> c = test_error;
Si::error_or<move_only_comparable<int>> d = test_error;
BOOST_CHECK_EQUAL(c, c);
BOOST_CHECK_EQUAL(c, d);
BOOST_CHECK_EQUAL(d, c);
BOOST_CHECK_EQUAL(d, d);
BOOST_CHECK_EQUAL(c, test_error);
BOOST_CHECK_EQUAL(test_error, c);
}
}
BOOST_AUTO_TEST_CASE(error_or_not_equal)
{
Si::error_or<move_only_comparable<int>> a(2);
Si::error_or<move_only_comparable<int>> b(3);
Si::error_or<move_only_comparable<int>> c = boost::system::error_code(2, boost::system::generic_category());
Si::error_or<move_only_comparable<int>> d = boost::system::error_code(3, boost::system::generic_category());
BOOST_CHECK_NE(a, b);
BOOST_CHECK_NE(a, c);
BOOST_CHECK_NE(a, d);
BOOST_CHECK_NE(b, a);
BOOST_CHECK_NE(b, c);
BOOST_CHECK_NE(b, d);
BOOST_CHECK_NE(c, a);
BOOST_CHECK_NE(c, b);
BOOST_CHECK_NE(c, d);
BOOST_CHECK_NE(d, a);
BOOST_CHECK_NE(d, b);
BOOST_CHECK_NE(d, c);
BOOST_CHECK_NE(a, 3);
BOOST_CHECK_NE(a, (boost::system::error_code(2 BOOST_PP_COMMA() boost::system::generic_category())));
}
BOOST_AUTO_TEST_CASE(error_or_move_only_in_container)
{
std::vector<Si::error_or<std::unique_ptr<int>>> v;
v.emplace_back(Si::make_unique<int>(3));
v.emplace_back(boost::system::error_code(23, boost::system::system_category()));
auto w = std::move(v);
BOOST_CHECK_EQUAL(3, **w[0].get_ptr());
BOOST_CHECK(boost::system::error_code(23, boost::system::system_category()) == w[1]);
}
BOOST_AUTO_TEST_CASE(error_or_copyable_in_container)
{
std::vector<Si::error_or<Si::noexcept_string>> v;
v.emplace_back("Hello");
v.emplace_back(boost::system::error_code(23, boost::system::system_category()));
auto w = v;
BOOST_CHECK(w == v);
BOOST_CHECK_EQUAL("Hello", w[0].get());
BOOST_CHECK(boost::system::error_code(23, boost::system::system_category()) == w[1]);
}
<|endoftext|> |
<commit_before><commit_msg>this is a no-op, remove if<commit_after><|endoftext|> |
<commit_before>#include <utils/cmd_args.hpp>
#include <memory_pool.hpp>
#include <complex>
using double_complex = std::complex<double>;
using namespace sddk;
void test1()
{
memory_pool mp;
}
void test2()
{
memory_pool mp;
mp.allocate<double_complex, memory_t::host>(1024);
mp.reset<memory_t::host>();
}
void test3()
{
memory_pool mp;
mp.allocate<double_complex, memory_t::host>(1024);
mp.allocate<double_complex, memory_t::host>(2024);
mp.allocate<double_complex, memory_t::host>(3024);
mp.reset<memory_t::host>();
}
void test4()
{
memory_pool mp;
mp.allocate<double_complex, memory_t::host>(1024);
mp.reset<memory_t::host>();
mp.allocate<double_complex, memory_t::host>(1024);
mp.allocate<double_complex, memory_t::host>(1024);
mp.reset<memory_t::host>();
mp.allocate<double_complex, memory_t::host>(1024);
mp.allocate<double_complex, memory_t::host>(1024);
mp.allocate<double_complex, memory_t::host>(1024);
mp.reset<memory_t::host>();
}
void test5()
{
memory_pool mp;
for (int k = 0; k < 2; k++) {
std::vector<double*> vp;
for (size_t i = 1; i < 20; i++) {
size_t sz = 1 << i;
double* ptr = mp.allocate<double, memory_t::host>(sz);
ptr[0] = 0;
ptr[sz - 1] = 0;
vp.push_back(ptr);
}
for (auto& e: vp) {
mp.free<memory_t::host>(e);
}
}
}
int run_test()
{
test1();
test2();
test3();
test4();
test5();
return 0;
}
int main(int argn, char** argv)
{
cmd_args args;
args.parse_args(argn, argv);
if (args.exist("help")) {
printf("Usage: %s [options]\n", argv[0]);
args.print_help();
return 0;
}
printf("%-30s", "testing memory pool: ");
int result = run_test();
if (result) {
printf("\x1b[31m" "Failed" "\x1b[0m" "\n");
} else {
printf("\x1b[32m" "OK" "\x1b[0m" "\n");
}
return 0;
}
<commit_msg>update mem_pool test<commit_after>#include <utils/cmd_args.hpp>
#include <memory_pool.hpp>
#include <complex>
#include <sys/time.h>
using double_complex = std::complex<double>;
using namespace sddk;
void test1()
{
memory_pool mp(memory_t::host);
}
void test2()
{
memory_pool mp(memory_t::host);
auto ptr = mp.allocate<double_complex>(1024);
mp.free(ptr);
}
void test2a()
{
memory_pool mp(memory_t::host);
auto ptr = mp.allocate<double_complex>(1024);
mp.free(ptr);
ptr = mp.allocate<double_complex>(512);
mp.free(ptr);
}
void test3()
{
memory_pool mp(memory_t::host);
auto p1 = mp.allocate<double_complex>(1024);
auto p2 = mp.allocate<double_complex>(2024);
auto p3 = mp.allocate<double_complex>(3024);
mp.free(p1);
mp.free(p2);
mp.free(p3);
}
void test3a()
{
memory_pool mp(memory_t::host);
mp.allocate<double_complex>(1024);
mp.allocate<double_complex>(2024);
mp.allocate<double_complex>(3024);
mp.reset();
}
void test4()
{
memory_pool mp(memory_t::host);
mp.allocate<double_complex>(1024);
mp.reset();
mp.allocate<double_complex>(1024);
mp.allocate<double_complex>(1024);
mp.reset();
mp.allocate<double_complex>(1024);
mp.allocate<double_complex>(1024);
mp.allocate<double_complex>(1024);
mp.reset();
}
void test5()
{
memory_pool mp(memory_t::host);
for (int k = 0; k < 2; k++) {
std::vector<double*> vp;
for (size_t i = 1; i < 20; i++) {
size_t sz = 1 << i;
double* ptr = mp.allocate<double>(sz);
ptr[0] = 0;
ptr[sz - 1] = 0;
vp.push_back(ptr);
}
for (auto& e: vp) {
mp.free(e);
}
}
}
/// Wall-clock time in seconds.
inline double wtime()
{
timeval t;
gettimeofday(&t, NULL);
return double(t.tv_sec) + double(t.tv_usec) / 1e6;
}
double test_alloc(size_t n)
{
double t0 = wtime();
/* time to allocate + fill */
char* ptr = (char*)std::malloc(n);
std::fill(ptr, ptr + n, 0);
double t1 = wtime();
/* time fo fill */
std::fill(ptr, ptr + n, 0);
double t2 = wtime();
/* harmless: add zero to t0 to prevent full optimization of the code with GCC */
t0 += ptr[0];
std::free(ptr);
double t3 = wtime();
//return (t1 - t0) - (t2 - t1);
return (t3 - t0) - 2 * (t2 - t1);
}
double test_alloc(size_t n, memory_pool& mp)
{
double t0 = wtime();
/* time to allocate + fill */
char* ptr = mp.allocate<char>(n);
std::fill(ptr, ptr + n, 0);
double t1 = wtime();
/* time fo fill */
std::fill(ptr, ptr + n, 0);
double t2 = wtime();
/* harmless: add zero to t0 to prevent full optimization of the code with GCC */
t0 += ptr[0];
mp.free(ptr);
double t3 = wtime();
//return (t1 - t0) - (t2 - t1);
return (t3 - t0) - 2 * (t2 - t1);
}
void test6()
{
double t0{0};
for (int k = 0; k < 8; k++) {
for (int i = 10; i < 30; i++) {
size_t sz = size_t(1) << i;
t0 += test_alloc(sz);
}
}
memory_pool mp(memory_t::host);
double t1{0};
for (int k = 0; k < 8; k++) {
for (int i = 10; i < 30; i++) {
size_t sz = size_t(1) << i;
t1 += test_alloc(sz, mp);
}
}
std::cout << "std::malloc time: " << t0 << ", sddk::memory_pool time: " << t1 << "\n";
}
void test6a()
{
double t0{0};
for (int k = 0; k < 100; k++) {
for (int i = 2; i < 1024; i++) {
size_t sz = i;
t0 += test_alloc(sz);
}
}
memory_pool mp(memory_t::host);
double t1{0};
for (int k = 0; k < 100; k++) {
for (int i = 2; i < 1024; i++) {
size_t sz = i;
t1 += test_alloc(sz, mp);
}
}
std::cout << "std::malloc time: " << t0 << ", sddk::memory_pool time: " << t1 << "\n";
mp.print();
}
int run_test()
{
test1();
test2();
test2a();
test3();
test3a();
test4();
test5();
//test6();
//test6a();
return 0;
}
int main(int argn, char** argv)
{
cmd_args args;
args.parse_args(argn, argv);
if (args.exist("help")) {
printf("Usage: %s [options]\n", argv[0]);
args.print_help();
return 0;
}
printf("%-30s", "testing memory pool: ");
int result = run_test();
if (result) {
printf("\x1b[31m" "Failed" "\x1b[0m" "\n");
} else {
printf("\x1b[32m" "OK" "\x1b[0m" "\n");
}
return 0;
}
<|endoftext|> |
<commit_before>//
// BoardPage.xaml.cpp
// Implementation of the MainPage class.
//
#include "pch.h"
#include "BoardPage.h"
using namespace ygc;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Devices::Sensors;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::UI::Xaml::Media::Imaging;
BoardPage::BoardPage(Page^ rootPage)
{
LayoutRoot = ref new Canvas();
rootPage->Content = LayoutRoot;
stonesOnCanvas = ref new Vector<Image^>();
AppSpaceWidth = 0.0;
AppSpaceHeight = 0.0;
}
void BoardPage::InitUI()
{
AppSpaceWidth = Window::Current->Bounds.Width;
AppSpaceHeight = Window::Current->Bounds.Height - 32 / Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->RawPixelsPerViewPixel;
PanelWidth = 60.0;
SideMargin = AppSpaceWidth / (currentMatch->board->sBoardWidth + 1); // TODO: Can we have it bound to height in a nicer fashion?
InitBoardGrid();
InitScrollViewer();
DrawBoardGrid();
}
void BoardPage::InitBoardGrid()
{
//init board
boardGrid = ref new Canvas();
boardGrid->Background = ref new SolidColorBrush(Windows::UI::Colors::DarkGreen);
boardGrid->RenderTransform = ref new RotateTransform();
boardGrid->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Center;
boardGrid->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Center;
boardGrid->Margin = Thickness(0);
boardGridBorder = ref new Border();
boardGridBorder->Padding = 2 * SideMargin;
boardGridBorder->Child = boardGrid;
}
void BoardPage::InitScrollViewer()
{
//init view
ScrollBoardView = ref new ScrollViewer();
ScrollBoardView->ZoomMode = Windows::UI::Xaml::Controls::ZoomMode::Enabled;
ScrollBoardView->HorizontalScrollBarVisibility = Windows::UI::Xaml::Controls::ScrollBarVisibility::Hidden;
ScrollBoardView->VerticalScrollBarVisibility = Windows::UI::Xaml::Controls::ScrollBarVisibility::Hidden;
ScrollBoardView->HorizontalContentAlignment = Windows::UI::Xaml::HorizontalAlignment::Center;
ScrollBoardView->VerticalContentAlignment = Windows::UI::Xaml::VerticalAlignment::Center;
ScrollBoardView->MinZoomFactor = 0.5;
ScrollBoardView->MaxZoomFactor = 3.0;
ScrollBoardView->Background = ref new SolidColorBrush(Windows::UI::Colors::DarkOrange);
ScrollBoardView->Content = boardGridBorder;
ScrollBoardView->Width = Window::Current->Bounds.Width;
ScrollBoardView->Height = Window::Current->Bounds.Height;
LayoutRoot->SetZIndex(ScrollBoardView, 1);
ScrollBoardView->RenderTransform = ref new RotateTransform();
((RotateTransform^)ScrollBoardView->RenderTransform)->CenterX = ScrollBoardView->Width / 2.0f;
((RotateTransform^)ScrollBoardView->RenderTransform)->CenterY = ScrollBoardView->Height / 2.0f;
ScrollBoardView->SizeChanged += ref new SizeChangedEventHandler(this, &BoardPage::UpdateScrollBoardViewScroll);
ScrollBoardView->Loaded += ref new RoutedEventHandler([this](Object ^ s, RoutedEventArgs ^ re){
double sw = ScrollBoardView->ScrollableWidth;
double sh = ScrollBoardView->ScrollableHeight;
ScrollBoardView->ChangeView(sw / 2.0, sh / 2.0, 1.0f);
});
LayoutRoot->Children->Append(ScrollBoardView);
}
void BoardPage::UpdateScrollBoardViewScroll(Object^ s, SizeChangedEventArgs^ e)
{
double ov = ScrollBoardView->HorizontalOffset;
double oh = ScrollBoardView->ScrollableHeight - ScrollBoardView->VerticalOffset;
ScrollBoardView->ChangeView(ov, oh, ScrollBoardView->ZoomFactor);
}
void BoardPage::DrawBoardGrid()
{
uint16_t bgWidth = currentMatch->board->sBoardWidth;
uint16_t bgHeight = currentMatch->board->sBoardHeight;
for (auto i = 0; i < bgWidth; ++i) {
Shapes::Line^ vertLine = ref new Shapes::Line();
vertLine->Stroke = ref new SolidColorBrush(defaultAppSettings::defaultGridColor);
vertLine->X1 = (1 + i) * SideMargin;
vertLine->X2 = vertLine->X1;
vertLine->Y1 = SideMargin;
vertLine->Y2 = SideMargin * bgHeight;
boardGrid->Children->Append(vertLine);
}
for (auto j = 0; j < bgHeight; ++j) {
Shapes::Line^ horiLine = ref new Shapes::Line();
horiLine->Stroke = ref new SolidColorBrush(defaultAppSettings::defaultGridColor);
horiLine->X1 = SideMargin;
horiLine->X2 = SideMargin * bgWidth;
horiLine->Y1 = (1 + j) * SideMargin;
horiLine->Y2 = horiLine->Y1;
boardGrid->Children->Append(horiLine);
}
}
void BoardPage::AddStone(ygcStoneColor^ turn, uint16_t x, uint16_t y)
{
Image^ stone = ref new Image();
stone->Name = "Stone" + x.ToString() + "x" + y.ToString();
stone->Source = ref new BitmapImage(ref new Uri(defaultAppSettings::defaultStones[turn]));
stone->Width = 0.9 * SideMargin;
stone->Height = stone->Width;
boardGrid->Children->Append(stone);
boardGrid->SetZIndex(stone, 2);
boardGrid->SetTop(stone, SideMargin * (y + 1) - stone->Width / 2.0);
boardGrid->SetLeft(stone, SideMargin * (x + 1) - stone->Width / 2.0);
stonesOnCanvas->Append(stone);
*currentMatch->board->GetAt(x, y)->takenBy = *turn;
}
bool BoardPage::RemoveStone(uint16_t x, uint16_t y)
{
uint32_t stoneIndex;
for (auto stone : stonesOnCanvas) {
if (stone->Name == "Stone" + x.ToString() + "x" + y.ToString()) {
boardGrid->Children->IndexOf(stone, &stoneIndex);
boardGrid->Children->RemoveAt(stoneIndex);
stonesOnCanvas->IndexOf(stone, &stoneIndex);
stonesOnCanvas->RemoveAt(stoneIndex);
*currentMatch->board->GetAt(x, y)->takenBy = 0;
return true;
}
}
return false;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void BoardPage::BoardOnNavigatedTo(NavigationEventArgs^ e)
{
(void) e; // Unused parameter
/*switch (Settings.OrientationLock)
{
case OrientationLock.Rotate:
this->SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
AppSpaceWidth = Window::Current->Bounds.Width;
AppSpaceHeight = Window::Current->Bounds.Height - 32;
break;
case OrientationLock.HorizontalLock:
this.SupportedOrientations = SupportedPageOrientation.Landscape;
break;
case OrientationLock.VerticalLock:
this.SupportedOrientations = SupportedPageOrientation.Portrait;
AppSpaceWidth = Window::Current->Bounds.Width;
AppSpaceHeight = Window::Current->Bounds.Height - 32;
break;
}*/
AppSpaceWidth = Window::Current->Bounds.Width;
AppSpaceHeight = Window::Current->Bounds.Height - 32.0 / Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->RawPixelsPerViewPixel;
boardGrid->Width = AppSpaceWidth;
boardGrid->Height = AppSpaceWidth * (currentMatch->board->sBoardHeight + 1) / double(currentMatch->board->sBoardWidth + 1);
((RotateTransform^)boardGrid->RenderTransform)->CenterX = boardGrid->Width / 2.0f;
((RotateTransform^)boardGrid->RenderTransform)->CenterY = boardGrid->Height / 2.0f;
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows::Phone::UI::Input::HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
void BoardPage::BoardOnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
{
}
void BoardPage::BoardOrientHandler(Object^ sender, SizeChangedEventArgs^ sce)
{
boardGrid->Background = ref new SolidColorBrush(Windows::UI::Colors::DimGray);
if (Windows::UI::ViewManagement::ApplicationView::GetForCurrentView()->Orientation == Windows::UI::ViewManagement::ApplicationViewOrientation::Portrait) {
AppSpaceWidth = Window::Current->Bounds.Width;
AppSpaceHeight = Window::Current->Bounds.Height - 32 / Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->RawPixelsPerViewPixel;
((RotateTransform^)boardGrid->RenderTransform)->Angle = 0.0f;
} else {
AppSpaceWidth = Window::Current->Bounds.Width - 72 / Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->RawPixelsPerViewPixel;
AppSpaceHeight = Window::Current->Bounds.Height;
((RotateTransform^)boardGrid->RenderTransform)->Angle = 270.0f;
}
SideMargin = AppSpaceWidth / (currentMatch->board->sBoardWidth + 1); // TODO: Can we bound it to height in a nice fashion?
ScrollBoardView->Height = AppSpaceHeight;
ScrollBoardView->Width = AppSpaceWidth;
}<commit_msg>BoardOrientHandler : mental hiccup<commit_after>//
// BoardPage.xaml.cpp
// Implementation of the MainPage class.
//
#include "pch.h"
#include "BoardPage.h"
using namespace ygc;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Devices::Sensors;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::UI::Xaml::Media::Imaging;
BoardPage::BoardPage(Page^ rootPage)
{
LayoutRoot = ref new Canvas();
rootPage->Content = LayoutRoot;
stonesOnCanvas = ref new Vector<Image^>();
AppSpaceWidth = 0.0;
AppSpaceHeight = 0.0;
}
void BoardPage::InitUI()
{
AppSpaceWidth = Window::Current->Bounds.Width;
AppSpaceHeight = Window::Current->Bounds.Height - 32 / Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->RawPixelsPerViewPixel;
PanelWidth = 60.0;
SideMargin = AppSpaceWidth / (currentMatch->board->sBoardWidth + 1); // TODO: Can we have it bound to height in a nicer fashion?
InitBoardGrid();
InitScrollViewer();
DrawBoardGrid();
}
void BoardPage::InitBoardGrid()
{
//init board
boardGrid = ref new Canvas();
boardGrid->Background = ref new SolidColorBrush(Windows::UI::Colors::DarkGreen);
boardGrid->RenderTransform = ref new RotateTransform();
boardGrid->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Center;
boardGrid->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Center;
boardGrid->Margin = Thickness(0);
boardGridBorder = ref new Border();
boardGridBorder->Padding = 2 * SideMargin;
boardGridBorder->Child = boardGrid;
}
void BoardPage::InitScrollViewer()
{
//init view
ScrollBoardView = ref new ScrollViewer();
ScrollBoardView->ZoomMode = Windows::UI::Xaml::Controls::ZoomMode::Enabled;
ScrollBoardView->HorizontalScrollBarVisibility = Windows::UI::Xaml::Controls::ScrollBarVisibility::Hidden;
ScrollBoardView->VerticalScrollBarVisibility = Windows::UI::Xaml::Controls::ScrollBarVisibility::Hidden;
ScrollBoardView->HorizontalContentAlignment = Windows::UI::Xaml::HorizontalAlignment::Center;
ScrollBoardView->VerticalContentAlignment = Windows::UI::Xaml::VerticalAlignment::Center;
ScrollBoardView->MinZoomFactor = 0.5;
ScrollBoardView->MaxZoomFactor = 3.0;
ScrollBoardView->Background = ref new SolidColorBrush(Windows::UI::Colors::DarkOrange);
ScrollBoardView->Content = boardGridBorder;
ScrollBoardView->Width = Window::Current->Bounds.Width;
ScrollBoardView->Height = Window::Current->Bounds.Height;
LayoutRoot->SetZIndex(ScrollBoardView, 1);
ScrollBoardView->RenderTransform = ref new RotateTransform();
((RotateTransform^)ScrollBoardView->RenderTransform)->CenterX = ScrollBoardView->Width / 2.0f;
((RotateTransform^)ScrollBoardView->RenderTransform)->CenterY = ScrollBoardView->Height / 2.0f;
ScrollBoardView->SizeChanged += ref new SizeChangedEventHandler(this, &BoardPage::UpdateScrollBoardViewScroll);
ScrollBoardView->Loaded += ref new RoutedEventHandler([this](Object ^ s, RoutedEventArgs ^ re){
double sw = ScrollBoardView->ScrollableWidth;
double sh = ScrollBoardView->ScrollableHeight;
ScrollBoardView->ChangeView(sw / 2.0, sh / 2.0, 1.0f);
});
LayoutRoot->Children->Append(ScrollBoardView);
}
void BoardPage::UpdateScrollBoardViewScroll(Object^ s, SizeChangedEventArgs^ e)
{
double ov = ScrollBoardView->HorizontalOffset;
double oh = ScrollBoardView->ScrollableHeight - ScrollBoardView->VerticalOffset;
ScrollBoardView->ChangeView(ov, oh, ScrollBoardView->ZoomFactor);
}
void BoardPage::DrawBoardGrid()
{
uint16_t bgWidth = currentMatch->board->sBoardWidth;
uint16_t bgHeight = currentMatch->board->sBoardHeight;
for (auto i = 0; i < bgWidth; ++i) {
Shapes::Line^ vertLine = ref new Shapes::Line();
vertLine->Stroke = ref new SolidColorBrush(defaultAppSettings::defaultGridColor);
vertLine->X1 = (1 + i) * SideMargin;
vertLine->X2 = vertLine->X1;
vertLine->Y1 = SideMargin;
vertLine->Y2 = SideMargin * bgHeight;
boardGrid->Children->Append(vertLine);
}
for (auto j = 0; j < bgHeight; ++j) {
Shapes::Line^ horiLine = ref new Shapes::Line();
horiLine->Stroke = ref new SolidColorBrush(defaultAppSettings::defaultGridColor);
horiLine->X1 = SideMargin;
horiLine->X2 = SideMargin * bgWidth;
horiLine->Y1 = (1 + j) * SideMargin;
horiLine->Y2 = horiLine->Y1;
boardGrid->Children->Append(horiLine);
}
}
void BoardPage::AddStone(ygcStoneColor^ turn, uint16_t x, uint16_t y)
{
Image^ stone = ref new Image();
stone->Name = "Stone" + x.ToString() + "x" + y.ToString();
stone->Source = ref new BitmapImage(ref new Uri(defaultAppSettings::defaultStones[turn]));
stone->Width = 0.9 * SideMargin;
stone->Height = stone->Width;
boardGrid->Children->Append(stone);
boardGrid->SetZIndex(stone, 2);
boardGrid->SetTop(stone, SideMargin * (y + 1) - stone->Width / 2.0);
boardGrid->SetLeft(stone, SideMargin * (x + 1) - stone->Width / 2.0);
stonesOnCanvas->Append(stone);
*currentMatch->board->GetAt(x, y)->takenBy = *turn;
}
bool BoardPage::RemoveStone(uint16_t x, uint16_t y)
{
uint32_t stoneIndex;
for (auto stone : stonesOnCanvas) {
if (stone->Name == "Stone" + x.ToString() + "x" + y.ToString()) {
boardGrid->Children->IndexOf(stone, &stoneIndex);
boardGrid->Children->RemoveAt(stoneIndex);
stonesOnCanvas->IndexOf(stone, &stoneIndex);
stonesOnCanvas->RemoveAt(stoneIndex);
*currentMatch->board->GetAt(x, y)->takenBy = 0;
return true;
}
}
return false;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void BoardPage::BoardOnNavigatedTo(NavigationEventArgs^ e)
{
(void) e; // Unused parameter
/*switch (Settings.OrientationLock)
{
case OrientationLock.Rotate:
this->SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
AppSpaceWidth = Window::Current->Bounds.Width;
AppSpaceHeight = Window::Current->Bounds.Height - 32;
break;
case OrientationLock.HorizontalLock:
this.SupportedOrientations = SupportedPageOrientation.Landscape;
break;
case OrientationLock.VerticalLock:
this.SupportedOrientations = SupportedPageOrientation.Portrait;
AppSpaceWidth = Window::Current->Bounds.Width;
AppSpaceHeight = Window::Current->Bounds.Height - 32;
break;
}*/
AppSpaceWidth = Window::Current->Bounds.Width;
AppSpaceHeight = Window::Current->Bounds.Height - 32.0 / Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->RawPixelsPerViewPixel;
boardGrid->Width = AppSpaceWidth;
boardGrid->Height = AppSpaceWidth * (currentMatch->board->sBoardHeight + 1) / double(currentMatch->board->sBoardWidth + 1);
((RotateTransform^)boardGrid->RenderTransform)->CenterX = boardGrid->Width / 2.0f;
((RotateTransform^)boardGrid->RenderTransform)->CenterY = boardGrid->Height / 2.0f;
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows::Phone::UI::Input::HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
void BoardPage::BoardOnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
{
}
void BoardPage::BoardOrientHandler(Object^ sender, SizeChangedEventArgs^ sce)
{
boardGrid->Background = ref new SolidColorBrush(Windows::UI::Colors::DimGray);
if (Windows::UI::ViewManagement::ApplicationView::GetForCurrentView()->Orientation == Windows::UI::ViewManagement::ApplicationViewOrientation::Portrait) {
AppSpaceWidth = Window::Current->Bounds.Width;
AppSpaceHeight = Window::Current->Bounds.Height - 32 / Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->RawPixelsPerViewPixel;
SideMargin = AppSpaceWidth / (currentMatch->board->sBoardWidth + 1); // TODO: Can we bound it to height in a nice fashion?
((RotateTransform^)boardGrid->RenderTransform)->Angle = 0.0f;
} else {
AppSpaceWidth = Window::Current->Bounds.Width - 72 / Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->RawPixelsPerViewPixel;
AppSpaceHeight = Window::Current->Bounds.Height;
SideMargin = AppSpaceHeight / (currentMatch->board->sBoardWidth + 1); // TODO: Can we bound it to height in a nice fashion?
((RotateTransform^)boardGrid->RenderTransform)->Angle = 270.0f;
}
ScrollBoardView->Height = AppSpaceHeight;
ScrollBoardView->Width = AppSpaceWidth;
}<|endoftext|> |
<commit_before><commit_msg>added Arduino sketch to adjust for timezones<commit_after><|endoftext|> |
<commit_before>/*
* Directory.cpp
*
* Implementation of Directory class in Directory.h
*
* Lead author:
* Dennis Egan
*
* Contributors:
* Justin Lesko
*/
#include "Directory.h"
#include "FCB.h"
#include <iostream>
#include <vector>
using namespace std;
/*
* Default constructor
*/
Directory::Directory(){
name = "";
}
/*
* Constructor to set name of directory
* :param dirName: name of directory
*/
Directory::Directory(string dirName){
name = dirName;
}
/*
* Deconstructor
*/
Directory::~Directory()
{
for(auto it = files.begin(); it != files.end(); it++)
delete *it;
files.clear();
}
// Setters and getters
string Directory::getName(){ return name; }
void Directory::setName(string newName){ name = newName;}
int Directory::getSize(){ return files.size(); }
vector<FCB*> Directory::getFiles(){ return files; }
/*
* Add file to directory
* :param newFile: file to be added to directory
*/
bool Directory::addFile(FCB* newFile)
{
if(!containsFile(newFile->getFileName()))
files.push_back(newFile);
}
/*
* Create file in directory
* If fileName not in directory -> true
* Else -> false
*
* :param fileName: name of file to create in directory
*/
bool Directory::createFile(string fileName){
// File was not in directory
if(!containsFile(fileName))
{
FCB* newFile = new FCB(fileName);
files.push_back(newFile);
return true;
}
// File was in directory
else
return false;
}
/*
* Delete file of name name from directory
* Returns true if found and deleted
*
* :param name: name of file to be deleted in directory
*/
bool Directory::deleteFile(string name)
{
for (int i = 0; i < files.size(); i++){
if (files[i]->getFileName() == name){
delete files[i];
files.erase(files.begin() + i);
return true;
}
i++;
}
return false;
}
/*
* Get file of name name from directory
* :param name: name of file to get
*/
FCB* Directory::getFile(string name)
{
if(!files.empty()){
for(int i = 0; i < files.size(); i++){
if(files[i]->getFileName() == name){
FCB* tmp = new FCB(*files[i]);
return tmp;
}
}
}
return NULL;
}
/*
* Get size of file of name name
* :param name: name of file to get size of
*/
int Directory::getFileSize(string name){
for(int i = 0; i < files.size(); i++){
if(files[i]->getFileName() == name)
return files[i]->getSize();
}
return -1;
}
/*
* Check if directory contains file of name name
* :param name: name of file to check if in directory
*/
bool Directory::containsFile(string name)
{
if(getFile(name) != NULL)
return true;
else
return false;
}
<commit_msg>Latest commit<commit_after>/*
* Directory.cpp
*
* Implementation of Directory class in Directory.h
*
* Lead author:
* Dennis Egan
*
* Contributors:
* Justin Lesko
*/
#include "Directory.h"
#include "FCB.h"
#include <iostream>
#include <vector>
using namespace std;
/*
* Default constructor
*/
Directory::Directory(){
name = "";
}
/*
* Constructor to set name of directory
* :param dirName: name of directory
*/
Directory::Directory(string dirName){
name = dirName;
}
/*
* Deconstructor
*/
Directory::~Directory()
{
for(auto it = files.begin(); it != files.end(); it++)
delete *it;
files.clear();
}
// Setters and getters
string Directory::getName(){ return name; }
void Directory::setName(string newName){ name = newName;}
int Directory::getSize(){ return files.size(); }
vector<FCB*> Directory::getFiles(){ return files; }
/*
* Add file to directory
* :param newFile: file to be added to directory
*/
bool Directory::addFile(FCB* newFile)
{
if(!containsFile(newFile->getFileName()))
files.push_back(newFile);
}
/*
* Create file in directory
* If fileName not in directory -> true
* Else -> false
*
* :param fileName: name of file to create in directory
*/
bool Directory::createFile(string fileName){
// File was not in directory
if(!containsFile(fileName))
{
FCB* newFile = new FCB(fileName);
files.push_back(newFile);
return true;
}
// File was in directory
else
return false;
}
/*
* Delete file of name name from directory
* Returns true if found and deleted
*
* :param name: name of file to be deleted in directory
*/
bool Directory::deleteFile(string name)
{
for (int i = 0; i < files.size(); i++){
if (files[i]->getFileName() == name){
delete files[i];
files.erase(files.begin() + i);
return true;
}
}
return false;
}
/*
* Get file of name name from directory
* :param name: name of file to get
*/
FCB* Directory::getFile(string name)
{
if(!files.empty()){
for(int i = 0; i < files.size(); i++){
if(files[i]->getFileName() == name){
FCB* tmp = new FCB(*files[i]);
return tmp;
}
}
}
return NULL;
}
/*
* Get size of file of name name
* :param name: name of file to get size of
*/
int Directory::getFileSize(string name){
for(int i = 0; i < files.size(); i++){
if(files[i]->getFileName() == name)
return files[i]->getSize();
}
return -1;
}
/*
* Check if directory contains file of name name
* :param name: name of file to check if in directory
*/
bool Directory::containsFile(string name)
{
if(getFile(name) != NULL)
return true;
else
return false;
}
<|endoftext|> |
<commit_before>#include "ClassDiagramGenerator.h"
#include <cplusplus/Overview.h>
#include <cplusplus/TypeOfExpression.h>
#include <cpptools/cppmodelmanager.h>
#include <cpptools/typehierarchybuilder.h>
#include <utils/qtcassert.h>
using namespace CppTools;
using namespace CPlusPlus;
namespace QtcUtilities {
namespace Internal {
namespace CodeDiscover {
enum Relation {
Extension, Dependency, Association
};
class Generator
{
public:
explicit Generator (ClassFlags f);
QString operator () (Symbol *symbol);
private:
void processHierarchy (const TypeHierarchy &hierarchy);
void processClass (const Class *c, const QList<TypeHierarchy> &hierarchy);
void processEnum (const Enum *e);
QString classView (const Class *c);
bool isInterface (const Class *c) const;
QString relation (const Symbol *l, Relation relation, const Symbol *r) const;
QString namespacedName (const Symbol *s) const;
QString accessType (const Symbol *s) const;
QString abstractStaticType (const Symbol *s) const;
QString member (Symbol *s, bool showDetails);
void processDependency (const QString &dependency, Class *dependant, Symbol *scope);
Symbol * find (const QString &name, Symbol *baseScope) const;
void addToSelectedHierarchy (const TypeHierarchy &hierarchy);
ClassFlags flags_;
Snapshot snapshot_;
QMap<Relation, QString> relationNames_;
Overview o_;
QStringList used_;
QStringList classes_;
QStringList relations_;
Symbol *selected_;
QSet<const Symbol *> selectedHierarchy_;
};
Generator::Generator (ClassFlags flags) :
flags_ (flags), snapshot_ (CppModelManager::instance ()->snapshot ()),
relationNames_ {{Extension, QStringLiteral ("<|--")},
{Dependency, QStringLiteral ("<...")},
{Association, QStringLiteral ("--")}},
selected_ (nullptr)
{
}
QString Generator::operator () (Symbol *symbol)
{
selected_ = symbol;
selectedHierarchy_ << symbol;
auto builder = TypeHierarchyBuilder (symbol, snapshot_);
auto hierarchy = builder.buildDerivedTypeHierarchy ();
addToSelectedHierarchy (hierarchy);
processHierarchy (hierarchy);
QStringList parts;
parts << QStringLiteral ("@startuml");
QMap<QString, QString> skins = {
{QStringLiteral ("selected"), QStringLiteral ("PaleGreen")},
{QStringLiteral ("hierarchy"), QStringLiteral ("PaleTurquoise")}
};
for (const auto &type: skins.keys ()) {
parts << QString (QStringLiteral ("skinparam class {\nBackgroundColor<<%1>> %2\n}"))
.arg (type, skins[type]);
parts << QString (QStringLiteral ("skinparam interface {\nBackgroundColor<<%1>> %2\n}"))
.arg (type, skins[type]);
}
parts << QStringLiteral ("set namespaceSeparator ::");
parts += classes_;
parts += relations_;
parts << QStringLiteral ("@enduml");
parts.removeDuplicates ();
return parts.join (QStringLiteral ("\n"));
}
bool isClassLike (const Symbol *s)
{
return (s->isClass () || s->isEnum ());
}
Symbol * Generator::find (const QString &name, Symbol *baseScope) const
{
if (isClassLike (baseScope)) {
return baseScope;
}
auto document = snapshot_.document (QString::fromUtf8 (baseScope->fileName ()));
auto *scope = document->scopeAt (baseScope->line ());
TypeOfExpression toe_;
toe_.init (document, snapshot_);
auto items = toe_ (name.toUtf8 (), scope);
for (auto item: items) {
if (auto *d = item.declaration ()) {
if (auto *t = d->asTemplate ()) {
d = t->declaration ();
}
if (!isClassLike (d)) {
continue;
}
return d;
}
}
return nullptr;
}
void Generator::addToSelectedHierarchy (const TypeHierarchy &hierarchy)
{
auto *symbol = hierarchy.symbol ();
selectedHierarchy_ << symbol;
if (flags_ & ShowBase) {
if (auto *c = symbol->asClass ()) {
for (uint i = 0, end = c->baseClassCount (); i < end; ++i) {
auto *base = c->baseClassAt (i);
if (auto *s = find (o_ (base->name ()), base)) {
addToSelectedHierarchy (s);
}
}
}
}
if (flags_ & ShowDerived) {
for (const auto &subHierarchy: hierarchy.hierarchy ()) {
addToSelectedHierarchy (subHierarchy);
}
}
}
void Generator::processHierarchy (const TypeHierarchy &hierarchy)
{
auto *symbol = hierarchy.symbol ();
auto name = o_ (symbol->name ());
if (used_.contains (name)) {
return;
}
used_ << name;
auto type = symbol->type ();
if (auto *c = type->asClassType ()) {
processClass (c, hierarchy.hierarchy ());
}
else if (auto *e = type->asEnumType ()) {
processEnum (e);
}
}
void Generator::processClass (const Class *c, const QList<TypeHierarchy> &hierarchy)
{
classes_ << classView (c);
if (flags_ & ShowBase) {
for (uint i = 0, end = c->baseClassCount (); i < end; ++i) {
auto *base = c->baseClassAt (i);
if (auto *processible = find (o_ (base->name ()), base)) {
processHierarchy (processible);
relations_ << relation (processible, Extension, c);
}
}
}
if (flags_ & ShowDerived) {
for (const auto &subHierarchy: hierarchy) {
processHierarchy (subHierarchy);
auto *s = subHierarchy.symbol ();
if (isClassLike (s)) {
relations_ << relation (c, Extension, s);
}
}
}
}
QString Generator::classView (const Class *c)
{
QStringList lines;
auto type = isInterface (c) ? QStringLiteral ("interface") : QStringLiteral ("class");
QString stereotype;
if (selected_ == c) {
stereotype = QStringLiteral ("<<selected>>");
}
else if (selectedHierarchy_.contains (c)) {
stereotype = QStringLiteral ("<<hierarchy>>");
}
lines << QString (QStringLiteral ("%1 %2%3 {")).arg (type, namespacedName (c),
stereotype);
auto inHierarchy = selectedHierarchy_.contains (c);
auto showMemberDetails = ((flags_ & ShowHierarchyDetails) && inHierarchy)
|| c == selected_
|| ((flags_ & ShowDependsDetails) && !inHierarchy);
for (uint i = 0, end = c->memberCount (); i < end; ++i) {
lines << member (c->memberAt (i), showMemberDetails);
}
lines << QStringLiteral ("}");
return lines.join (QStringLiteral ("\n"));
}
bool Generator::isInterface (const Class *c) const
{
for (uint i = 0, end = c->memberCount (); i < end; ++i) {
auto *symbol = c->memberAt (i);
if (auto *f = symbol->type ()->asFunctionType ()) {
if (f->isPureVirtual ()) {
return true;
}
}
}
return false;
}
QString Generator::relation (const Symbol *l, Relation relation, const Symbol *r) const
{
return namespacedName (l)
+ relationNames_.value (relation, QStringLiteral ("--"))
+ namespacedName (r);
}
QString Generator::namespacedName (const Symbol *s) const
{
QStringList classes;
classes << o_ (s->name ());
for (auto *i = s->enclosingClass (); i; i = i->enclosingClass ()) {
classes.prepend (o_ (i->name ()));
}
classes.removeAll ({});
QStringList namespaces;
namespaces << classes.join (QStringLiteral ("."));
for (auto *i = s->enclosingNamespace (); i; i = i->enclosingNamespace ()) {
namespaces.prepend (o_ (i->name ()));
}
namespaces.removeAll ({});
return namespaces.join (QStringLiteral ("::"));
}
QString Generator::accessType (const Symbol *s) const
{
if (s->isPublic () && (flags_ & ShowPublic)) {
return QStringLiteral ("+");
}
else if (s->isProtected () && (flags_ & ShowProtected)) {
return QStringLiteral ("#");
}
else if (s->isPrivate () && (flags_ & ShowPrivate)) {
return QStringLiteral ("-");
}
else {
return {};
}
}
QString Generator::abstractStaticType (const Symbol *s) const
{
auto type = s->type ();
if (type.isStatic ()) {
return QStringLiteral ("{static}");
}
else if (type.isVirtual ()) {
return QStringLiteral ("{abstract}");
}
return {};
}
void Generator::processEnum (const Enum *e)
{
QStringList lines;
lines << QString (QStringLiteral ("enum %1 {")).arg (namespacedName (e));
if (flags_ & ShowDependsDetails) {
for (uint i = 0, end = e->memberCount (); i < end; ++i) {
lines << o_ (e->memberAt (i)->name ());
}
}
lines << QStringLiteral ("}");
classes_ << lines.join (QStringLiteral ("\n"));
}
QString Generator::member (Symbol *s, bool showDetails)
{
auto access = accessType (s);
auto notFilteredByAccess = !access.isEmpty ();
auto lead = QString (access + abstractStaticType (s));
auto type = s->type ();
auto name = o_ (s->name ());
if (auto *f = type->asFunctionType ()) {
auto returnType = f->returnType ();
if ((flags_ & ShowDependencies) && returnType->isNamedType ()) {
processDependency (o_ (returnType), s->enclosingClass (), s);
}
if ((flags_ & ShowMethods) && notFilteredByAccess && showDetails) {
return QString (QStringLiteral ("%1 %2 %3: %4"))
.arg (lead, name, o_ (type), o_ (returnType));
}
return {};
}
if (s->isDeclaration ()) {
if ((flags_ & ShowDependencies) && type->isNamedType ()) {
processDependency (o_ (type), s->enclosingClass (), s);
}
if ((flags_ & ShowMembers) && notFilteredByAccess && showDetails) {
return QString (QStringLiteral ("%1 %2: %3")).arg (lead, name, o_ (type));
}
return {};
}
if (isClassLike (s)) {
processHierarchy (s);
relations_ << relation (s, Association, s->enclosingClass ());
return {};
}
return {};
}
void Generator::processDependency (const QString &dependency, Class *dependant,
Symbol *scope)
{
if (auto *d = find (dependency, scope)) {
processHierarchy (d);
relations_ << relation (d, Dependency, dependant);
}
if (dependency.contains (QStringLiteral ("<"))) {
auto begin = dependency.indexOf (QStringLiteral ("<"));
auto end = dependency.indexOf (QStringLiteral (">"));
if (begin != -1 && end != -1) {
auto arguments = dependency.mid (begin + 1, end - begin - 1);
for (const auto &i: arguments.split (QStringLiteral (","))) {
if (auto *processable = find (i, scope)) {
processHierarchy (processable);
relations_ << relation (processable, Dependency, dependant);
}
}
}
}
}
ClassDiagramGenerator::ClassDiagramGenerator (QObject *parent) : QObject (parent)
{
}
QString ClassDiagramGenerator::generate (Symbol *symbol, ClassFlags flags) const
{
QTC_ASSERT (symbol, {});
QString source;
if (isClassLike (symbol)) {
Generator generator (flags);
source = generator.operator () (symbol);
}
return source;
}
} // namespace CodeDiscover
} // namespace Internal
} // namespace QtcUtilities
<commit_msg>Don't count friends as methods.<commit_after>#include "ClassDiagramGenerator.h"
#include <cplusplus/Overview.h>
#include <cplusplus/TypeOfExpression.h>
#include <cpptools/cppmodelmanager.h>
#include <cpptools/typehierarchybuilder.h>
#include <utils/qtcassert.h>
using namespace CppTools;
using namespace CPlusPlus;
namespace QtcUtilities {
namespace Internal {
namespace CodeDiscover {
enum Relation {
Extension, Dependency, Association
};
class Generator
{
public:
explicit Generator (ClassFlags f);
QString operator () (Symbol *symbol);
private:
void processHierarchy (const TypeHierarchy &hierarchy);
void processClass (const Class *c, const QList<TypeHierarchy> &hierarchy);
void processEnum (const Enum *e);
QString classView (const Class *c);
bool isInterface (const Class *c) const;
QString relation (const Symbol *l, Relation relation, const Symbol *r) const;
QString namespacedName (const Symbol *s) const;
QString accessType (const Symbol *s) const;
QString abstractStaticType (const Symbol *s) const;
QString member (Symbol *s, bool showDetails);
void processDependency (const QString &dependency, Class *dependant, Symbol *scope);
Symbol * find (const QString &name, Symbol *baseScope) const;
void addToSelectedHierarchy (const TypeHierarchy &hierarchy);
ClassFlags flags_;
Snapshot snapshot_;
QMap<Relation, QString> relationNames_;
Overview o_;
QStringList used_;
QStringList classes_;
QStringList relations_;
Symbol *selected_;
QSet<const Symbol *> selectedHierarchy_;
};
Generator::Generator (ClassFlags flags) :
flags_ (flags), snapshot_ (CppModelManager::instance ()->snapshot ()),
relationNames_ {{Extension, QStringLiteral ("<|--")},
{Dependency, QStringLiteral ("<...")},
{Association, QStringLiteral ("--")}},
selected_ (nullptr)
{
}
QString Generator::operator () (Symbol *symbol)
{
selected_ = symbol;
selectedHierarchy_ << symbol;
auto builder = TypeHierarchyBuilder (symbol, snapshot_);
auto hierarchy = builder.buildDerivedTypeHierarchy ();
addToSelectedHierarchy (hierarchy);
processHierarchy (hierarchy);
QStringList parts;
parts << QStringLiteral ("@startuml");
QMap<QString, QString> skins = {
{QStringLiteral ("selected"), QStringLiteral ("PaleGreen")},
{QStringLiteral ("hierarchy"), QStringLiteral ("PaleTurquoise")}
};
for (const auto &type: skins.keys ()) {
parts << QString (QStringLiteral ("skinparam class {\nBackgroundColor<<%1>> %2\n}"))
.arg (type, skins[type]);
parts << QString (QStringLiteral ("skinparam interface {\nBackgroundColor<<%1>> %2\n}"))
.arg (type, skins[type]);
}
parts << QStringLiteral ("set namespaceSeparator ::");
parts += classes_;
parts += relations_;
parts << QStringLiteral ("@enduml");
parts.removeDuplicates ();
return parts.join (QStringLiteral ("\n"));
}
bool isClassLike (const Symbol *s)
{
return (s->isClass () || s->isEnum ());
}
Symbol * Generator::find (const QString &name, Symbol *baseScope) const
{
if (isClassLike (baseScope)) {
return baseScope;
}
auto document = snapshot_.document (QString::fromUtf8 (baseScope->fileName ()));
auto *scope = document->scopeAt (baseScope->line ());
TypeOfExpression toe_;
toe_.init (document, snapshot_);
auto items = toe_ (name.toUtf8 (), scope);
for (auto item: items) {
if (auto *d = item.declaration ()) {
if (auto *t = d->asTemplate ()) {
d = t->declaration ();
}
if (!isClassLike (d)) {
continue;
}
return d;
}
}
return nullptr;
}
void Generator::addToSelectedHierarchy (const TypeHierarchy &hierarchy)
{
auto *symbol = hierarchy.symbol ();
selectedHierarchy_ << symbol;
if (flags_ & ShowBase) {
if (auto *c = symbol->asClass ()) {
for (uint i = 0, end = c->baseClassCount (); i < end; ++i) {
auto *base = c->baseClassAt (i);
if (auto *s = find (o_ (base->name ()), base)) {
addToSelectedHierarchy (s);
}
}
}
}
if (flags_ & ShowDerived) {
for (const auto &subHierarchy: hierarchy.hierarchy ()) {
addToSelectedHierarchy (subHierarchy);
}
}
}
void Generator::processHierarchy (const TypeHierarchy &hierarchy)
{
auto *symbol = hierarchy.symbol ();
auto name = o_ (symbol->name ());
if (used_.contains (name)) {
return;
}
used_ << name;
auto type = symbol->type ();
if (auto *c = type->asClassType ()) {
processClass (c, hierarchy.hierarchy ());
}
else if (auto *e = type->asEnumType ()) {
processEnum (e);
}
}
void Generator::processClass (const Class *c, const QList<TypeHierarchy> &hierarchy)
{
classes_ << classView (c);
if (flags_ & ShowBase) {
for (uint i = 0, end = c->baseClassCount (); i < end; ++i) {
auto *base = c->baseClassAt (i);
if (auto *processible = find (o_ (base->name ()), base)) {
processHierarchy (processible);
relations_ << relation (processible, Extension, c);
}
}
}
if (flags_ & ShowDerived) {
for (const auto &subHierarchy: hierarchy) {
processHierarchy (subHierarchy);
auto *s = subHierarchy.symbol ();
if (isClassLike (s)) {
relations_ << relation (c, Extension, s);
}
}
}
}
QString Generator::classView (const Class *c)
{
QStringList lines;
auto type = isInterface (c) ? QStringLiteral ("interface") : QStringLiteral ("class");
QString stereotype;
if (selected_ == c) {
stereotype = QStringLiteral ("<<selected>>");
}
else if (selectedHierarchy_.contains (c)) {
stereotype = QStringLiteral ("<<hierarchy>>");
}
lines << QString (QStringLiteral ("%1 %2%3 {")).arg (type, namespacedName (c),
stereotype);
auto inHierarchy = selectedHierarchy_.contains (c);
auto showMemberDetails = ((flags_ & ShowHierarchyDetails) && inHierarchy)
|| c == selected_
|| ((flags_ & ShowDependsDetails) && !inHierarchy);
for (uint i = 0, end = c->memberCount (); i < end; ++i) {
lines << member (c->memberAt (i), showMemberDetails);
}
lines << QStringLiteral ("}");
return lines.join (QStringLiteral ("\n"));
}
bool Generator::isInterface (const Class *c) const
{
for (uint i = 0, end = c->memberCount (); i < end; ++i) {
auto *symbol = c->memberAt (i);
if (auto *f = symbol->type ()->asFunctionType ()) {
if (f->isPureVirtual ()) {
return true;
}
}
}
return false;
}
QString Generator::relation (const Symbol *l, Relation relation, const Symbol *r) const
{
return namespacedName (l)
+ relationNames_.value (relation, QStringLiteral ("--"))
+ namespacedName (r);
}
QString Generator::namespacedName (const Symbol *s) const
{
QStringList classes;
classes << o_ (s->name ());
for (auto *i = s->enclosingClass (); i; i = i->enclosingClass ()) {
classes.prepend (o_ (i->name ()));
}
classes.removeAll ({});
QStringList namespaces;
namespaces << classes.join (QStringLiteral ("."));
for (auto *i = s->enclosingNamespace (); i; i = i->enclosingNamespace ()) {
namespaces.prepend (o_ (i->name ()));
}
namespaces.removeAll ({});
return namespaces.join (QStringLiteral ("::"));
}
QString Generator::accessType (const Symbol *s) const
{
if (s->isPublic () && (flags_ & ShowPublic)) {
return QStringLiteral ("+");
}
else if (s->isProtected () && (flags_ & ShowProtected)) {
return QStringLiteral ("#");
}
else if (s->isPrivate () && (flags_ & ShowPrivate)) {
return QStringLiteral ("-");
}
else {
return {};
}
}
QString Generator::abstractStaticType (const Symbol *s) const
{
auto type = s->type ();
if (type.isStatic ()) {
return QStringLiteral ("{static}");
}
else if (type.isVirtual ()) {
return QStringLiteral ("{abstract}");
}
return {};
}
void Generator::processEnum (const Enum *e)
{
QStringList lines;
lines << QString (QStringLiteral ("enum %1 {")).arg (namespacedName (e));
if (flags_ & ShowDependsDetails) {
for (uint i = 0, end = e->memberCount (); i < end; ++i) {
lines << o_ (e->memberAt (i)->name ());
}
}
lines << QStringLiteral ("}");
classes_ << lines.join (QStringLiteral ("\n"));
}
QString Generator::member (Symbol *s, bool showDetails)
{
auto access = accessType (s);
auto notFilteredByAccess = !access.isEmpty ();
auto lead = QString (access + abstractStaticType (s));
auto type = s->type ();
auto name = o_ (s->name ());
if (auto *f = type->asFunctionType ()) {
auto returnType = f->returnType ();
if ((flags_ & ShowDependencies) && returnType->isNamedType ()) {
processDependency (o_ (returnType), s->enclosingClass (), s);
}
if ((flags_ & ShowMethods) && notFilteredByAccess && showDetails && !f->isFriend ()) {
return QString (QStringLiteral ("%1 %2 %3: %4"))
.arg (lead, name, o_ (type), o_ (returnType));
}
return {};
}
if (s->isDeclaration ()) {
if ((flags_ & ShowDependencies) && type->isNamedType ()) {
processDependency (o_ (type), s->enclosingClass (), s);
}
if ((flags_ & ShowMembers) && notFilteredByAccess && showDetails) {
return QString (QStringLiteral ("%1 %2: %3")).arg (lead, name, o_ (type));
}
return {};
}
if (isClassLike (s)) {
processHierarchy (s);
relations_ << relation (s, Association, s->enclosingClass ());
return {};
}
return {};
}
void Generator::processDependency (const QString &dependency, Class *dependant,
Symbol *scope)
{
if (auto *d = find (dependency, scope)) {
processHierarchy (d);
relations_ << relation (d, Dependency, dependant);
}
if (dependency.contains (QStringLiteral ("<"))) {
auto begin = dependency.indexOf (QStringLiteral ("<"));
auto end = dependency.indexOf (QStringLiteral (">"));
if (begin != -1 && end != -1) {
auto arguments = dependency.mid (begin + 1, end - begin - 1);
for (const auto &i: arguments.split (QStringLiteral (","))) {
if (auto *processable = find (i, scope)) {
processHierarchy (processable);
relations_ << relation (processable, Dependency, dependant);
}
}
}
}
}
ClassDiagramGenerator::ClassDiagramGenerator (QObject *parent) : QObject (parent)
{
}
QString ClassDiagramGenerator::generate (Symbol *symbol, ClassFlags flags) const
{
QTC_ASSERT (symbol, {});
QString source;
if (isClassLike (symbol)) {
Generator generator (flags);
source = generator.operator () (symbol);
}
return source;
}
} // namespace CodeDiscover
} // namespace Internal
} // namespace QtcUtilities
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/touchpad.h"
#include <stdlib.h>
#include <string>
#include <vector>
#include "base/string_util.h"
#include "base/process_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_member.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
// Allows InvokeLater without adding refcounting. The object is only deleted
// when its last InvokeLater is run anyway.
template<>
void RunnableMethodTraits<Touchpad>::RetainCallee(
Touchpad* remover) {
}
template<>
void RunnableMethodTraits<Touchpad>::ReleaseCallee(
Touchpad* remover) {
}
// static
void Touchpad::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterBooleanPref(prefs::kTapToClickEnabled, false);
prefs->RegisterBooleanPref(prefs::kVertEdgeScrollEnabled, true);
prefs->RegisterIntegerPref(prefs::kTouchpadSpeedFactor, 5);
prefs->RegisterIntegerPref(prefs::kTouchpadSensitivity, 5);
}
void Touchpad::Init(PrefService* prefs) {
tap_to_click_enabled_.Init(prefs::kTapToClickEnabled, prefs, this);
vert_edge_scroll_enabled_.Init(prefs::kVertEdgeScrollEnabled, prefs, this);
speed_factor_.Init(prefs::kTouchpadSpeedFactor, prefs, this);
sensitivity_.Init(prefs::kTouchpadSensitivity, prefs, this);
// Initialize touchpad settings to what's saved in user preferences.
SetTapToClick();
SetVertEdgeScroll();
SetSpeedFactor();
SetSensitivity();
}
void Touchpad::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::PREF_CHANGED)
NotifyPrefChanged(Details<std::wstring>(details).ptr());
}
void Touchpad::NotifyPrefChanged(const std::wstring* pref_name) {
if (!pref_name || *pref_name == prefs::kTapToClickEnabled)
SetTapToClick();
if (!pref_name || *pref_name == prefs::kVertEdgeScrollEnabled)
SetVertEdgeScroll();
if (!pref_name || *pref_name == prefs::kTouchpadSpeedFactor)
SetSpeedFactor();
if (!pref_name || *pref_name == prefs::kTouchpadSensitivity)
SetSensitivity();
}
void Touchpad::SetSynclientParam(const std::string& param, double value) {
// If not running on the file thread, then re-run on the file thread.
if (!ChromeThread::CurrentlyOn(ChromeThread::FILE)) {
base::Thread* file_thread = g_browser_process->file_thread();
if (file_thread)
file_thread->message_loop()->PostTask(FROM_HERE,
NewRunnableMethod(this, &Touchpad::SetSynclientParam, param, value));
} else {
// launch binary synclient to set the parameter
std::vector<std::string> argv;
argv.push_back("/usr/bin/synclient");
argv.push_back(StringPrintf("%s=%f", param.c_str(), value));
base::file_handle_mapping_vector no_files;
base::ProcessHandle handle;
if (!base::LaunchApp(argv, no_files, true, &handle))
LOG(ERROR) << "Failed to call /usr/bin/synclient";
}
}
void Touchpad::SetTapToClick() {
// To disable tap-to-click (i.e. a tap on the touchpad is recognized as a left
// mouse click event), we set MaxTapTime to 0. MaxTapTime is the maximum time
// (in milliseconds) for detecting a tap. The default is 180.
if (tap_to_click_enabled_.GetValue())
SetSynclientParam("MaxTapTime", 180);
else
SetSynclientParam("MaxTapTime", 0);
}
void Touchpad::SetVertEdgeScroll() {
// To disable vertical edge scroll, we set VertEdgeScroll to 0. Vertical edge
// scroll lets you use the right edge of the touchpad to control the movement
// of the vertical scroll bar.
if (vert_edge_scroll_enabled_.GetValue())
SetSynclientParam("VertEdgeScroll", 1);
else
SetSynclientParam("VertEdgeScroll", 0);
}
void Touchpad::SetSpeedFactor() {
// To set speed factor, we use MinSpeed. Both MaxSpeed and AccelFactor are 0.
// So MinSpeed will control the speed of the cursor with respect to the
// touchpad movement and there will not be any acceleration.
// MinSpeed is between 0.01 and 1.00. The preference is an integer between
// 1 and 10, so we divide that by 10 for the value of MinSpeed.
int value = speed_factor_.GetValue();
if (value < 1)
value = 1;
if (value > 10)
value = 10;
// Convert from 1-10 to 0.1-1.0
double d = static_cast<double>(value) / 10.0;
SetSynclientParam("MinSpeed", d);
}
void Touchpad::SetSensitivity() {
// To set the touch sensitivity, we use FingerHigh, which represents the
// the pressure needed for a tap to be registered. The range of FingerHigh
// goes from 30 to 75. We store the sensitivity preference as an int from
// 1 to 10. So we need to map the preference value of 1 to 10 to the
// FingerHigh value of 30 to 75.
int value = sensitivity_.GetValue();
if (value < 1)
value = 1;
if (value > 10)
value = 10;
// Convert from 1-10 to 30-75.
double d = value * 5 + 25;
SetSynclientParam("FingerHigh", d);
}
<commit_msg>Lands http://codereview.chromium.org/231008 for Charlie:<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/touchpad.h"
#include <stdlib.h>
#include <string>
#include <vector>
#include "base/string_util.h"
#include "base/process_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_member.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
// Allows InvokeLater without adding refcounting. The object is only deleted
// when its last InvokeLater is run anyway.
template<>
void RunnableMethodTraits<Touchpad>::RetainCallee(
Touchpad* remover) {
}
template<>
void RunnableMethodTraits<Touchpad>::ReleaseCallee(
Touchpad* remover) {
}
// static
void Touchpad::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterBooleanPref(prefs::kTapToClickEnabled, false);
prefs->RegisterBooleanPref(prefs::kVertEdgeScrollEnabled, false);
prefs->RegisterIntegerPref(prefs::kTouchpadSpeedFactor, 5);
prefs->RegisterIntegerPref(prefs::kTouchpadSensitivity, 5);
}
void Touchpad::Init(PrefService* prefs) {
tap_to_click_enabled_.Init(prefs::kTapToClickEnabled, prefs, this);
vert_edge_scroll_enabled_.Init(prefs::kVertEdgeScrollEnabled, prefs, this);
speed_factor_.Init(prefs::kTouchpadSpeedFactor, prefs, this);
sensitivity_.Init(prefs::kTouchpadSensitivity, prefs, this);
// Initialize touchpad settings to what's saved in user preferences.
SetTapToClick();
SetVertEdgeScroll();
SetSpeedFactor();
SetSensitivity();
}
void Touchpad::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::PREF_CHANGED)
NotifyPrefChanged(Details<std::wstring>(details).ptr());
}
void Touchpad::NotifyPrefChanged(const std::wstring* pref_name) {
if (!pref_name || *pref_name == prefs::kTapToClickEnabled)
SetTapToClick();
if (!pref_name || *pref_name == prefs::kVertEdgeScrollEnabled)
SetVertEdgeScroll();
if (!pref_name || *pref_name == prefs::kTouchpadSpeedFactor)
SetSpeedFactor();
if (!pref_name || *pref_name == prefs::kTouchpadSensitivity)
SetSensitivity();
}
void Touchpad::SetSynclientParam(const std::string& param, double value) {
// If not running on the file thread, then re-run on the file thread.
if (!ChromeThread::CurrentlyOn(ChromeThread::FILE)) {
base::Thread* file_thread = g_browser_process->file_thread();
if (file_thread)
file_thread->message_loop()->PostTask(FROM_HERE,
NewRunnableMethod(this, &Touchpad::SetSynclientParam, param, value));
} else {
// launch binary synclient to set the parameter
std::vector<std::string> argv;
argv.push_back("/usr/bin/synclient");
argv.push_back(StringPrintf("%s=%f", param.c_str(), value));
base::file_handle_mapping_vector no_files;
base::ProcessHandle handle;
if (!base::LaunchApp(argv, no_files, true, &handle))
LOG(ERROR) << "Failed to call /usr/bin/synclient";
}
}
void Touchpad::SetTapToClick() {
// To disable tap-to-click (i.e. a tap on the touchpad is recognized as a left
// mouse click event), we set MaxTapTime to 0. MaxTapTime is the maximum time
// (in milliseconds) for detecting a tap. The default is 180.
if (tap_to_click_enabled_.GetValue())
SetSynclientParam("MaxTapTime", 180);
else
SetSynclientParam("MaxTapTime", 0);
}
void Touchpad::SetVertEdgeScroll() {
// To disable vertical edge scroll, we set VertEdgeScroll to 0. Vertical edge
// scroll lets you use the right edge of the touchpad to control the movement
// of the vertical scroll bar.
if (vert_edge_scroll_enabled_.GetValue())
SetSynclientParam("VertEdgeScroll", 1);
else
SetSynclientParam("VertEdgeScroll", 0);
}
void Touchpad::SetSpeedFactor() {
// To set speed factor, we use MinSpeed. Both MaxSpeed and AccelFactor are 0.
// So MinSpeed will control the speed of the cursor with respect to the
// touchpad movement and there will not be any acceleration.
// MinSpeed is between 0.01 and 1.00. The preference is an integer between
// 1 and 10, so we divide that by 10 for the value of MinSpeed.
int value = speed_factor_.GetValue();
if (value < 1)
value = 1;
if (value > 10)
value = 10;
// Convert from 1-10 to 0.1-1.0
double d = static_cast<double>(value) / 10.0;
SetSynclientParam("MinSpeed", d);
}
void Touchpad::SetSensitivity() {
// To set the touch sensitivity, we use FingerHigh, which represents the
// the pressure needed for a tap to be registered. The range of FingerHigh
// goes from 25 to 70. We store the sensitivity preference as an int from
// 1 to 10. So we need to map the preference value of 1 to 10 to the
// FingerHigh value of 25 to 70 inversely.
int value = sensitivity_.GetValue();
if (value < 1)
value = 1;
if (value > 10)
value = 10;
// Convert from 1-10 to 70-25.
double d = (15 - value) * 5;
SetSynclientParam("FingerHigh", d);
}
<|endoftext|> |
<commit_before>// This header inspired P0052R5
// Copyright (C) 2011-2018 Roki. Distributed under the MIT License
#ifndef INCLUDED_SROOK_SCOPE_UNIQUE_RESOURCE_HPP
#define INCLUDED_SROOK_SCOPE_UNIQUE_RESOURCE_HPP
#include <srook/config/attribute/visibility.hpp>
#include <srook/config/cpp_predefined.hpp>
#include <srook/config/feature.hpp>
#include <srook/config/require.hpp>
#include <srook/type_traits.hpp>
#include <srook/utility.hpp>
#include <type_traits>
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
# define CJUNCT srook::type_traits::detail::Land
# define DJUNCT srook::type_traits::detail::Lor
#else
# define CJUNCT srook::type_traits::detail::Land_2
# define DJUNCT srook::type_traits::detail::Lor_2
#endif
namespace srook {
namespace scope {
namespace detail {
template <class T>
struct is_nothrow_movable
: bool_constant<CJUNCT<std::is_nothrow_move_constructible<T>, std::is_nothrow_move_assignable<T> >::value> {
};
} // namespace detail
template <class R, class D>
class SROOK_ATTRIBUTE_TEMPLATE_VIS_DEFAULT unique_resource : noncopyable<unique_resource<R, D> > {
SROOK_STATIC_ASSERT((DJUNCT<std::is_nothrow_move_constructible<R>, srook::is_copy_constructible<R> >::value),
"resource must be nothrow_move_constructible or copy_consturcitble");
SROOK_STATIC_ASSERT((DJUNCT<std::is_nothrow_move_constructible<D>, srook::is_copy_constructible<D> >::value),
"deleter must be nothrow_move_constructible or copy_consturcitble");
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
static SROOK_CONSTEXPR bool
is_nothrow_delete_v = noexcept(declval<D&>()(declval<R&>())),
is_nothrow_swappable_v = is_nothrow_delete_v and CJUNCT<detail::is_nothrow_movable<R>, detail::is_nothrow_movable<D> >::value;
#endif
unique_resource& operator=(const unique_resource&) SROOK_EQ_DELETE
unique_resource(const unique_resource&) SROOK_EQ_DELETE
public:
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
template <class RR, class DD, REQUIRES(CJUNCT<is_constructible<R, RR>, is_constructible<D, DD> >::value)>
SROOK_ATTRIBUTE_INLINE_VISIBILITY explicit
unique_resource(RR&& r, DD&& d)
: resource(srook::forward<RR>(r)), deleter(srook::forward<DD>(d))
{}
#else
template <class RR, class DD>
SROOK_ATTRIBUTE_INLINE_VISIBILITY explicit
unique_resource(utility::cxx03::move_tag<RR> r, utility::cxx03::move_tag<DD> d,
REQUIRES(CJUNCT<is_constructible<R, RR>, is_constructible<D, DD> >::value) = SROOK_NULLPTR_T())
: resource(r.get()), deleter(d.get()), execute_on_destruction(true)
{}
template <class RR, class DD>
SROOK_ATTRIBUTE_INLINE_VISIBILITY explicit
unique_resource(const RR& r, const DD& d,
REQUIRES(CJUNCT<is_constructible<R, RR>, is_constructible<D, DD> >::value) = SROOK_NULLPTR_T())
: resource(r), deleter(d), execute_on_destruction(true)
{}
#endif
SROOK_ATTRIBUTE_INLINE_VISIBILITY
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
unique_resource(unique_resource&& rhs)
: resource(srook::move(rhs.resource)),
deleter(srook::move(rhs.deleter)),
execute_on_destruction(exchange(rhs.execute_on_destruction, false))
#else
unique_resource(utility::cxx03::move_tag<unique_resource> rhs)
: resource(rhs.get().resource),
deleter(rhs.get().deleter),
execute_on_destruction(exchange(rhs.get().execute_on_destruction, false))
#endif
{}
SROOK_ATTRIBUTE_INLINE_VISIBILITY
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
unique_resource& operator=(unique_resource&& rhs)
#else
unique_resource& operator=(utility::cxx03::move_tag<unique_resource> rhs)
#endif
SROOK_NOEXCEPT((is_nothrow_delete_v and CJUNCT<std::is_nothrow_move_assignable<R>, std::is_nothrow_move_assignable<D> >::value))
{
SROOK_STATIC_ASSERT((DJUNCT<std::is_nothrow_move_assignable<R>, is_copy_assignable<R> >::value),
"The resource must be nothrow-move assignable, or copy assignable");
SROOK_STATIC_ASSERT((DJUNCT<std::is_nothrow_move_assignable<D>, is_copy_assignable<R> >::value),
"The resource must be nothrow-move assignable, or copy assignable");
if (&rhs == this) return *this;
reset();
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
deleter = srook::move(rhs.deleter);
resource = srook::move(rhs.resource);
execute_on_destruction = exchange(rhs.execute_on_destruction, false);
#else
deleter = rhs.get().deleter;
resource = rhs.get().resource;
execute_on_destruction = exchange(rhs.get().execute_on_destruction, false);
#endif
return *this;
}
SROOK_ATTRIBUTE_INLINE_VISIBILITY
~unique_resource()
{
reset();
}
void swap(unique_resource& other)
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
SROOK_NOEXCEPT(is_nothrow_swappable_v)
#endif
{
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
SROOK_IF_CONSTEXPR(is_nothrow_swappable_v) {
using std::swap;
swap(execute_on_destruction, other.execute_on_destruction);
swap(resource, other.resource);
swap(deleter, other.deleter);
} else {
#endif
unique_resource tmp = srook::move(*this);
*this = srook::move(other);
other = srook::move(tmp);
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
}
#endif
}
void reset()
SROOK_NOEXCEPT(is_nothrow_delete_v)
{
if (execute_on_destruction) {
execute_on_destruction = false;
deleter(resource);
}
}
template <class RR>
void reset(RR& r)
SROOK_NOEXCEPT(is_nothrow_delete_v)
{
reset();
resource = srook::move(r);
execute_on_destruction = true;
release();
}
SROOK_FORCE_INLINE
R release() SROOK_NOEXCEPT_TRUE
{
execute_on_destruction = false;
return get();
}
SROOK_FORCE_INLINE
const R& get() const SROOK_NOEXCEPT_TRUE
{
return resource;
}
SROOK_FORCE_INLINE
R operator->() const SROOK_NOEXCEPT_TRUE
{
return resource;
}
SROOK_FORCE_INLINE
typename std::add_lvalue_reference<typename srook::remove_pointer<R>::type>::type
operator*() const SROOK_NOEXCEPT_TRUE
{
return resource;
}
private:
R resource;
D deleter;
bool execute_on_destruction
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
= true
#endif
;
};
template <class R, class D>
unique_resource<typename decay<R>::type, typename decay<D>::type>
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
make_unique_resource(R&& r, D&& d)
#else
make_unique_resource(utility::cxx03::move_tag<R> r, utility::cxx03::move_tag<D> d)
#endif
SROOK_NOEXCEPT((is_nothrow_constructible<unique_resource<typename decay<R>::type, typename decay<D>::type>, R, D>::value))
{
return unique_resource<typename decay<R>::type, typename decay<D>::type>(srook::forward<R>(r), srook::forward<D>(d));
}
template <class R, class D>
unique_resource<R, typename remove_reference<D>::type>
make_unique_resource(std::reference_wrapper<R> r,
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
D&& d
#else
utility::cxx03::move_tag<D> d
#endif
)
SROOK_NOEXCEPT((is_nothrow_constructible<unique_resource<R, typename remove_reference<D>::type>, decltype(r.get()), declval<D>()>::value))
{
return unique_resource<R, typename srook::remove_reference<D>::type>(r.get(), srook::forward<D>(d));
}
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS17_CONSTANT
template <class R, class D>
unique_resource(R&& r, D&& d)
-> unique_resource<typename decay<R>::type, typename decay<D>::type>;
template <class R, class D>
unique_resource(std::reference_wrapper<R> r, D&& d)
-> unique_resource<R&, typename decay<D>::type>;
#endif
} // namespace scope
using scope::make_unique_resource;
using scope::unique_resource;
} // namespace srook
# undef CJUNCT
# undef DJUNCT
#endif
<commit_msg>fix includes<commit_after>// This header inspired P0052R5
// Copyright (C) 2011-2018 Roki. Distributed under the MIT License
#ifndef INCLUDED_SROOK_SCOPE_UNIQUE_RESOURCE_HPP
#define INCLUDED_SROOK_SCOPE_UNIQUE_RESOURCE_HPP
#include <srook/config/attribute/visibility.hpp>
#include <srook/config/cpp_predefined.hpp>
#include <srook/config/feature.hpp>
#include <srook/config/require.hpp>
#include <srook/type_traits/is_constructible.hpp>
#include <srook/type_traits/is_copy_assignable.hpp>
#include <srook/type_traits/remove_pointer.hpp>
#include <srook/type_traits/is_copy_constructible.hpp>
#include <srook/type_traits/decay.hpp>
#include <srook/utility/move.hpp>
#include <srook/utility/noncopyable.hpp>
#include <srook/utility/exchange.hpp>
#include <type_traits>
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
# define CJUNCT srook::type_traits::detail::Land
# define DJUNCT srook::type_traits::detail::Lor
#else
# define CJUNCT srook::type_traits::detail::Land_2
# define DJUNCT srook::type_traits::detail::Lor_2
#endif
namespace srook {
namespace scope {
namespace detail {
template <class T>
struct is_nothrow_movable
: bool_constant<CJUNCT<std::is_nothrow_move_constructible<T>, std::is_nothrow_move_assignable<T> >::value> {
};
} // namespace detail
template <class R, class D>
class SROOK_ATTRIBUTE_TEMPLATE_VIS_DEFAULT unique_resource : noncopyable<unique_resource<R, D> > {
SROOK_STATIC_ASSERT((DJUNCT<std::is_nothrow_move_constructible<R>, srook::is_copy_constructible<R> >::value),
"resource must be nothrow_move_constructible or copy_consturcitble");
SROOK_STATIC_ASSERT((DJUNCT<std::is_nothrow_move_constructible<D>, srook::is_copy_constructible<D> >::value),
"deleter must be nothrow_move_constructible or copy_consturcitble");
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
static SROOK_CONSTEXPR bool
is_nothrow_delete_v = noexcept(declval<D&>()(declval<R&>())),
is_nothrow_swappable_v = is_nothrow_delete_v and CJUNCT<detail::is_nothrow_movable<R>, detail::is_nothrow_movable<D> >::value;
#endif
unique_resource& operator=(const unique_resource&) SROOK_EQ_DELETE
unique_resource(const unique_resource&) SROOK_EQ_DELETE
public:
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
template <class RR, class DD, REQUIRES(CJUNCT<is_constructible<R, RR>, is_constructible<D, DD> >::value)>
SROOK_ATTRIBUTE_INLINE_VISIBILITY explicit
unique_resource(RR&& r, DD&& d)
: resource(srook::forward<RR>(r)), deleter(srook::forward<DD>(d))
{}
#else
template <class RR, class DD>
SROOK_ATTRIBUTE_INLINE_VISIBILITY explicit
unique_resource(utility::cxx03::move_tag<RR> r, utility::cxx03::move_tag<DD> d,
REQUIRES(CJUNCT<is_constructible<R, RR>, is_constructible<D, DD> >::value) = SROOK_NULLPTR_T())
: resource(r.get()), deleter(d.get()), execute_on_destruction(true)
{}
template <class RR, class DD>
SROOK_ATTRIBUTE_INLINE_VISIBILITY explicit
unique_resource(const RR& r, const DD& d,
REQUIRES(CJUNCT<is_constructible<R, RR>, is_constructible<D, DD> >::value) = SROOK_NULLPTR_T())
: resource(r), deleter(d), execute_on_destruction(true)
{}
#endif
SROOK_ATTRIBUTE_INLINE_VISIBILITY
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
unique_resource(unique_resource&& rhs)
: resource(srook::move(rhs.resource)),
deleter(srook::move(rhs.deleter)),
execute_on_destruction(exchange(rhs.execute_on_destruction, false))
#else
unique_resource(utility::cxx03::move_tag<unique_resource> rhs)
: resource(rhs.get().resource),
deleter(rhs.get().deleter),
execute_on_destruction(exchange(rhs.get().execute_on_destruction, false))
#endif
{}
SROOK_ATTRIBUTE_INLINE_VISIBILITY
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
unique_resource& operator=(unique_resource&& rhs)
#else
unique_resource& operator=(utility::cxx03::move_tag<unique_resource> rhs)
#endif
SROOK_NOEXCEPT((is_nothrow_delete_v and CJUNCT<std::is_nothrow_move_assignable<R>, std::is_nothrow_move_assignable<D> >::value))
{
SROOK_STATIC_ASSERT((DJUNCT<std::is_nothrow_move_assignable<R>, is_copy_assignable<R> >::value),
"The resource must be nothrow-move assignable, or copy assignable");
SROOK_STATIC_ASSERT((DJUNCT<std::is_nothrow_move_assignable<D>, is_copy_assignable<R> >::value),
"The resource must be nothrow-move assignable, or copy assignable");
if (&rhs == this) return *this;
reset();
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
deleter = srook::move(rhs.deleter);
resource = srook::move(rhs.resource);
execute_on_destruction = exchange(rhs.execute_on_destruction, false);
#else
deleter = rhs.get().deleter;
resource = rhs.get().resource;
execute_on_destruction = exchange(rhs.get().execute_on_destruction, false);
#endif
return *this;
}
SROOK_ATTRIBUTE_INLINE_VISIBILITY
~unique_resource()
{
reset();
}
void swap(unique_resource& other)
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
SROOK_NOEXCEPT(is_nothrow_swappable_v)
#endif
{
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
SROOK_IF_CONSTEXPR(is_nothrow_swappable_v) {
using std::swap;
swap(execute_on_destruction, other.execute_on_destruction);
swap(resource, other.resource);
swap(deleter, other.deleter);
} else {
#endif
unique_resource tmp = srook::move(*this);
*this = srook::move(other);
other = srook::move(tmp);
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
}
#endif
}
void reset()
SROOK_NOEXCEPT(is_nothrow_delete_v)
{
if (execute_on_destruction) {
execute_on_destruction = false;
deleter(resource);
}
}
template <class RR>
void reset(RR& r)
SROOK_NOEXCEPT(is_nothrow_delete_v)
{
reset();
resource = srook::move(r);
execute_on_destruction = true;
release();
}
SROOK_FORCE_INLINE
R release() SROOK_NOEXCEPT_TRUE
{
execute_on_destruction = false;
return get();
}
SROOK_FORCE_INLINE
const R& get() const SROOK_NOEXCEPT_TRUE
{
return resource;
}
SROOK_FORCE_INLINE
R operator->() const SROOK_NOEXCEPT_TRUE
{
return resource;
}
SROOK_FORCE_INLINE
typename std::add_lvalue_reference<typename srook::remove_pointer<R>::type>::type
operator*() const SROOK_NOEXCEPT_TRUE
{
return resource;
}
private:
R resource;
D deleter;
bool execute_on_destruction
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
= true
#endif
;
};
template <class R, class D>
unique_resource<typename decay<R>::type, typename decay<D>::type>
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
make_unique_resource(R&& r, D&& d)
#else
make_unique_resource(utility::cxx03::move_tag<R> r, utility::cxx03::move_tag<D> d)
#endif
SROOK_NOEXCEPT((is_nothrow_constructible<unique_resource<typename decay<R>::type, typename decay<D>::type>, R, D>::value))
{
return unique_resource<typename decay<R>::type, typename decay<D>::type>(srook::forward<R>(r), srook::forward<D>(d));
}
template <class R, class D>
unique_resource<R, typename remove_reference<D>::type>
make_unique_resource(std::reference_wrapper<R> r,
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS11_CONSTANT
D&& d
#else
utility::cxx03::move_tag<D> d
#endif
)
SROOK_NOEXCEPT((is_nothrow_constructible<unique_resource<R, typename remove_reference<D>::type>, decltype(r.get()), declval<D>()>::value))
{
return unique_resource<R, typename srook::remove_reference<D>::type>(r.get(), srook::forward<D>(d));
}
#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS17_CONSTANT
template <class R, class D>
unique_resource(R&& r, D&& d)
-> unique_resource<typename decay<R>::type, typename decay<D>::type>;
template <class R, class D>
unique_resource(std::reference_wrapper<R> r, D&& d)
-> unique_resource<R&, typename decay<D>::type>;
#endif
} // namespace scope
using scope::make_unique_resource;
using scope::unique_resource;
} // namespace srook
# undef CJUNCT
# undef DJUNCT
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/wrench_menu_model.h"
#include <algorithm>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/defaults.h"
#include "chrome/browser/page_menu_model.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/sync_ui_util.h"
#include "chrome/browser/upgrade_detector.h"
#include "chrome/common/chrome_switches.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
////////////////////////////////////////////////////////////////////////////////
// ToolsMenuModel
ToolsMenuModel::ToolsMenuModel(menus::SimpleMenuModel::Delegate* delegate,
Browser* browser)
: SimpleMenuModel(delegate) {
Build(browser);
}
ToolsMenuModel::~ToolsMenuModel() {}
void ToolsMenuModel::Build(Browser* browser) {
AddCheckItemWithStringId(IDC_SHOW_BOOKMARK_BAR, IDS_SHOW_BOOKMARK_BAR);
AddSeparator();
AddItemWithStringId(IDC_MANAGE_EXTENSIONS, IDS_SHOW_EXTENSIONS);
AddItemWithStringId(IDC_TASK_MANAGER, IDS_TASK_MANAGER);
AddItemWithStringId(IDC_CLEAR_BROWSING_DATA, IDS_CLEAR_BROWSING_DATA);
AddSeparator();
encoding_menu_model_.reset(new EncodingMenuModel(browser));
AddSubMenuWithStringId(IDC_ENCODING_MENU, IDS_ENCODING_MENU,
encoding_menu_model_.get());
AddItemWithStringId(IDC_VIEW_SOURCE, IDS_VIEW_SOURCE);
if (g_browser_process->have_inspector_files()) {
AddItemWithStringId(IDC_DEV_TOOLS, IDS_DEV_TOOLS);
AddItemWithStringId(IDC_DEV_TOOLS_CONSOLE, IDS_DEV_TOOLS_CONSOLE);
}
}
////////////////////////////////////////////////////////////////////////////////
// WrenchMenuModel
WrenchMenuModel::WrenchMenuModel(menus::SimpleMenuModel::Delegate* delegate,
Browser* browser)
: menus::SimpleMenuModel(delegate),
browser_(browser) {
Build();
}
WrenchMenuModel::~WrenchMenuModel() {
}
bool WrenchMenuModel::IsLabelDynamicAt(int index) const {
return IsDynamicItem(index) || SimpleMenuModel::IsLabelDynamicAt(index);
}
string16 WrenchMenuModel::GetLabelAt(int index) const {
if (!IsDynamicItem(index))
return SimpleMenuModel::GetLabelAt(index);
int command_id = GetCommandIdAt(index);
switch (command_id) {
case IDC_ABOUT:
return GetAboutEntryMenuLabel();
case IDC_SYNC_BOOKMARKS:
return GetSyncMenuLabel();
default:
NOTREACHED();
return string16();
}
}
bool WrenchMenuModel::GetIconAt(int index, SkBitmap* icon) const {
if (GetCommandIdAt(index) == IDC_ABOUT &&
Singleton<UpgradeDetector>::get()->notify_upgrade()) {
// Show the exclamation point next to the menu item.
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
*icon = *rb.GetBitmapNamed(IDR_UPDATE_AVAILABLE);
return true;
}
return false;
}
void WrenchMenuModel::Build() {
AddItemWithStringId(IDC_NEW_TAB, IDS_NEW_TAB);
AddItemWithStringId(IDC_NEW_WINDOW, IDS_NEW_WINDOW);
AddItemWithStringId(IDC_NEW_INCOGNITO_WINDOW, IDS_NEW_INCOGNITO_WINDOW);
AddSeparator();
CreateCutCopyPaste();
AddSeparator();
CreateZoomFullscreen();
AddSeparator();
AddItemWithStringId(IDC_SAVE_PAGE, IDS_SAVE_PAGE);
AddItemWithStringId(IDC_FIND, IDS_FIND);
AddItemWithStringId(IDC_PRINT, IDS_PRINT);
tools_menu_model_.reset(new ToolsMenuModel(delegate(), browser_));
AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_TOOLS_MENU,
tools_menu_model_.get());
AddSeparator();
AddItemWithStringId(IDC_SHOW_BOOKMARK_MANAGER, IDS_BOOKMARK_MANAGER);
AddItemWithStringId(IDC_SHOW_HISTORY, IDS_SHOW_HISTORY);
AddItemWithStringId(IDC_SHOW_DOWNLOADS, IDS_SHOW_DOWNLOADS);
AddSeparator();
#if defined(OS_MACOSX)
AddItemWithStringId(IDC_OPTIONS, IDS_PREFERENCES_MAC);
#else
AddItemWithStringId(IDC_OPTIONS, IDS_OPTIONS);
#endif
AddItemWithStringId(IDC_HELP_PAGE, IDS_HELP_PAGE);
if (browser_defaults::kShowExitMenuItem) {
AddSeparator();
#if defined(OS_CHROMEOS)
AddItemWithStringId(IDC_EXIT, IDS_SIGN_OUT);
#else
AddItemWithStringId(IDC_EXIT, IDS_EXIT);
#endif
}
}
void WrenchMenuModel::CreateCutCopyPaste() {
AddItemWithStringId(IDC_CUT, IDS_CUT);
AddItemWithStringId(IDC_COPY, IDS_COPY);
AddItemWithStringId(IDC_PASTE, IDS_PASTE);
}
void WrenchMenuModel::CreateZoomFullscreen() {
AddItemWithStringId(IDC_ZOOM_PLUS, IDS_ZOOM_PLUS);
AddItemWithStringId(IDC_ZOOM_MINUS, IDS_ZOOM_MINUS);
AddItemWithStringId(IDC_FULLSCREEN, IDS_FULLSCREEN);
}
string16 WrenchMenuModel::GetSyncMenuLabel() const {
return sync_ui_util::GetSyncMenuLabel(
browser_->profile()->GetOriginalProfile()->GetProfileSyncService());
}
string16 WrenchMenuModel::GetAboutEntryMenuLabel() const {
if (Singleton<UpgradeDetector>::get()->notify_upgrade()) {
return l10n_util::GetStringFUTF16(
IDS_UPDATE_NOW, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
}
return l10n_util::GetStringFUTF16(
IDS_ABOUT, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
}
bool WrenchMenuModel::IsDynamicItem(int index) const {
int command_id = GetCommandIdAt(index);
return command_id == IDC_SYNC_BOOKMARKS ||
command_id == IDC_ABOUT;
}
<commit_msg>Windows: Show the "About" menu item on the new Wrench menu.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/wrench_menu_model.h"
#include <algorithm>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/defaults.h"
#include "chrome/browser/page_menu_model.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/sync_ui_util.h"
#include "chrome/browser/upgrade_detector.h"
#include "chrome/common/chrome_switches.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
////////////////////////////////////////////////////////////////////////////////
// ToolsMenuModel
ToolsMenuModel::ToolsMenuModel(menus::SimpleMenuModel::Delegate* delegate,
Browser* browser)
: SimpleMenuModel(delegate) {
Build(browser);
}
ToolsMenuModel::~ToolsMenuModel() {}
void ToolsMenuModel::Build(Browser* browser) {
AddCheckItemWithStringId(IDC_SHOW_BOOKMARK_BAR, IDS_SHOW_BOOKMARK_BAR);
AddSeparator();
AddItemWithStringId(IDC_MANAGE_EXTENSIONS, IDS_SHOW_EXTENSIONS);
AddItemWithStringId(IDC_TASK_MANAGER, IDS_TASK_MANAGER);
AddItemWithStringId(IDC_CLEAR_BROWSING_DATA, IDS_CLEAR_BROWSING_DATA);
AddSeparator();
encoding_menu_model_.reset(new EncodingMenuModel(browser));
AddSubMenuWithStringId(IDC_ENCODING_MENU, IDS_ENCODING_MENU,
encoding_menu_model_.get());
AddItemWithStringId(IDC_VIEW_SOURCE, IDS_VIEW_SOURCE);
if (g_browser_process->have_inspector_files()) {
AddItemWithStringId(IDC_DEV_TOOLS, IDS_DEV_TOOLS);
AddItemWithStringId(IDC_DEV_TOOLS_CONSOLE, IDS_DEV_TOOLS_CONSOLE);
}
}
////////////////////////////////////////////////////////////////////////////////
// WrenchMenuModel
WrenchMenuModel::WrenchMenuModel(menus::SimpleMenuModel::Delegate* delegate,
Browser* browser)
: menus::SimpleMenuModel(delegate),
browser_(browser) {
Build();
}
WrenchMenuModel::~WrenchMenuModel() {
}
bool WrenchMenuModel::IsLabelDynamicAt(int index) const {
return IsDynamicItem(index) || SimpleMenuModel::IsLabelDynamicAt(index);
}
string16 WrenchMenuModel::GetLabelAt(int index) const {
if (!IsDynamicItem(index))
return SimpleMenuModel::GetLabelAt(index);
int command_id = GetCommandIdAt(index);
switch (command_id) {
case IDC_ABOUT:
return GetAboutEntryMenuLabel();
case IDC_SYNC_BOOKMARKS:
return GetSyncMenuLabel();
default:
NOTREACHED();
return string16();
}
}
bool WrenchMenuModel::GetIconAt(int index, SkBitmap* icon) const {
if (GetCommandIdAt(index) == IDC_ABOUT &&
Singleton<UpgradeDetector>::get()->notify_upgrade()) {
// Show the exclamation point next to the menu item.
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
*icon = *rb.GetBitmapNamed(IDR_UPDATE_AVAILABLE);
return true;
}
return false;
}
void WrenchMenuModel::Build() {
AddItemWithStringId(IDC_NEW_TAB, IDS_NEW_TAB);
AddItemWithStringId(IDC_NEW_WINDOW, IDS_NEW_WINDOW);
AddItemWithStringId(IDC_NEW_INCOGNITO_WINDOW, IDS_NEW_INCOGNITO_WINDOW);
AddSeparator();
CreateCutCopyPaste();
AddSeparator();
CreateZoomFullscreen();
AddSeparator();
AddItemWithStringId(IDC_SAVE_PAGE, IDS_SAVE_PAGE);
AddItemWithStringId(IDC_FIND, IDS_FIND);
AddItemWithStringId(IDC_PRINT, IDS_PRINT);
tools_menu_model_.reset(new ToolsMenuModel(delegate(), browser_));
AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_TOOLS_MENU,
tools_menu_model_.get());
AddSeparator();
AddItemWithStringId(IDC_SHOW_BOOKMARK_MANAGER, IDS_BOOKMARK_MANAGER);
AddItemWithStringId(IDC_SHOW_HISTORY, IDS_SHOW_HISTORY);
AddItemWithStringId(IDC_SHOW_DOWNLOADS, IDS_SHOW_DOWNLOADS);
AddSeparator();
#if defined(OS_MACOSX)
AddItemWithStringId(IDC_OPTIONS, IDS_PREFERENCES_MAC);
#else
AddItemWithStringId(IDC_OPTIONS, IDS_OPTIONS);
#endif
if (browser_defaults::kShowAboutMenuItem) {
AddItem(IDC_ABOUT,
l10n_util::GetStringFUTF16(
IDS_ABOUT,
l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));
}
AddItemWithStringId(IDC_HELP_PAGE, IDS_HELP_PAGE);
if (browser_defaults::kShowExitMenuItem) {
AddSeparator();
#if defined(OS_CHROMEOS)
AddItemWithStringId(IDC_EXIT, IDS_SIGN_OUT);
#else
AddItemWithStringId(IDC_EXIT, IDS_EXIT);
#endif
}
}
void WrenchMenuModel::CreateCutCopyPaste() {
AddItemWithStringId(IDC_CUT, IDS_CUT);
AddItemWithStringId(IDC_COPY, IDS_COPY);
AddItemWithStringId(IDC_PASTE, IDS_PASTE);
}
void WrenchMenuModel::CreateZoomFullscreen() {
AddItemWithStringId(IDC_ZOOM_PLUS, IDS_ZOOM_PLUS);
AddItemWithStringId(IDC_ZOOM_MINUS, IDS_ZOOM_MINUS);
AddItemWithStringId(IDC_FULLSCREEN, IDS_FULLSCREEN);
}
string16 WrenchMenuModel::GetSyncMenuLabel() const {
return sync_ui_util::GetSyncMenuLabel(
browser_->profile()->GetOriginalProfile()->GetProfileSyncService());
}
string16 WrenchMenuModel::GetAboutEntryMenuLabel() const {
if (Singleton<UpgradeDetector>::get()->notify_upgrade()) {
return l10n_util::GetStringFUTF16(
IDS_UPDATE_NOW, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
}
return l10n_util::GetStringFUTF16(
IDS_ABOUT, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
}
bool WrenchMenuModel::IsDynamicItem(int index) const {
int command_id = GetCommandIdAt(index);
return command_id == IDC_SYNC_BOOKMARKS ||
command_id == IDC_ABOUT;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/child_process_host.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/singleton.h"
#include "base/string_util.h"
#include "base/waitable_event.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/plugin_messages.h"
#include "chrome/common/process_watcher.h"
#include "chrome/common/result_codes.h"
#include "chrome/installer/util/google_update_settings.h"
#if defined(OS_LINUX)
#include "base/linux_util.h"
#endif // OS_LINUX
#if defined(OS_POSIX)
// This is defined in chrome/browser/google_update_settings_posix.cc. It's the
// static string containing the user's unique GUID. We send this in the crash
// report.
namespace google_update {
extern std::string posix_guid;
} // namespace google_update
#endif // OS_POSIX
namespace {
typedef std::list<ChildProcessHost*> ChildProcessList;
// The NotificationTask is used to notify about plugin process connection/
// disconnection. It is needed because the notifications in the
// NotificationService must happen in the main thread.
class ChildNotificationTask : public Task {
public:
ChildNotificationTask(
NotificationType notification_type, ChildProcessInfo* info)
: notification_type_(notification_type), info_(*info) { }
virtual void Run() {
NotificationService::current()->
Notify(notification_type_, NotificationService::AllSources(),
Details<ChildProcessInfo>(&info_));
}
private:
NotificationType notification_type_;
ChildProcessInfo info_;
};
} // namespace
ChildProcessHost::ChildProcessHost(
ProcessType type, ResourceDispatcherHost* resource_dispatcher_host)
: Receiver(type, -1),
ALLOW_THIS_IN_INITIALIZER_LIST(listener_(this)),
resource_dispatcher_host_(resource_dispatcher_host),
opening_channel_(false) {
Singleton<ChildProcessList>::get()->push_back(this);
}
ChildProcessHost::~ChildProcessHost() {
Singleton<ChildProcessList>::get()->remove(this);
resource_dispatcher_host_->CancelRequestsForProcess(id());
if (handle())
ProcessWatcher::EnsureProcessTerminated(handle());
}
// static
FilePath ChildProcessHost::GetChildPath() {
FilePath child_path;
child_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath(
switches::kBrowserSubprocessPath);
if (!child_path.empty())
return child_path;
#if defined(OS_LINUX)
// Use /proc/self/exe rather than our known binary path so updates
// can't swap out the binary from underneath us.
child_path = FilePath("/proc/self/exe");
#elif defined(OS_MACOSX)
// On the Mac, the child executable lives at a predefined location within
// the app bundle's versioned directory.
child_path = chrome::GetVersionedDirectory().
Append(chrome::kHelperProcessExecutablePath);
#else
// On most platforms, the child executable is the same as the current
// executable.
PathService::Get(base::FILE_EXE, &child_path);
#endif
return child_path;
}
// static
void ChildProcessHost::SetCrashReporterCommandLine(CommandLine* command_line) {
#if defined(USE_LINUX_BREAKPAD)
const bool unattended = (getenv("CHROME_HEADLESS") != NULL);
if (unattended || GoogleUpdateSettings::GetCollectStatsConsent()) {
command_line->AppendSwitchWithValue(switches::kEnableCrashReporter,
ASCIIToWide(google_update::posix_guid +
"," +
base::GetLinuxDistro()));
}
#elif defined(OS_MACOSX)
if (GoogleUpdateSettings::GetCollectStatsConsent())
command_line->AppendSwitchWithValue(switches::kEnableCrashReporter,
ASCIIToWide(google_update::posix_guid));
#endif // OS_MACOSX
}
bool ChildProcessHost::CreateChannel() {
channel_id_ = GenerateRandomChannelID(this);
channel_.reset(new IPC::Channel(
channel_id_, IPC::Channel::MODE_SERVER, &listener_));
if (!channel_->Connect())
return false;
opening_channel_ = true;
return true;
}
void ChildProcessHost::SetHandle(base::ProcessHandle process) {
DCHECK(!handle());
set_handle(process);
}
void ChildProcessHost::InstanceCreated() {
Notify(NotificationType::CHILD_INSTANCE_CREATED);
}
bool ChildProcessHost::Send(IPC::Message* msg) {
if (!channel_.get()) {
delete msg;
return false;
}
return channel_->Send(msg);
}
void ChildProcessHost::Notify(NotificationType type) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE, new ChildNotificationTask(type, this));
}
void ChildProcessHost::OnChildDied() {
DCHECK(handle());
bool did_crash = base::DidProcessCrash(NULL, handle());
if (did_crash) {
// Report that this child process crashed.
Notify(NotificationType::CHILD_PROCESS_CRASHED);
}
// Notify in the main loop of the disconnection.
Notify(NotificationType::CHILD_PROCESS_HOST_DISCONNECTED);
// On POSIX, once we've called DidProcessCrash, handle() is no longer
// valid. Ensure the destructor doesn't try to use it.
set_handle(base::kNullProcessHandle);
delete this;
}
ChildProcessHost::ListenerHook::ListenerHook(ChildProcessHost* host)
: host_(host) {
}
void ChildProcessHost::ListenerHook::OnMessageReceived(
const IPC::Message& msg) {
#ifdef IPC_MESSAGE_LOG_ENABLED
IPC::Logging* logger = IPC::Logging::current();
if (msg.type() == IPC_LOGGING_ID) {
logger->OnReceivedLoggingMessage(msg);
return;
}
if (logger->Enabled())
logger->OnPreDispatchMessage(msg);
#endif
bool msg_is_ok = true;
bool handled = host_->resource_dispatcher_host_->OnMessageReceived(
msg, host_, &msg_is_ok);
if (!handled) {
if (msg.type() == PluginProcessHostMsg_ShutdownRequest::ID) {
// Must remove the process from the list now, in case it gets used for a
// new instance before our watcher tells us that the process terminated.
Singleton<ChildProcessList>::get()->remove(host_);
if (host_->CanShutdown())
host_->Send(new PluginProcessMsg_Shutdown());
} else {
host_->OnMessageReceived(msg);
}
}
if (!msg_is_ok)
base::KillProcess(host_->handle(), ResultCodes::KILLED_BAD_MESSAGE, false);
#ifdef IPC_MESSAGE_LOG_ENABLED
if (logger->Enabled())
logger->OnPostDispatchMessage(msg, host_->channel_id_);
#endif
}
void ChildProcessHost::ListenerHook::OnChannelConnected(int32 peer_pid) {
host_->opening_channel_ = false;
host_->OnChannelConnected(peer_pid);
#if defined(IPC_MESSAGE_LOG_ENABLED)
bool enabled = IPC::Logging::current()->Enabled();
host_->Send(new PluginProcessMsg_SetIPCLoggingEnabled(enabled));
#endif
host_->Send(new PluginProcessMsg_AskBeforeShutdown());
// Notify in the main loop of the connection.
host_->Notify(NotificationType::CHILD_PROCESS_HOST_CONNECTED);
}
void ChildProcessHost::ListenerHook::OnChannelError() {
host_->opening_channel_ = false;
host_->OnChannelError();
// This will delete host_, which will also destroy this!
host_->OnChildDied();
}
ChildProcessHost::Iterator::Iterator()
: all_(true), type_(UNKNOWN_PROCESS) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)) <<
"ChildProcessInfo::Iterator must be used on the IO thread.";
iterator_ = Singleton<ChildProcessList>::get()->begin();
}
ChildProcessHost::Iterator::Iterator(ProcessType type)
: all_(false), type_(type) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)) <<
"ChildProcessInfo::Iterator must be used on the IO thread.";
iterator_ = Singleton<ChildProcessList>::get()->begin();
if (!Done() && (*iterator_)->type() != type_)
++(*this);
}
ChildProcessHost* ChildProcessHost::Iterator::operator++() {
do {
++iterator_;
if (Done())
break;
if (!all_ && (*iterator_)->type() != type_)
continue;
return *iterator_;
} while (true);
return NULL;
}
bool ChildProcessHost::Iterator::Done() {
return iterator_ == Singleton<ChildProcessList>::get()->end();
}
<commit_msg>Revert "linux: use /proc/self/exe when exec'ing ourselves"<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/child_process_host.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/singleton.h"
#include "base/string_util.h"
#include "base/waitable_event.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/plugin_messages.h"
#include "chrome/common/process_watcher.h"
#include "chrome/common/result_codes.h"
#include "chrome/installer/util/google_update_settings.h"
#if defined(OS_LINUX)
#include "base/linux_util.h"
#endif // OS_LINUX
#if defined(OS_POSIX)
// This is defined in chrome/browser/google_update_settings_posix.cc. It's the
// static string containing the user's unique GUID. We send this in the crash
// report.
namespace google_update {
extern std::string posix_guid;
} // namespace google_update
#endif // OS_POSIX
namespace {
typedef std::list<ChildProcessHost*> ChildProcessList;
// The NotificationTask is used to notify about plugin process connection/
// disconnection. It is needed because the notifications in the
// NotificationService must happen in the main thread.
class ChildNotificationTask : public Task {
public:
ChildNotificationTask(
NotificationType notification_type, ChildProcessInfo* info)
: notification_type_(notification_type), info_(*info) { }
virtual void Run() {
NotificationService::current()->
Notify(notification_type_, NotificationService::AllSources(),
Details<ChildProcessInfo>(&info_));
}
private:
NotificationType notification_type_;
ChildProcessInfo info_;
};
} // namespace
ChildProcessHost::ChildProcessHost(
ProcessType type, ResourceDispatcherHost* resource_dispatcher_host)
: Receiver(type, -1),
ALLOW_THIS_IN_INITIALIZER_LIST(listener_(this)),
resource_dispatcher_host_(resource_dispatcher_host),
opening_channel_(false) {
Singleton<ChildProcessList>::get()->push_back(this);
}
ChildProcessHost::~ChildProcessHost() {
Singleton<ChildProcessList>::get()->remove(this);
resource_dispatcher_host_->CancelRequestsForProcess(id());
if (handle())
ProcessWatcher::EnsureProcessTerminated(handle());
}
// static
FilePath ChildProcessHost::GetChildPath() {
FilePath child_path;
child_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath(
switches::kBrowserSubprocessPath);
if (!child_path.empty())
return child_path;
#if !defined(OS_MACOSX)
// On most platforms, the child executable is the same as the current
// executable.
PathService::Get(base::FILE_EXE, &child_path);
#else
// On the Mac, the child executable lives at a predefined location within
// the app bundle's versioned directory.
child_path = chrome::GetVersionedDirectory().
Append(chrome::kHelperProcessExecutablePath);
#endif // OS_MACOSX
return child_path;
}
// static
void ChildProcessHost::SetCrashReporterCommandLine(CommandLine* command_line) {
#if defined(USE_LINUX_BREAKPAD)
const bool unattended = (getenv("CHROME_HEADLESS") != NULL);
if (unattended || GoogleUpdateSettings::GetCollectStatsConsent()) {
command_line->AppendSwitchWithValue(switches::kEnableCrashReporter,
ASCIIToWide(google_update::posix_guid +
"," +
base::GetLinuxDistro()));
}
#elif defined(OS_MACOSX)
if (GoogleUpdateSettings::GetCollectStatsConsent())
command_line->AppendSwitchWithValue(switches::kEnableCrashReporter,
ASCIIToWide(google_update::posix_guid));
#endif // OS_MACOSX
}
bool ChildProcessHost::CreateChannel() {
channel_id_ = GenerateRandomChannelID(this);
channel_.reset(new IPC::Channel(
channel_id_, IPC::Channel::MODE_SERVER, &listener_));
if (!channel_->Connect())
return false;
opening_channel_ = true;
return true;
}
void ChildProcessHost::SetHandle(base::ProcessHandle process) {
DCHECK(!handle());
set_handle(process);
}
void ChildProcessHost::InstanceCreated() {
Notify(NotificationType::CHILD_INSTANCE_CREATED);
}
bool ChildProcessHost::Send(IPC::Message* msg) {
if (!channel_.get()) {
delete msg;
return false;
}
return channel_->Send(msg);
}
void ChildProcessHost::Notify(NotificationType type) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE, new ChildNotificationTask(type, this));
}
void ChildProcessHost::OnChildDied() {
DCHECK(handle());
bool did_crash = base::DidProcessCrash(NULL, handle());
if (did_crash) {
// Report that this child process crashed.
Notify(NotificationType::CHILD_PROCESS_CRASHED);
}
// Notify in the main loop of the disconnection.
Notify(NotificationType::CHILD_PROCESS_HOST_DISCONNECTED);
// On POSIX, once we've called DidProcessCrash, handle() is no longer
// valid. Ensure the destructor doesn't try to use it.
set_handle(base::kNullProcessHandle);
delete this;
}
ChildProcessHost::ListenerHook::ListenerHook(ChildProcessHost* host)
: host_(host) {
}
void ChildProcessHost::ListenerHook::OnMessageReceived(
const IPC::Message& msg) {
#ifdef IPC_MESSAGE_LOG_ENABLED
IPC::Logging* logger = IPC::Logging::current();
if (msg.type() == IPC_LOGGING_ID) {
logger->OnReceivedLoggingMessage(msg);
return;
}
if (logger->Enabled())
logger->OnPreDispatchMessage(msg);
#endif
bool msg_is_ok = true;
bool handled = host_->resource_dispatcher_host_->OnMessageReceived(
msg, host_, &msg_is_ok);
if (!handled) {
if (msg.type() == PluginProcessHostMsg_ShutdownRequest::ID) {
// Must remove the process from the list now, in case it gets used for a
// new instance before our watcher tells us that the process terminated.
Singleton<ChildProcessList>::get()->remove(host_);
if (host_->CanShutdown())
host_->Send(new PluginProcessMsg_Shutdown());
} else {
host_->OnMessageReceived(msg);
}
}
if (!msg_is_ok)
base::KillProcess(host_->handle(), ResultCodes::KILLED_BAD_MESSAGE, false);
#ifdef IPC_MESSAGE_LOG_ENABLED
if (logger->Enabled())
logger->OnPostDispatchMessage(msg, host_->channel_id_);
#endif
}
void ChildProcessHost::ListenerHook::OnChannelConnected(int32 peer_pid) {
host_->opening_channel_ = false;
host_->OnChannelConnected(peer_pid);
#if defined(IPC_MESSAGE_LOG_ENABLED)
bool enabled = IPC::Logging::current()->Enabled();
host_->Send(new PluginProcessMsg_SetIPCLoggingEnabled(enabled));
#endif
host_->Send(new PluginProcessMsg_AskBeforeShutdown());
// Notify in the main loop of the connection.
host_->Notify(NotificationType::CHILD_PROCESS_HOST_CONNECTED);
}
void ChildProcessHost::ListenerHook::OnChannelError() {
host_->opening_channel_ = false;
host_->OnChannelError();
// This will delete host_, which will also destroy this!
host_->OnChildDied();
}
ChildProcessHost::Iterator::Iterator()
: all_(true), type_(UNKNOWN_PROCESS) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)) <<
"ChildProcessInfo::Iterator must be used on the IO thread.";
iterator_ = Singleton<ChildProcessList>::get()->begin();
}
ChildProcessHost::Iterator::Iterator(ProcessType type)
: all_(false), type_(type) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)) <<
"ChildProcessInfo::Iterator must be used on the IO thread.";
iterator_ = Singleton<ChildProcessList>::get()->begin();
if (!Done() && (*iterator_)->type() != type_)
++(*this);
}
ChildProcessHost* ChildProcessHost::Iterator::operator++() {
do {
++iterator_;
if (Done())
break;
if (!all_ && (*iterator_)->type() != type_)
continue;
return *iterator_;
} while (true);
return NULL;
}
bool ChildProcessHost::Iterator::Done() {
return iterator_ == Singleton<ChildProcessList>::get()->end();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <TDatabasePDG.h>
#include <TRandom.h>
#include <TF1.h>
#include <TStopwatch.h>
#include <AliESDtrackCuts.h>
#include <AliESDtrack.h>
#include <TFile.h>
#include <TTree.h>
#include <TRandom3.h>
#include "AliToyMCEvent.h"
#include "AliToyMCEventGeneratorSimple.h"
ClassImp(AliToyMCEventGeneratorSimple);
AliToyMCEventGeneratorSimple::AliToyMCEventGeneratorSimple()
:AliToyMCEventGenerator()
,fVertexMean(0.)
,fVertexSigma(7.)
,fNtracks(20)
,fInputFileNameESD("")
,fESDCuts(0x0)
{
//
}
//________________________________________________________________
AliToyMCEventGeneratorSimple::AliToyMCEventGeneratorSimple(const AliToyMCEventGeneratorSimple &gen)
:AliToyMCEventGenerator(gen)
,fVertexMean(gen.fVertexMean)
,fVertexSigma(gen.fVertexSigma)
,fNtracks(gen.fNtracks)
,fInputFileNameESD(gen.fInputFileNameESD)
,fESDCuts(gen.fESDCuts)
{
}
//________________________________________________________________
AliToyMCEventGeneratorSimple::~AliToyMCEventGeneratorSimple()
{
}
//________________________________________________________________
AliToyMCEventGeneratorSimple& AliToyMCEventGeneratorSimple::operator = (const AliToyMCEventGeneratorSimple &gen)
{
//assignment operator
if (&gen == this) return *this;
new (this) AliToyMCEventGeneratorSimple(gen);
return *this;
}
//________________________________________________________________
void AliToyMCEventGeneratorSimple::SetParametersSimple(Double_t vertexMean, Double_t vertexSigma) {
fVertexMean = vertexMean;
fVertexSigma = vertexSigma;
}
//________________________________________________________________
AliToyMCEvent* AliToyMCEventGeneratorSimple::Generate(Double_t time)
{
//
//
//
AliToyMCEvent *retEvent = new AliToyMCEvent();
retEvent->SetT0(time);
retEvent->SetX(0);
retEvent->SetX(0);
retEvent->SetZ(gRandom->Gaus(fVertexMean,fVertexSigma));
Double_t etaCuts=.9;
Double_t mass = TDatabasePDG::Instance()->GetParticle("pi+")->Mass();
TF1 fpt("fpt",Form("x*(1+(sqrt(x*x+%f^2)-%f)/([0]*[1]))^(-[0])",mass,mass),0.4,10);
fpt.SetParameters(7.24,0.120);
fpt.SetNpx(10000);
// Int_t nTracks = 400; //TODO: draw from experim dist
// Int_t nTracks = 20; //TODO: draw from experim dist
for(Int_t iTrack=0; iTrack<fNtracks; iTrack++){
Double_t phi = gRandom->Uniform(0.0, 2*TMath::Pi());
Double_t eta = gRandom->Uniform(-etaCuts, etaCuts);
Double_t pt = fpt.GetRandom(); // momentum for f1
Short_t sign=1;
if(gRandom->Rndm() < 0.5){
sign =1;
}else{
sign=-1;
}
Double_t theta = 2*TMath::ATan(TMath::Exp(-eta))-TMath::Pi()/2.;
Double_t pxyz[3];
pxyz[0]=pt*TMath::Cos(phi);
pxyz[1]=pt*TMath::Sin(phi);
pxyz[2]=pt*TMath::Tan(theta);
Double_t vertex[3]={0,0,retEvent->GetZ()};
Double_t cv[21]={0};
AliToyMCTrack *tempTrack = new AliToyMCTrack(vertex,pxyz,cv,sign);
Bool_t trackDist = DistortTrack(*tempTrack, time);
if(trackDist) retEvent->AddTrack(*tempTrack);
delete tempTrack;
}
return retEvent;
}
//________________________________________________________________
void AliToyMCEventGeneratorSimple::RunSimulation(const Int_t nevents/*=10*/, const Int_t ntracks/*=400*/)
{
//
// run simple simulation with equal event spacing
//
if (!ConnectOutputFile()) return;
//initialise the space charge. Should be done after the tree was set up
InitSpaceCharge();
fNtracks=ntracks;
Double_t eventTime=0.;
const Double_t eventSpacing=1./50e3; //50kHz equally spaced
TStopwatch s;
for (Int_t ievent=0; ievent<nevents; ++ievent){
printf("Generating event %3d (%.3g)\n",ievent,eventTime);
fEvent = Generate(eventTime);
FillTree();
delete fEvent;
fEvent=0x0;
eventTime+=eventSpacing;
}
s.Stop();
s.Print();
CloseOutputFile();
}
//________________________________________________________________
AliToyMCEvent* AliToyMCEventGeneratorSimple::GenerateESD(AliESDEvent &esdEvent, Double_t time) {
AliToyMCEvent *retEvent = new AliToyMCEvent();
retEvent->SetT0(time);
retEvent->SetX(esdEvent.GetPrimaryVertex()->GetX());
retEvent->SetY(esdEvent.GetPrimaryVertex()->GetY());
retEvent->SetZ(esdEvent.GetPrimaryVertex()->GetZ());
if(!fNtracks) fNtracks = esdEvent.GetNumberOfTracks();
Int_t nUsedTracks = 0;
for(Int_t iTrack=0; iTrack<esdEvent.GetNumberOfTracks(); iTrack++){
AliESDtrack *part = esdEvent.GetTrack(iTrack);
if(!part) continue;
if (!fESDCuts->AcceptTrack(/*(AliESDtrack*)*/part))continue;
if(part->Pt() < 0.3) continue; //avoid tracks that fail to propagate through entire volume
Double_t pxyz[3];
pxyz[0]=part->Px();
pxyz[1]=part->Py();
pxyz[2]=part->Pz();
Double_t vertex[3]={retEvent->GetX(),retEvent->GetY(),retEvent->GetZ()};
Double_t cv[21]={0};
Int_t sign = part->Charge();
AliToyMCTrack *tempTrack = new AliToyMCTrack(vertex,pxyz,cv,sign);
Bool_t trackDist = DistortTrack(*tempTrack, time);
if(trackDist) {
retEvent->AddTrack(*tempTrack);
nUsedTracks++;
}
delete tempTrack;
if(nUsedTracks >= fNtracks) break;
}
return retEvent;
}
//________________________________________________________________
void AliToyMCEventGeneratorSimple::RunSimulationESD(const Int_t nevents/*=10*/, const Int_t ntracks/*=400*/)
{
//
// run simulation using esd input with equal event spacing
//
if (!ConnectOutputFile()) return;
TFile f(Form("%s%s",fInputFileNameESD.Data(),"#AliESDs.root"));
if(!f.IsOpen()) {
std::cout << "file "<<fInputFileNameESD.Data() <<" could not be opened" << std::endl;
return;
}
TTree* esdTree = (TTree*) f.Get("esdTree");
if(!esdTree) {
std::cout <<"no esdTree in file " << std::endl;
return;
}
InitSpaceCharge();
AliESDEvent* esdEvent = new AliESDEvent();
fNtracks = ntracks;
esdEvent->ReadFromTree(esdTree);
Double_t eventTime=0.;
const Double_t eventSpacing=1./50e3; //50kHz equally spaced
TStopwatch s;
Int_t nEvents = nevents;
fESDCuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kTRUE,1);
if(nevents>esdTree->GetEntries()) nEvents = esdTree->GetEntries();
Int_t nUsedEvents = 0;
for (Int_t ievent=0; ievent<esdTree->GetEntries(); ++ievent){
printf("Generating event %3d (%.3g)\n",nUsedEvents,eventTime);
esdTree->GetEvent(ievent);
if(esdEvent->GetNumberOfTracks()==0) {
std::cout << " tracks == 0" << std::endl;
continue;
}
fEvent = GenerateESD(*esdEvent, eventTime);
if(fEvent->GetNumberOfTracks() >=10) {
nUsedEvents++;
FillTree();
eventTime+=eventSpacing;
}
delete fEvent;
fEvent=0x0;
if(nUsedEvents>=nevents) break;
}
s.Stop();
s.Print();
CloseOutputFile();
}
//________________________________________________________________
void AliToyMCEventGeneratorSimple::RunSimulationBunchTrain(const Int_t nevents/*=10*/, const Int_t ntracks/*=400*/)
{
//
// run simple simulation with equal event spacing
//
//Parameters for bunc
const Double_t abortGap = 3e-6; //
const Double_t collFreq = 50e3;
const Double_t bSpacing = 50e-9; //bunch spacing
const Int_t nTrainBunches = 48;
const Int_t nTrains = 12;
const Double_t revFreq = 1.11e4; //revolution frequency
const Double_t collProb = collFreq/(nTrainBunches*nTrains*revFreq);
const Double_t trainLength = bSpacing*(nTrainBunches-1);
const Double_t totTrainLength = nTrains*trainLength;
const Double_t trainSpacing = (1./revFreq - abortGap - totTrainLength)/(nTrains-1);
Bool_t equalSpacing = kFALSE;
TRandom3 *rand = new TRandom3();
//rand->SetSeed();
if (!ConnectOutputFile()) return;
//initialise the space charge. Should be done after the tree was set up
InitSpaceCharge();
fNtracks=ntracks;
Double_t eventTime=0.;
const Double_t eventSpacing=1./50e3; //50kHz equally spaced
TStopwatch s;
Int_t nGeneratedEvents = 0;
Int_t bunchCounter = 0;
Int_t trainCounter = 0;
//for (Int_t ievent=0; ievent<nevents; ++ievent){
while (nGeneratedEvents<nevents){
// std::cout <<trainCounter << " " << bunchCounter << " "<< "eventTime " << eventTime << std::endl;
if(equalSpacing) {
printf("Generating event %3d (%.3g)\n",nGeneratedEvents,eventTime);
fEvent = Generate(eventTime);
nGeneratedEvents++;
FillTree();
delete fEvent;
fEvent=0x0;
eventTime+=1./collFreq;
}
else{
Int_t nCollsInCrossing = rand -> Poisson(collProb);
for(Int_t iColl = 0; iColl<nCollsInCrossing; iColl++){
printf("Generating event %3d (%.3g)\n",nGeneratedEvents,eventTime);
fEvent = Generate(eventTime);
nGeneratedEvents++;
FillTree();
delete fEvent;
fEvent=0x0;
}
bunchCounter++;
if(bunchCounter>=nTrainBunches){
trainCounter++;
if(trainCounter>=nTrains){
eventTime+=abortGap;
trainCounter=0;
}
else eventTime+=trainSpacing;
bunchCounter=0;
}
else eventTime+= bSpacing;
}
}
s.Stop();
s.Print();
delete rand;
CloseOutputFile();
}
<commit_msg>added track ID also for the tracks from ESD input<commit_after>#include <iostream>
#include <TDatabasePDG.h>
#include <TRandom.h>
#include <TF1.h>
#include <TStopwatch.h>
#include <AliESDtrackCuts.h>
#include <AliESDtrack.h>
#include <TFile.h>
#include <TTree.h>
#include <TRandom3.h>
#include "AliToyMCEvent.h"
#include "AliToyMCEventGeneratorSimple.h"
ClassImp(AliToyMCEventGeneratorSimple);
AliToyMCEventGeneratorSimple::AliToyMCEventGeneratorSimple()
:AliToyMCEventGenerator()
,fVertexMean(0.)
,fVertexSigma(7.)
,fNtracks(20)
,fInputFileNameESD("")
,fESDCuts(0x0)
{
//
}
//________________________________________________________________
AliToyMCEventGeneratorSimple::AliToyMCEventGeneratorSimple(const AliToyMCEventGeneratorSimple &gen)
:AliToyMCEventGenerator(gen)
,fVertexMean(gen.fVertexMean)
,fVertexSigma(gen.fVertexSigma)
,fNtracks(gen.fNtracks)
,fInputFileNameESD(gen.fInputFileNameESD)
,fESDCuts(gen.fESDCuts)
{
}
//________________________________________________________________
AliToyMCEventGeneratorSimple::~AliToyMCEventGeneratorSimple()
{
}
//________________________________________________________________
AliToyMCEventGeneratorSimple& AliToyMCEventGeneratorSimple::operator = (const AliToyMCEventGeneratorSimple &gen)
{
//assignment operator
if (&gen == this) return *this;
new (this) AliToyMCEventGeneratorSimple(gen);
return *this;
}
//________________________________________________________________
void AliToyMCEventGeneratorSimple::SetParametersSimple(Double_t vertexMean, Double_t vertexSigma) {
fVertexMean = vertexMean;
fVertexSigma = vertexSigma;
}
//________________________________________________________________
AliToyMCEvent* AliToyMCEventGeneratorSimple::Generate(Double_t time)
{
//
//
//
AliToyMCEvent *retEvent = new AliToyMCEvent();
retEvent->SetT0(time);
retEvent->SetX(0);
retEvent->SetX(0);
retEvent->SetZ(gRandom->Gaus(fVertexMean,fVertexSigma));
Double_t etaCuts=.9;
Double_t mass = TDatabasePDG::Instance()->GetParticle("pi+")->Mass();
TF1 fpt("fpt",Form("x*(1+(sqrt(x*x+%f^2)-%f)/([0]*[1]))^(-[0])",mass,mass),0.4,10);
fpt.SetParameters(7.24,0.120);
fpt.SetNpx(10000);
// Int_t nTracks = 400; //TODO: draw from experim dist
// Int_t nTracks = 20; //TODO: draw from experim dist
for(Int_t iTrack=0; iTrack<fNtracks; iTrack++){
Double_t phi = gRandom->Uniform(0.0, 2*TMath::Pi());
Double_t eta = gRandom->Uniform(-etaCuts, etaCuts);
Double_t pt = fpt.GetRandom(); // momentum for f1
Short_t sign=1;
if(gRandom->Rndm() < 0.5){
sign =1;
}else{
sign=-1;
}
Double_t theta = 2*TMath::ATan(TMath::Exp(-eta))-TMath::Pi()/2.;
Double_t pxyz[3];
pxyz[0]=pt*TMath::Cos(phi);
pxyz[1]=pt*TMath::Sin(phi);
pxyz[2]=pt*TMath::Tan(theta);
Double_t vertex[3]={0,0,retEvent->GetZ()};
Double_t cv[21]={0};
AliToyMCTrack *tempTrack = new AliToyMCTrack(vertex,pxyz,cv,sign);
// use unique ID for track number
// this will be used in DistortTrack track to set the cluster label
tempTrack->SetUniqueID(iTrack);
Bool_t trackDist = DistortTrack(*tempTrack, time);
if(trackDist) retEvent->AddTrack(*tempTrack);
delete tempTrack;
}
return retEvent;
}
//________________________________________________________________
void AliToyMCEventGeneratorSimple::RunSimulation(const Int_t nevents/*=10*/, const Int_t ntracks/*=400*/)
{
//
// run simple simulation with equal event spacing
//
if (!ConnectOutputFile()) return;
//initialise the space charge. Should be done after the tree was set up
InitSpaceCharge();
fNtracks=ntracks;
Double_t eventTime=0.;
const Double_t eventSpacing=1./50e3; //50kHz equally spaced
TStopwatch s;
for (Int_t ievent=0; ievent<nevents; ++ievent){
printf("Generating event %3d (%.3g)\n",ievent,eventTime);
fEvent = Generate(eventTime);
FillTree();
delete fEvent;
fEvent=0x0;
eventTime+=eventSpacing;
}
s.Stop();
s.Print();
CloseOutputFile();
}
//________________________________________________________________
AliToyMCEvent* AliToyMCEventGeneratorSimple::GenerateESD(AliESDEvent &esdEvent, Double_t time) {
AliToyMCEvent *retEvent = new AliToyMCEvent();
retEvent->SetT0(time);
retEvent->SetX(esdEvent.GetPrimaryVertex()->GetX());
retEvent->SetY(esdEvent.GetPrimaryVertex()->GetY());
retEvent->SetZ(esdEvent.GetPrimaryVertex()->GetZ());
if(!fNtracks) fNtracks = esdEvent.GetNumberOfTracks();
Int_t nUsedTracks = 0;
for(Int_t iTrack=0; iTrack<esdEvent.GetNumberOfTracks(); iTrack++){
AliESDtrack *part = esdEvent.GetTrack(iTrack);
if(!part) continue;
if (!fESDCuts->AcceptTrack(/*(AliESDtrack*)*/part))continue;
if(part->Pt() < 0.3) continue; //avoid tracks that fail to propagate through entire volume
Double_t pxyz[3];
pxyz[0]=part->Px();
pxyz[1]=part->Py();
pxyz[2]=part->Pz();
Double_t vertex[3]={retEvent->GetX(),retEvent->GetY(),retEvent->GetZ()};
Double_t cv[21]={0};
Int_t sign = part->Charge();
AliToyMCTrack *tempTrack = new AliToyMCTrack(vertex,pxyz,cv,sign);
// use unique ID for track number
// this will be used in DistortTrack track to set the cluster label
tempTrack->SetUniqueID(iTrack);
Bool_t trackDist = DistortTrack(*tempTrack, time);
if(trackDist) {
retEvent->AddTrack(*tempTrack);
nUsedTracks++;
}
delete tempTrack;
if(nUsedTracks >= fNtracks) break;
}
return retEvent;
}
//________________________________________________________________
void AliToyMCEventGeneratorSimple::RunSimulationESD(const Int_t nevents/*=10*/, const Int_t ntracks/*=400*/)
{
//
// run simulation using esd input with equal event spacing
//
if (!ConnectOutputFile()) return;
TFile f(Form("%s%s",fInputFileNameESD.Data(),"#AliESDs.root"));
if(!f.IsOpen()) {
std::cout << "file "<<fInputFileNameESD.Data() <<" could not be opened" << std::endl;
return;
}
TTree* esdTree = (TTree*) f.Get("esdTree");
if(!esdTree) {
std::cout <<"no esdTree in file " << std::endl;
return;
}
InitSpaceCharge();
AliESDEvent* esdEvent = new AliESDEvent();
fNtracks = ntracks;
esdEvent->ReadFromTree(esdTree);
Double_t eventTime=0.;
const Double_t eventSpacing=1./50e3; //50kHz equally spaced
TStopwatch s;
Int_t nEvents = nevents;
fESDCuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kTRUE,1);
if(nevents>esdTree->GetEntries()) nEvents = esdTree->GetEntries();
Int_t nUsedEvents = 0;
for (Int_t ievent=0; ievent<esdTree->GetEntries(); ++ievent){
printf("Generating event %3d (%.3g)\n",nUsedEvents,eventTime);
esdTree->GetEvent(ievent);
if(esdEvent->GetNumberOfTracks()==0) {
std::cout << " tracks == 0" << std::endl;
continue;
}
fEvent = GenerateESD(*esdEvent, eventTime);
if(fEvent->GetNumberOfTracks() >=10) {
nUsedEvents++;
FillTree();
eventTime+=eventSpacing;
}
delete fEvent;
fEvent=0x0;
if(nUsedEvents>=nevents) break;
}
s.Stop();
s.Print();
CloseOutputFile();
}
//________________________________________________________________
void AliToyMCEventGeneratorSimple::RunSimulationBunchTrain(const Int_t nevents/*=10*/, const Int_t ntracks/*=400*/)
{
//
// run simple simulation with equal event spacing
//
//Parameters for bunc
const Double_t abortGap = 3e-6; //
const Double_t collFreq = 50e3;
const Double_t bSpacing = 50e-9; //bunch spacing
const Int_t nTrainBunches = 48;
const Int_t nTrains = 12;
const Double_t revFreq = 1.11e4; //revolution frequency
const Double_t collProb = collFreq/(nTrainBunches*nTrains*revFreq);
const Double_t trainLength = bSpacing*(nTrainBunches-1);
const Double_t totTrainLength = nTrains*trainLength;
const Double_t trainSpacing = (1./revFreq - abortGap - totTrainLength)/(nTrains-1);
Bool_t equalSpacing = kFALSE;
TRandom3 *rand = new TRandom3();
//rand->SetSeed();
if (!ConnectOutputFile()) return;
//initialise the space charge. Should be done after the tree was set up
InitSpaceCharge();
fNtracks=ntracks;
Double_t eventTime=0.;
const Double_t eventSpacing=1./50e3; //50kHz equally spaced
TStopwatch s;
Int_t nGeneratedEvents = 0;
Int_t bunchCounter = 0;
Int_t trainCounter = 0;
//for (Int_t ievent=0; ievent<nevents; ++ievent){
while (nGeneratedEvents<nevents){
// std::cout <<trainCounter << " " << bunchCounter << " "<< "eventTime " << eventTime << std::endl;
if(equalSpacing) {
printf("Generating event %3d (%.3g)\n",nGeneratedEvents,eventTime);
fEvent = Generate(eventTime);
nGeneratedEvents++;
FillTree();
delete fEvent;
fEvent=0x0;
eventTime+=1./collFreq;
}
else{
Int_t nCollsInCrossing = rand -> Poisson(collProb);
for(Int_t iColl = 0; iColl<nCollsInCrossing; iColl++){
printf("Generating event %3d (%.3g)\n",nGeneratedEvents,eventTime);
fEvent = Generate(eventTime);
nGeneratedEvents++;
FillTree();
delete fEvent;
fEvent=0x0;
}
bunchCounter++;
if(bunchCounter>=nTrainBunches){
trainCounter++;
if(trainCounter>=nTrains){
eventTime+=abortGap;
trainCounter=0;
}
else eventTime+=trainSpacing;
bunchCounter=0;
}
else eventTime+= bSpacing;
}
}
s.Stop();
s.Print();
delete rand;
CloseOutputFile();
}
<|endoftext|> |
<commit_before>#include "MatrixConfig.h"
#include <SmurffCpp/Utils/MatrixUtils.h>
#include <SmurffCpp/IO/IDataWriter.h>
#include <SmurffCpp/DataMatrices/IDataCreator.h>
#include <SmurffCpp/Utils/Error.h>
using namespace smurff;
//
// Dense double matrix constructos
//
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, const std::vector<double>& values
, const NoiseConfig& noiseConfig
)
: MatrixConfig(nrow, ncol, std::shared_ptr<std::vector<double> >(), noiseConfig)
{
// Wait for nrow and ncol checks pass in constructor in initializer list to prevent wasteful vector copying
m_values = std::make_shared<std::vector<double> >(values);
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::vector<double>&& values
, const NoiseConfig& noiseConfig
)
: MatrixConfig(nrow, ncol, std::make_shared<std::vector<double> >(std::move(values)), noiseConfig)
{
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::shared_ptr<std::vector<double> > values
, const NoiseConfig& noiseConfig
)
: TensorConfig(true, false, false, 2, nrow * ncol, noiseConfig)
{
if (nrow == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'nrow' cannot be zero.");
}
if (ncol == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'ncol' cannot be zero.");
}
m_dims->push_back(nrow);
m_dims->push_back(ncol);
m_columns->resize(m_nnz * m_nmodes);
m_values = values;
for (std::uint64_t row = 0; row < nrow; row++)
{
for (std::uint64_t col = 0; col < ncol; col++)
{
m_columns->operator[](nrow * col + row) = row;
m_columns->operator[](nrow * col + row + m_nnz) = col;
}
}
}
//
// Sparse double matrix constructors
//
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, const std::vector<std::uint32_t>& rows
, const std::vector<std::uint32_t>& cols
, const std::vector<double>& values
, const NoiseConfig& noiseConfig
, bool isScarce
)
: TensorConfig(false, false, isScarce, 2, values.size(), noiseConfig)
{
if (nrow == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'nrow' cannot be zero.");
}
if (ncol == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'ncol' cannot be zero.");
}
if (rows.size() != cols.size() || rows.size() != values.size())
{
THROWERROR("Cannot create MatrixConfig instance: 'rows', 'cols' and 'values' should all be the same size.");
}
m_dims->push_back(nrow);
m_dims->push_back(ncol);
m_columns->resize(m_nnz * m_nmodes);
m_values->resize(m_nnz);
for (std::uint64_t i = 0; i < m_nnz; i++)
{
m_columns->operator[](i) = rows[i];
m_columns->operator[](i + m_nnz) = cols[i];
m_values->operator[](i) = values[i];
}
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::vector<std::uint32_t>&& rows
, std::vector<std::uint32_t>&& cols
, std::vector<double>&& values
, const NoiseConfig& noiseConfig
, bool isScarce
)
: MatrixConfig( nrow
, ncol
, std::make_shared<std::vector<std::uint32_t> >(std::move(rows))
, std::make_shared<std::vector<std::uint32_t> >(std::move(cols))
, std::make_shared<std::vector<double> >(std::move(values))
, noiseConfig, isScarce
)
{
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::shared_ptr<std::vector<std::uint32_t> > rows
, std::shared_ptr<std::vector<std::uint32_t> > cols
, std::shared_ptr<std::vector<double> > values
, const NoiseConfig& noiseConfig
, bool isScarce
)
: TensorConfig(false, false, isScarce, 2, values->size(), noiseConfig)
{
if (nrow == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'nrow' cannot be zero.");
}
if (ncol == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'ncol' cannot be zero.");
}
if (rows->size() != cols->size() || rows->size() != values->size())
{
THROWERROR("Cannot create MatrixConfig instance: 'rows', 'cols' and 'values' should all be the same size.");
}
m_dims->push_back(nrow);
m_dims->push_back(ncol);
m_columns->resize(m_nnz * m_nmodes);
m_values = values;
m_rows = rows;
m_cols = cols;
for (std::uint64_t i = 0; i < m_nnz; i++)
{
m_columns->operator[](i) = rows->operator[](i);
m_columns->operator[](i + m_nnz) = cols->operator[](i);
}
}
//
// Sparse binary matrix constructors
//
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, const std::vector<std::uint32_t>& rows
, const std::vector<std::uint32_t>& cols
, const NoiseConfig& noiseConfig
, bool isScarce
)
: TensorConfig(false, true, isScarce, 2, rows.size(), noiseConfig)
{
if (nrow == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'nrow' cannot be zero.");
}
if (ncol == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'ncol' cannot be zero.");
}
if (rows.size() != cols.size())
{
THROWERROR("Cannot create MatrixConfig instance: 'rows' and 'cols' should all be the same size.");
}
m_dims->push_back(nrow);
m_dims->push_back(ncol);
m_columns->resize(m_nnz * m_nmodes);
m_values->resize(m_nnz);
for (std::uint64_t i = 0; i < m_nnz; i++)
{
m_columns->operator[](i) = rows[i];
m_columns->operator[](i + m_nnz) = cols[i];
m_values->operator[](i) = 1;
}
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::vector<std::uint32_t>&& rows
, std::vector<std::uint32_t>&& cols
, const NoiseConfig& noiseConfig
, bool isScarce
)
: MatrixConfig( nrow
, ncol
, std::make_shared<std::vector<std::uint32_t> >(std::move(rows))
, std::make_shared<std::vector<std::uint32_t> >(std::move(cols))
, noiseConfig, isScarce
)
{
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::shared_ptr<std::vector<std::uint32_t> > rows
, std::shared_ptr<std::vector<std::uint32_t> > cols
, const NoiseConfig& noiseConfig
, bool isScarce
)
: TensorConfig(false, true, isScarce, 2, rows->size(), noiseConfig)
{
if (nrow == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'nrow' cannot be zero.");
}
if (ncol == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'ncol' cannot be zero.");
}
if (rows->size() != cols->size())
{
THROWERROR("Cannot create MatrixConfig instance: 'rows' and 'cols' should all be the same size.");
}
m_dims->push_back(nrow);
m_dims->push_back(ncol);
m_columns->resize(m_nnz * m_nmodes);
m_values->resize(m_nnz);
m_rows = rows;
m_cols = cols;
for (std::uint64_t i = 0; i < m_nnz; i++)
{
m_columns->operator[](i) = rows->operator[](i);
m_columns->operator[](i + m_nnz) = cols->operator[](i);
m_values->operator[](i) = 1;
}
}
//
// Constructors for constructing sparse matrix as a tensor
//
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, const std::vector<std::uint32_t>& columns
, const std::vector<double>& values
, const NoiseConfig& noiseConfig
, bool isScarce
)
: TensorConfig({ nrow, ncol }, columns, values, noiseConfig, isScarce)
{
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::vector<std::uint32_t>&& columns
, std::vector<double>&& values
, const NoiseConfig& noiseConfig
, bool isScarce
)
: TensorConfig({ nrow, ncol }, std::move(columns), std::move(values), noiseConfig, isScarce)
{
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::shared_ptr<std::vector<std::uint32_t> > columns
, std::shared_ptr<std::vector<double> > values
, const NoiseConfig& noiseConfig
, bool isScarce
)
: TensorConfig(std::make_shared<std::vector<std::uint64_t> >(std::initializer_list<std::uint64_t>({ nrow, ncol })), columns, values, noiseConfig, isScarce)
{
}
//
// Constructors for constructing sparse binary matrix as a tensor
//
MatrixConfig::MatrixConfig(std::uint64_t nrow, std::uint64_t ncol,
const std::vector<std::uint32_t>& columns,
const NoiseConfig& noiseConfig, bool isScarce)
: TensorConfig({ nrow, ncol }, columns, noiseConfig, isScarce)
{
}
MatrixConfig::MatrixConfig(std::uint64_t nrow, std::uint64_t ncol,
std::vector<std::uint32_t>&& columns,
const NoiseConfig& noiseConfig, bool isScarce)
: TensorConfig({ nrow, ncol }, std::move(columns), noiseConfig, isScarce)
{
}
MatrixConfig::MatrixConfig(std::uint64_t nrow, std::uint64_t ncol,
std::shared_ptr<std::vector<std::uint32_t> > columns,
const NoiseConfig& noiseConfig, bool isScarce)
: TensorConfig(std::make_shared<std::vector<std::uint64_t> >(std::initializer_list<std::uint64_t>({ nrow, ncol })), columns, noiseConfig, isScarce)
{
}
// TODO: probably remove default constructor
MatrixConfig::MatrixConfig()
: TensorConfig(true, false, false, 2, 0, NoiseConfig())
{
m_dims->push_back(0);
m_dims->push_back(0);
m_columns->clear();
m_values->clear();
}
//
// other methods
//
std::uint64_t MatrixConfig::getNRow() const
{
return m_dims->operator[](0);
}
std::uint64_t MatrixConfig::getNCol() const
{
return m_dims->operator[](1);
}
const std::vector<std::uint32_t>& MatrixConfig::getRows() const
{
return *getRowsPtr();
}
const std::vector<std::uint32_t>& MatrixConfig::getCols() const
{
return *getColsPtr();
}
std::shared_ptr<std::vector<std::uint32_t> > MatrixConfig::getRowsPtr() const
{
if (!m_rows)
{
m_rows = std::make_shared<std::vector<std::uint32_t> >();
if (m_nnz != 0)
{
m_rows->reserve(m_nnz);
for (std::uint64_t i = 0; i < m_nnz; i++)
m_rows->push_back(m_columns->operator[](i));
}
}
return m_rows;
}
std::shared_ptr<std::vector<std::uint32_t> > MatrixConfig::getColsPtr() const
{
if (!m_cols)
{
m_cols = std::make_shared<std::vector<std::uint32_t> >();
if (m_nnz != 0)
{
m_cols->reserve(m_nnz);
for (std::uint64_t i = 0; i < m_nnz; i++)
m_cols->push_back(m_columns->operator[](i + m_nnz));
}
}
return m_cols;
}
std::shared_ptr<Data> MatrixConfig::create(std::shared_ptr<IDataCreator> creator) const
{
//have to use dynamic cast here but only because shared_from_this() can only return base pointer even from child
return creator->create(std::dynamic_pointer_cast<const MatrixConfig>(shared_from_this()));
}
void MatrixConfig::write(std::shared_ptr<IDataWriter> writer) const
{
//have to use dynamic cast here but only because shared_from_this() can only return base pointer even from child
writer->write(std::dynamic_pointer_cast<const MatrixConfig>(shared_from_this()));
}
<commit_msg>Do not initialized columns ptr for dense matrices<commit_after>#include "MatrixConfig.h"
#include <SmurffCpp/Utils/MatrixUtils.h>
#include <SmurffCpp/IO/IDataWriter.h>
#include <SmurffCpp/DataMatrices/IDataCreator.h>
#include <SmurffCpp/Utils/Error.h>
using namespace smurff;
//
// Dense double matrix constructos
//
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, const std::vector<double>& values
, const NoiseConfig& noiseConfig
)
: MatrixConfig(nrow, ncol, std::shared_ptr<std::vector<double> >(), noiseConfig)
{
// Wait for nrow and ncol checks pass in constructor in initializer list to prevent wasteful vector copying
m_values = std::make_shared<std::vector<double> >(values);
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::vector<double>&& values
, const NoiseConfig& noiseConfig
)
: MatrixConfig(nrow, ncol, std::make_shared<std::vector<double> >(std::move(values)), noiseConfig)
{
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::shared_ptr<std::vector<double> > values
, const NoiseConfig& noiseConfig
)
: TensorConfig(true, false, false, 2, nrow * ncol, noiseConfig)
{
if (nrow == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'nrow' cannot be zero.");
}
if (ncol == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'ncol' cannot be zero.");
}
m_dims->push_back(nrow);
m_dims->push_back(ncol);
m_values = values;
}
//
// Sparse double matrix constructors
//
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, const std::vector<std::uint32_t>& rows
, const std::vector<std::uint32_t>& cols
, const std::vector<double>& values
, const NoiseConfig& noiseConfig
, bool isScarce
)
: TensorConfig(false, false, isScarce, 2, values.size(), noiseConfig)
{
if (nrow == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'nrow' cannot be zero.");
}
if (ncol == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'ncol' cannot be zero.");
}
if (rows.size() != cols.size() || rows.size() != values.size())
{
THROWERROR("Cannot create MatrixConfig instance: 'rows', 'cols' and 'values' should all be the same size.");
}
m_dims->push_back(nrow);
m_dims->push_back(ncol);
m_columns->resize(m_nnz * m_nmodes);
m_values->resize(m_nnz);
for (std::uint64_t i = 0; i < m_nnz; i++)
{
m_columns->operator[](i) = rows[i];
m_columns->operator[](i + m_nnz) = cols[i];
m_values->operator[](i) = values[i];
}
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::vector<std::uint32_t>&& rows
, std::vector<std::uint32_t>&& cols
, std::vector<double>&& values
, const NoiseConfig& noiseConfig
, bool isScarce
)
: MatrixConfig( nrow
, ncol
, std::make_shared<std::vector<std::uint32_t> >(std::move(rows))
, std::make_shared<std::vector<std::uint32_t> >(std::move(cols))
, std::make_shared<std::vector<double> >(std::move(values))
, noiseConfig, isScarce
)
{
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::shared_ptr<std::vector<std::uint32_t> > rows
, std::shared_ptr<std::vector<std::uint32_t> > cols
, std::shared_ptr<std::vector<double> > values
, const NoiseConfig& noiseConfig
, bool isScarce
)
: TensorConfig(false, false, isScarce, 2, values->size(), noiseConfig)
{
if (nrow == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'nrow' cannot be zero.");
}
if (ncol == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'ncol' cannot be zero.");
}
if (rows->size() != cols->size() || rows->size() != values->size())
{
THROWERROR("Cannot create MatrixConfig instance: 'rows', 'cols' and 'values' should all be the same size.");
}
m_dims->push_back(nrow);
m_dims->push_back(ncol);
m_columns->resize(m_nnz * m_nmodes);
m_values = values;
m_rows = rows;
m_cols = cols;
for (std::uint64_t i = 0; i < m_nnz; i++)
{
m_columns->operator[](i) = rows->operator[](i);
m_columns->operator[](i + m_nnz) = cols->operator[](i);
}
}
//
// Sparse binary matrix constructors
//
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, const std::vector<std::uint32_t>& rows
, const std::vector<std::uint32_t>& cols
, const NoiseConfig& noiseConfig
, bool isScarce
)
: TensorConfig(false, true, isScarce, 2, rows.size(), noiseConfig)
{
if (nrow == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'nrow' cannot be zero.");
}
if (ncol == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'ncol' cannot be zero.");
}
if (rows.size() != cols.size())
{
THROWERROR("Cannot create MatrixConfig instance: 'rows' and 'cols' should all be the same size.");
}
m_dims->push_back(nrow);
m_dims->push_back(ncol);
m_columns->resize(m_nnz * m_nmodes);
m_values->resize(m_nnz);
for (std::uint64_t i = 0; i < m_nnz; i++)
{
m_columns->operator[](i) = rows[i];
m_columns->operator[](i + m_nnz) = cols[i];
m_values->operator[](i) = 1;
}
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::vector<std::uint32_t>&& rows
, std::vector<std::uint32_t>&& cols
, const NoiseConfig& noiseConfig
, bool isScarce
)
: MatrixConfig( nrow
, ncol
, std::make_shared<std::vector<std::uint32_t> >(std::move(rows))
, std::make_shared<std::vector<std::uint32_t> >(std::move(cols))
, noiseConfig, isScarce
)
{
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::shared_ptr<std::vector<std::uint32_t> > rows
, std::shared_ptr<std::vector<std::uint32_t> > cols
, const NoiseConfig& noiseConfig
, bool isScarce
)
: TensorConfig(false, true, isScarce, 2, rows->size(), noiseConfig)
{
if (nrow == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'nrow' cannot be zero.");
}
if (ncol == 0)
{
THROWERROR("Cannot create MatrixConfig instance: 'ncol' cannot be zero.");
}
if (rows->size() != cols->size())
{
THROWERROR("Cannot create MatrixConfig instance: 'rows' and 'cols' should all be the same size.");
}
m_dims->push_back(nrow);
m_dims->push_back(ncol);
m_columns->resize(m_nnz * m_nmodes);
m_values->resize(m_nnz);
m_rows = rows;
m_cols = cols;
for (std::uint64_t i = 0; i < m_nnz; i++)
{
m_columns->operator[](i) = rows->operator[](i);
m_columns->operator[](i + m_nnz) = cols->operator[](i);
m_values->operator[](i) = 1;
}
}
//
// Constructors for constructing sparse matrix as a tensor
//
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, const std::vector<std::uint32_t>& columns
, const std::vector<double>& values
, const NoiseConfig& noiseConfig
, bool isScarce
)
: TensorConfig({ nrow, ncol }, columns, values, noiseConfig, isScarce)
{
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::vector<std::uint32_t>&& columns
, std::vector<double>&& values
, const NoiseConfig& noiseConfig
, bool isScarce
)
: TensorConfig({ nrow, ncol }, std::move(columns), std::move(values), noiseConfig, isScarce)
{
}
MatrixConfig::MatrixConfig( std::uint64_t nrow
, std::uint64_t ncol
, std::shared_ptr<std::vector<std::uint32_t> > columns
, std::shared_ptr<std::vector<double> > values
, const NoiseConfig& noiseConfig
, bool isScarce
)
: TensorConfig(std::make_shared<std::vector<std::uint64_t> >(std::initializer_list<std::uint64_t>({ nrow, ncol })), columns, values, noiseConfig, isScarce)
{
}
//
// Constructors for constructing sparse binary matrix as a tensor
//
MatrixConfig::MatrixConfig(std::uint64_t nrow, std::uint64_t ncol,
const std::vector<std::uint32_t>& columns,
const NoiseConfig& noiseConfig, bool isScarce)
: TensorConfig({ nrow, ncol }, columns, noiseConfig, isScarce)
{
}
MatrixConfig::MatrixConfig(std::uint64_t nrow, std::uint64_t ncol,
std::vector<std::uint32_t>&& columns,
const NoiseConfig& noiseConfig, bool isScarce)
: TensorConfig({ nrow, ncol }, std::move(columns), noiseConfig, isScarce)
{
}
MatrixConfig::MatrixConfig(std::uint64_t nrow, std::uint64_t ncol,
std::shared_ptr<std::vector<std::uint32_t> > columns,
const NoiseConfig& noiseConfig, bool isScarce)
: TensorConfig(std::make_shared<std::vector<std::uint64_t> >(std::initializer_list<std::uint64_t>({ nrow, ncol })), columns, noiseConfig, isScarce)
{
}
// TODO: probably remove default constructor
MatrixConfig::MatrixConfig()
: TensorConfig(true, false, false, 2, 0, NoiseConfig())
{
m_dims->push_back(0);
m_dims->push_back(0);
m_columns->clear();
m_values->clear();
}
//
// other methods
//
std::uint64_t MatrixConfig::getNRow() const
{
return m_dims->operator[](0);
}
std::uint64_t MatrixConfig::getNCol() const
{
return m_dims->operator[](1);
}
const std::vector<std::uint32_t>& MatrixConfig::getRows() const
{
return *getRowsPtr();
}
const std::vector<std::uint32_t>& MatrixConfig::getCols() const
{
return *getColsPtr();
}
std::shared_ptr<std::vector<std::uint32_t> > MatrixConfig::getRowsPtr() const
{
if (!m_rows)
{
m_rows = std::make_shared<std::vector<std::uint32_t> >();
if (m_nnz != 0)
{
m_rows->reserve(m_nnz);
for (std::uint64_t i = 0; i < m_nnz; i++)
m_rows->push_back(m_columns->operator[](i));
}
}
return m_rows;
}
std::shared_ptr<std::vector<std::uint32_t> > MatrixConfig::getColsPtr() const
{
if (!m_cols)
{
m_cols = std::make_shared<std::vector<std::uint32_t> >();
if (m_nnz != 0)
{
m_cols->reserve(m_nnz);
for (std::uint64_t i = 0; i < m_nnz; i++)
m_cols->push_back(m_columns->operator[](i + m_nnz));
}
}
return m_cols;
}
std::shared_ptr<Data> MatrixConfig::create(std::shared_ptr<IDataCreator> creator) const
{
//have to use dynamic cast here but only because shared_from_this() can only return base pointer even from child
return creator->create(std::dynamic_pointer_cast<const MatrixConfig>(shared_from_this()));
}
void MatrixConfig::write(std::shared_ptr<IDataWriter> writer) const
{
//have to use dynamic cast here but only because shared_from_this() can only return base pointer even from child
writer->write(std::dynamic_pointer_cast<const MatrixConfig>(shared_from_this()));
}
<|endoftext|> |
<commit_before>/*
This file is part of Kontact.
Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qcheckbox.h>
#include <qlayout.h>
//Added by qt3to4:
#include <QVBoxLayout>
#include <dcopref.h>
#include <kaboutdata.h>
#include <kacceleratormanager.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <k3listview.h>
#include <klocale.h>
#include "kcmkmailsummary.h"
#include <kdepimmacros.h>
extern "C"
{
KDE_EXPORT KCModule *create_kmailsummary( QWidget *parent, const char * )
{
KInstance *inst = new KInstance("kcmkmailsummary" );
return new KCMKMailSummary( inst, parent );
}
}
KCMKMailSummary::KCMKMailSummary( KInstance *inst, QWidget *parent )
: KCModule( inst, parent )
{
initGUI();
connect( mFolderView, SIGNAL( clicked( Q3ListViewItem* ) ), SLOT( modified() ) );
connect( mFullPath, SIGNAL( toggled( bool ) ), SLOT( modified() ) );
KAcceleratorManager::manage( this );
load();
KAboutData *about = new KAboutData( I18N_NOOP( "kcmkmailsummary" ),
I18N_NOOP( "Mail Summary Configuration Dialog" ),
0, 0, KAboutData::License_GPL,
I18N_NOOP( "(c) 2004 Tobias Koenig" ) );
about->addAuthor( "Tobias Koenig", 0, "tokoe@kde.org" );
setAboutData( about );
}
void KCMKMailSummary::modified()
{
emit changed( true );
}
void KCMKMailSummary::initGUI()
{
QVBoxLayout *layout = new QVBoxLayout( this );
layout->setSpacing( KDialog::spacingHint() );
layout->setMargin( 0 );
mFolderView = new K3ListView( this );
mFolderView->setRootIsDecorated( true );
mFolderView->setFullWidth( true );
mFolderView->addColumn( i18n( "Summary" ) );
mFullPath = new QCheckBox( i18n( "Show full path for folders" ), this );
layout->addWidget( mFolderView );
layout->addWidget( mFullPath );
}
void KCMKMailSummary::initFolders()
{
DCOPRef kmail( "kmail", "KMailIface" );
QStringList folderList;
kmail.call( "folderList" ).get( folderList );
mFolderView->clear();
mFolderMap.clear();
QStringList::Iterator it;
for ( it = folderList.begin(); it != folderList.end(); ++it ) {
QString displayName;
if ( (*it) == "/Local" )
displayName = i18nc( "prefix for local folders", "Local" );
else {
DCOPRef folderRef = kmail.call( "getFolder(QString)", *it );
folderRef.call( "displayName()" ).get( displayName );
}
if ( (*it).contains( '/' ) == 1 ) {
if ( mFolderMap.find( *it ) == mFolderMap.end() )
mFolderMap.insert( *it, new Q3ListViewItem( mFolderView,
displayName ) );
} else {
const int pos = (*it).lastIndexOf( '/' );
const QString parentFolder = (*it).left( pos );
mFolderMap.insert( *it,
new Q3CheckListItem( mFolderMap[ parentFolder ],
displayName,
Q3CheckListItem::CheckBox ) );
}
}
}
void KCMKMailSummary::loadFolders()
{
KConfig config( "kcmkmailsummaryrc" );
config.setGroup( "General" );
QStringList folders;
if ( !config.hasKey( "ActiveFolders" ) )
folders << "/Local/inbox";
else
folders = config.readEntry( "ActiveFolders" , QStringList() );
QMap<QString, Q3ListViewItem*>::Iterator it;
for ( it = mFolderMap.begin(); it != mFolderMap.end(); ++it ) {
if ( Q3CheckListItem *qli = dynamic_cast<Q3CheckListItem*>( it.value() ) ) {
if ( folders.contains( it.key() ) ) {
qli->setOn( true );
mFolderView->ensureItemVisible( it.value() );
} else {
qli->setOn( false );
}
}
}
mFullPath->setChecked( config.readEntry( "ShowFullPath", true ) );
}
void KCMKMailSummary::storeFolders()
{
KConfig config( "kcmkmailsummaryrc" );
config.setGroup( "General" );
QStringList folders;
QMap<QString, Q3ListViewItem*>::Iterator it;
for ( it = mFolderMap.begin(); it != mFolderMap.end(); ++it )
if ( Q3CheckListItem *qli = dynamic_cast<Q3CheckListItem*>( it.value() ) )
if ( qli->isOn() )
folders.append( it.key() );
config.writeEntry( "ActiveFolders", folders );
config.writeEntry( "ShowFullPath", mFullPath->isChecked() );
config.sync();
}
void KCMKMailSummary::load()
{
initFolders();
loadFolders();
emit changed( false );
}
void KCMKMailSummary::save()
{
storeFolders();
emit changed( false );
}
void KCMKMailSummary::defaults()
{
mFullPath->setChecked( true );
emit changed( true );
}
#include "kcmkmailsummary.moc"
<commit_msg>assuming it means to count the /s<commit_after>/*
This file is part of Kontact.
Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qcheckbox.h>
#include <qlayout.h>
//Added by qt3to4:
#include <QVBoxLayout>
#include <dcopref.h>
#include <kaboutdata.h>
#include <kacceleratormanager.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <k3listview.h>
#include <klocale.h>
#include "kcmkmailsummary.h"
#include <kdepimmacros.h>
extern "C"
{
KDE_EXPORT KCModule *create_kmailsummary( QWidget *parent, const char * )
{
KInstance *inst = new KInstance("kcmkmailsummary" );
return new KCMKMailSummary( inst, parent );
}
}
KCMKMailSummary::KCMKMailSummary( KInstance *inst, QWidget *parent )
: KCModule( inst, parent )
{
initGUI();
connect( mFolderView, SIGNAL( clicked( Q3ListViewItem* ) ), SLOT( modified() ) );
connect( mFullPath, SIGNAL( toggled( bool ) ), SLOT( modified() ) );
KAcceleratorManager::manage( this );
load();
KAboutData *about = new KAboutData( I18N_NOOP( "kcmkmailsummary" ),
I18N_NOOP( "Mail Summary Configuration Dialog" ),
0, 0, KAboutData::License_GPL,
I18N_NOOP( "(c) 2004 Tobias Koenig" ) );
about->addAuthor( "Tobias Koenig", 0, "tokoe@kde.org" );
setAboutData( about );
}
void KCMKMailSummary::modified()
{
emit changed( true );
}
void KCMKMailSummary::initGUI()
{
QVBoxLayout *layout = new QVBoxLayout( this );
layout->setSpacing( KDialog::spacingHint() );
layout->setMargin( 0 );
mFolderView = new K3ListView( this );
mFolderView->setRootIsDecorated( true );
mFolderView->setFullWidth( true );
mFolderView->addColumn( i18n( "Summary" ) );
mFullPath = new QCheckBox( i18n( "Show full path for folders" ), this );
layout->addWidget( mFolderView );
layout->addWidget( mFullPath );
}
void KCMKMailSummary::initFolders()
{
DCOPRef kmail( "kmail", "KMailIface" );
QStringList folderList;
kmail.call( "folderList" ).get( folderList );
mFolderView->clear();
mFolderMap.clear();
QStringList::Iterator it;
for ( it = folderList.begin(); it != folderList.end(); ++it ) {
QString displayName;
if ( (*it) == "/Local" )
displayName = i18nc( "prefix for local folders", "Local" );
else {
DCOPRef folderRef = kmail.call( "getFolder(QString)", *it );
folderRef.call( "displayName()" ).get( displayName );
}
if ( (*it).count( '/' ) == 1 ) {
if ( mFolderMap.find( *it ) == mFolderMap.end() )
mFolderMap.insert( *it, new Q3ListViewItem( mFolderView,
displayName ) );
} else {
const int pos = (*it).lastIndexOf( '/' );
const QString parentFolder = (*it).left( pos );
mFolderMap.insert( *it,
new Q3CheckListItem( mFolderMap[ parentFolder ],
displayName,
Q3CheckListItem::CheckBox ) );
}
}
}
void KCMKMailSummary::loadFolders()
{
KConfig config( "kcmkmailsummaryrc" );
config.setGroup( "General" );
QStringList folders;
if ( !config.hasKey( "ActiveFolders" ) )
folders << "/Local/inbox";
else
folders = config.readEntry( "ActiveFolders" , QStringList() );
QMap<QString, Q3ListViewItem*>::Iterator it;
for ( it = mFolderMap.begin(); it != mFolderMap.end(); ++it ) {
if ( Q3CheckListItem *qli = dynamic_cast<Q3CheckListItem*>( it.value() ) ) {
if ( folders.contains( it.key() ) ) {
qli->setOn( true );
mFolderView->ensureItemVisible( it.value() );
} else {
qli->setOn( false );
}
}
}
mFullPath->setChecked( config.readEntry( "ShowFullPath", true ) );
}
void KCMKMailSummary::storeFolders()
{
KConfig config( "kcmkmailsummaryrc" );
config.setGroup( "General" );
QStringList folders;
QMap<QString, Q3ListViewItem*>::Iterator it;
for ( it = mFolderMap.begin(); it != mFolderMap.end(); ++it )
if ( Q3CheckListItem *qli = dynamic_cast<Q3CheckListItem*>( it.value() ) )
if ( qli->isOn() )
folders.append( it.key() );
config.writeEntry( "ActiveFolders", folders );
config.writeEntry( "ShowFullPath", mFullPath->isChecked() );
config.sync();
}
void KCMKMailSummary::load()
{
initFolders();
loadFolders();
emit changed( false );
}
void KCMKMailSummary::save()
{
storeFolders();
emit changed( false );
}
void KCMKMailSummary::defaults()
{
mFullPath->setChecked( true );
emit changed( true );
}
#include "kcmkmailsummary.moc"
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/search_extension.h"
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/render_messages_params.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "v8/include/v8.h"
using WebKit::WebFrame;
using WebKit::WebView;
namespace extensions_v8 {
const char* const kSearchExtensionName = "v8/InstantSearch";
class SearchExtensionWrapper : public v8::Extension {
public:
SearchExtensionWrapper();
// Allows v8's javascript code to call the native functions defined
// in this class for window.chrome.
virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(
v8::Handle<v8::String> name);
// Helper function to find the RenderView. May return NULL.
static RenderView* GetRenderView();
// Implementation of window.chrome.setSuggestResult.
static v8::Handle<v8::Value> SetSuggestResult(const v8::Arguments& args);
private:
DISALLOW_COPY_AND_ASSIGN(SearchExtensionWrapper);
};
SearchExtensionWrapper::SearchExtensionWrapper()
: v8::Extension(kSearchExtensionName,
"var chrome;"
"if (!chrome)"
" chrome = {};"
"chrome.setSuggestResult = function(text) {"
" native function NativeSetSuggestResult();"
" NativeSetSuggestResult(text);"
"};") {
}
v8::Handle<v8::FunctionTemplate> SearchExtensionWrapper::GetNativeFunction(
v8::Handle<v8::String> name) {
if (name->Equals(v8::String::New("NativeSetSuggestResult"))) {
return v8::FunctionTemplate::New(SetSuggestResult);
}
return v8::Handle<v8::FunctionTemplate>();
}
// static
RenderView* SearchExtensionWrapper::GetRenderView() {
WebFrame* webframe = WebFrame::frameForEnteredContext();
DCHECK(webframe) << "There should be an active frame since we just got "
"a native function called.";
if (!webframe) return NULL;
WebView* webview = webframe->view();
if (!webview) return NULL; // can happen during closing
return RenderView::FromWebView(webview);
}
// static
v8::Handle<v8::Value> SearchExtensionWrapper::SetSuggestResult(
const v8::Arguments& args) {
if (!args.Length() || !args[0]->IsString()) return v8::Undefined();
std::string suggest = std::string(*v8::String::Utf8Value(args[0]));
if (!suggest.length()) return v8::Undefined();
RenderView* render_view = GetRenderView();
if (!render_view) return v8::Undefined();
render_view->SetSuggestResult(suggest);
return v8::Undefined();
}
v8::Extension* SearchExtension::Get() {
return new SearchExtensionWrapper();
}
} // namespace extensions_v8
<commit_msg>Makes window.chrome.setSuggestResult pass through an empty string.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/search_extension.h"
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/render_messages_params.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "v8/include/v8.h"
using WebKit::WebFrame;
using WebKit::WebView;
namespace extensions_v8 {
const char* const kSearchExtensionName = "v8/InstantSearch";
class SearchExtensionWrapper : public v8::Extension {
public:
SearchExtensionWrapper();
// Allows v8's javascript code to call the native functions defined
// in this class for window.chrome.
virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(
v8::Handle<v8::String> name);
// Helper function to find the RenderView. May return NULL.
static RenderView* GetRenderView();
// Implementation of window.chrome.setSuggestResult.
static v8::Handle<v8::Value> SetSuggestResult(const v8::Arguments& args);
private:
DISALLOW_COPY_AND_ASSIGN(SearchExtensionWrapper);
};
SearchExtensionWrapper::SearchExtensionWrapper()
: v8::Extension(kSearchExtensionName,
"var chrome;"
"if (!chrome)"
" chrome = {};"
"chrome.setSuggestResult = function(text) {"
" native function NativeSetSuggestResult();"
" NativeSetSuggestResult(text);"
"};") {
}
v8::Handle<v8::FunctionTemplate> SearchExtensionWrapper::GetNativeFunction(
v8::Handle<v8::String> name) {
if (name->Equals(v8::String::New("NativeSetSuggestResult"))) {
return v8::FunctionTemplate::New(SetSuggestResult);
}
return v8::Handle<v8::FunctionTemplate>();
}
// static
RenderView* SearchExtensionWrapper::GetRenderView() {
WebFrame* webframe = WebFrame::frameForEnteredContext();
DCHECK(webframe) << "There should be an active frame since we just got "
"a native function called.";
if (!webframe) return NULL;
WebView* webview = webframe->view();
if (!webview) return NULL; // can happen during closing
return RenderView::FromWebView(webview);
}
// static
v8::Handle<v8::Value> SearchExtensionWrapper::SetSuggestResult(
const v8::Arguments& args) {
if (!args.Length() || !args[0]->IsString()) return v8::Undefined();
RenderView* render_view = GetRenderView();
if (!render_view) return v8::Undefined();
render_view->SetSuggestResult(std::string(*v8::String::Utf8Value(args[0])));
return v8::Undefined();
}
v8::Extension* SearchExtension::Get() {
return new SearchExtensionWrapper();
}
} // namespace extensions_v8
<|endoftext|> |
<commit_before><commit_msg>docx OMathArg can actually be more than one element<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2011, 2012 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 "CounterImp.h"
namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{
namespace {
struct AdditiveGlyph
{
int weight;
char16_t* glyph;
};
// 1 4999
AdditiveGlyph upperRoman[] =
{
1000, u"M",
900, u"CM",
500, u"D",
400, u"CD",
100, u"C",
90, u"XC",
50, u"L",
40, u"XL",
10, u"X",
9, u"IX",
5, u"V",
4, u"IV",
1, u"I",
0, 0
};
// 1 4999
AdditiveGlyph lowerRoman[] =
{
1000, u"m",
900, u"cm",
500, u"d",
400, u"cd",
100, u"c",
90, u"xc",
50, u"l",
40, u"xl",
10, u"x",
9, u"ix",
5, u"v",
4, u"iv",
1, u"i",
0, 0
};
std::u16string convertToRoman(int n, AdditiveGlyph* glyphList)
{
if (n < 0 || 5000 <= n)
return toString(n);
std::u16string value;
for (AdditiveGlyph* i = glyphList; i->glyph; ++i) {
int t = n / i->weight;
if (0 < t) {
n -= t * i->weight;
while (0 < t--)
value += i->glyph;
}
}
return value;
}
std::u16string emit(int i, unsigned type)
{
std::u16string value;
switch (type) {
case CSSListStyleTypeValueImp::None:
break;
case CSSListStyleTypeValueImp::Disc:
value = u"\u2022"; // •
break;
case CSSListStyleTypeValueImp::Circle:
value = u"\u25E6"; // ◦
break;
case CSSListStyleTypeValueImp::Square:
// Use u25A0 instead of u25FE for the IPA font for now
value = u"\u25A0"; // ◾ "\u25FE"
break;
case CSSListStyleTypeValueImp::Decimal:
value = toString(i);
break;
case CSSListStyleTypeValueImp::DecimalLeadingZero:
value = toString(i < 0 ? -i : i);
if (-9 <= i && i <= 9)
value = u"0" + value;
if (i < 0)
value = u"-" + value;
break;
case CSSListStyleTypeValueImp::LowerAlpha:
case CSSListStyleTypeValueImp::LowerLatin:
value = std::u16string(1, u'a' + static_cast<unsigned>(i) % 26 - 1);
break;
case CSSListStyleTypeValueImp::UpperAlpha:
case CSSListStyleTypeValueImp::UpperLatin:
value = std::u16string(1, u'A' + static_cast<unsigned>(i) % 26 - 1);
break;
case CSSListStyleTypeValueImp::LowerGreek:
// This style is only defined because CSS2.1 has it.
// It doesn't appear to actually be used in Greek texts.
value = std::u16string(1, u"αβγδεζηθικλμνξοπρστυφχψω"[static_cast<unsigned>(i - 1) % 24]);
break;
case CSSListStyleTypeValueImp::LowerRoman:
value = convertToRoman(i, lowerRoman);
break;
case CSSListStyleTypeValueImp::UpperRoman:
value = convertToRoman(i, upperRoman);
break;
case CSSListStyleTypeValueImp::Armenian:
case CSSListStyleTypeValueImp::Georgian:
default:
value = toString(i);
break;
}
return value;
}
}
void CounterImp::nest(int number)
{
counters.push_back(number);
}
void CounterImp::reset(int number)
{
if (counters.empty())
nest(number);
else
counters.back() = number;
}
void CounterImp::increment(int number)
{
assert(!counters.empty());
counters.back() += number;
}
bool CounterImp::restore()
{
counters.pop_back();
return counters.empty();
}
std::u16string CounterImp::eval(unsigned type, CSSAutoNumberingValueImp::CounterContext* context)
{
this->separator = u"";
this->listStyle.setValue(type);
if (counters.empty()) {
nest(0);
context->addCounter(this);
}
return emit(counters.back(), type);
}
std::u16string CounterImp::eval(const std::u16string& separator, unsigned type, CSSAutoNumberingValueImp::CounterContext* context)
{
this->separator = separator;
this->listStyle.setValue(type);
if (counters.empty()) {
nest(0);
context->addCounter(this);
}
std::u16string value;
for (auto i = counters.begin(); i != counters.end(); ++i) {
if (i != counters.begin())
value += separator;
value += emit(*i, type);
}
return value;
}
std::u16string CounterImp::getIdentifier()
{
return identifier;
}
std::u16string CounterImp::getListStyle()
{
return listStyle.getCssText();
}
std::u16string CounterImp::getSeparator()
{
return separator;
}
}
}
}
}
<commit_msg>(CounterImp::increment) : Fix a bug; cf. list-style-001.<commit_after>/*
* Copyright 2011, 2012 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 "CounterImp.h"
namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{
namespace {
struct AdditiveGlyph
{
int weight;
char16_t* glyph;
};
// 1 4999
AdditiveGlyph upperRoman[] =
{
1000, u"M",
900, u"CM",
500, u"D",
400, u"CD",
100, u"C",
90, u"XC",
50, u"L",
40, u"XL",
10, u"X",
9, u"IX",
5, u"V",
4, u"IV",
1, u"I",
0, 0
};
// 1 4999
AdditiveGlyph lowerRoman[] =
{
1000, u"m",
900, u"cm",
500, u"d",
400, u"cd",
100, u"c",
90, u"xc",
50, u"l",
40, u"xl",
10, u"x",
9, u"ix",
5, u"v",
4, u"iv",
1, u"i",
0, 0
};
std::u16string convertToRoman(int n, AdditiveGlyph* glyphList)
{
if (n < 0 || 5000 <= n)
return toString(n);
std::u16string value;
for (AdditiveGlyph* i = glyphList; i->glyph; ++i) {
int t = n / i->weight;
if (0 < t) {
n -= t * i->weight;
while (0 < t--)
value += i->glyph;
}
}
return value;
}
std::u16string emit(int i, unsigned type)
{
std::u16string value;
switch (type) {
case CSSListStyleTypeValueImp::None:
break;
case CSSListStyleTypeValueImp::Disc:
value = u"\u2022"; // •
break;
case CSSListStyleTypeValueImp::Circle:
value = u"\u25E6"; // ◦
break;
case CSSListStyleTypeValueImp::Square:
// Use u25A0 instead of u25FE for the IPA font for now
value = u"\u25A0"; // ◾ "\u25FE"
break;
case CSSListStyleTypeValueImp::Decimal:
value = toString(i);
break;
case CSSListStyleTypeValueImp::DecimalLeadingZero:
value = toString(i < 0 ? -i : i);
if (-9 <= i && i <= 9)
value = u"0" + value;
if (i < 0)
value = u"-" + value;
break;
case CSSListStyleTypeValueImp::LowerAlpha:
case CSSListStyleTypeValueImp::LowerLatin:
value = std::u16string(1, u'a' + static_cast<unsigned>(i) % 26 - 1);
break;
case CSSListStyleTypeValueImp::UpperAlpha:
case CSSListStyleTypeValueImp::UpperLatin:
value = std::u16string(1, u'A' + static_cast<unsigned>(i) % 26 - 1);
break;
case CSSListStyleTypeValueImp::LowerGreek:
// This style is only defined because CSS2.1 has it.
// It doesn't appear to actually be used in Greek texts.
value = std::u16string(1, u"αβγδεζηθικλμνξοπρστυφχψω"[static_cast<unsigned>(i - 1) % 24]);
break;
case CSSListStyleTypeValueImp::LowerRoman:
value = convertToRoman(i, lowerRoman);
break;
case CSSListStyleTypeValueImp::UpperRoman:
value = convertToRoman(i, upperRoman);
break;
case CSSListStyleTypeValueImp::Armenian:
case CSSListStyleTypeValueImp::Georgian:
default:
value = toString(i);
break;
}
return value;
}
}
void CounterImp::nest(int number)
{
counters.push_back(number);
}
void CounterImp::reset(int number)
{
if (counters.empty())
nest(number);
else
counters.back() = number;
}
void CounterImp::increment(int number)
{
if (counters.empty())
nest(0);
counters.back() += number;
}
bool CounterImp::restore()
{
counters.pop_back();
return counters.empty();
}
std::u16string CounterImp::eval(unsigned type, CSSAutoNumberingValueImp::CounterContext* context)
{
this->separator = u"";
this->listStyle.setValue(type);
if (counters.empty()) {
nest(0);
context->addCounter(this);
}
return emit(counters.back(), type);
}
std::u16string CounterImp::eval(const std::u16string& separator, unsigned type, CSSAutoNumberingValueImp::CounterContext* context)
{
this->separator = separator;
this->listStyle.setValue(type);
if (counters.empty()) {
nest(0);
context->addCounter(this);
}
std::u16string value;
for (auto i = counters.begin(); i != counters.end(); ++i) {
if (i != counters.begin())
value += separator;
value += emit(*i, type);
}
return value;
}
std::u16string CounterImp::getIdentifier()
{
return identifier;
}
std::u16string CounterImp::getListStyle()
{
return listStyle.getCssText();
}
std::u16string CounterImp::getSeparator()
{
return separator;
}
}
}
}
}
<|endoftext|> |
<commit_before>/*!
* Copyright (c) 2015 by Contributors
* \file fully_connected.cc
* \brief fully connect operator
*/
#include "./fully_connected-inl.h"
#if MXNET_USE_MKL2017 == 1
#include <mkl_memory.h>
#include "./mkl/mkl_memory-inl.h"
#include "./mkl/mkl_fully_connected-inl.h"
#endif // MXNET_USE_MKL2017
#if MXNET_USE_NNPACK == 1
#include "./nnpack/nnpack_fully_connected-inl.h"
#endif // MXNET_USE_NNPACK
namespace mxnet {
namespace op {
template<>
Operator* CreateOp<cpu>(FullyConnectedParam param, int dtype,
std::vector<TShape> *in_shape,
std::vector<TShape> *out_shape,
Context ctx) {
Operator *op = NULL;
#if MXNET_USE_MKL2017 == 1
switch (dtype) {
case mshadow::kFloat32:
return new MKLFullyConnectedOp<cpu, float>(param, *in_shape, *out_shape);
case mshadow::kFloat64:
return new MKLFullyConnectedOp<cpu, double>(param, *in_shape, *out_shape);
default:
LOG(INFO) << MKLFullyConnectedOp<cpu, float>::getName() << " Skip MKL optimization";
break;
}
#endif
#if MXNET_USE_NNPACK == 1
const size_t batch_size = (*in_shape)[0][0];
// nnp_fully_connected_inference will do optimization for batch-size = 1
// nnp_fully_connected_output will do optimization for batch-size > 1
switch (dtype) {
case mshadow::kFloat32:
return new NNPACKFullyConnectedOp<cpu, float>(param);
default:
break;
}
#endif
switch (dtype) {
case mshadow::kFloat32:
op = new FullyConnectedOp<cpu, float>(param);
break;
case mshadow::kFloat64:
op = new FullyConnectedOp<cpu, double>(param);
break;
case mshadow::kFloat16:
LOG(FATAL) << "float16 fully connected layer is currently"
"only supported by CuDNN version.";
break;
default:
LOG(FATAL) << "Unsupported type " << dtype;
}
return op;
}
// DO_BIND_DISPATCH comes from operator_common.h
Operator *FullyConnectedProp::CreateOperatorEx(Context ctx, std::vector<TShape> *in_shape,
std::vector<int> *in_type) const {
std::vector<TShape> out_shape(1, TShape()), aux_shape;
std::vector<int> out_type(1, -1), aux_type;
CHECK(InferType(in_type, &out_type, &aux_type));
CHECK(InferShape(in_shape, &out_shape, &aux_shape));
DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0], in_shape, &out_shape, ctx);
}
DMLC_REGISTER_PARAMETER(FullyConnectedParam);
MXNET_REGISTER_OP_PROPERTY(FullyConnected, FullyConnectedProp)
.describe(R"code(Apply a linear transformation: :math:`Y = XW^T + b`.
Shapes:
- **data**: `(batch_size, input_dim)`
- **weight**: `(num_hidden, input_dim)`
- **bias**: `(num_hidden,)`
- **out**: `(batch_size, num_hidden)`
The learnable parameters include both ``weight`` and ``bias``.
If ``no_bias`` is set to be true, then the ``bias`` term is ignored.
)code" ADD_FILELINE)
.add_argument("data", "NDArray-or-Symbol", "Input data.")
.add_argument("weight", "NDArray-or-Symbol", "Weight matrix.")
.add_argument("bias", "NDArray-or-Symbol", "Bias parameter.")
.add_arguments(FullyConnectedParam::__FIELDS__());
} // namespace op
} // namespace mxnet
<commit_msg>Remove MKL's fully connected layer for the convergence (#5768)<commit_after>/*!
* Copyright (c) 2015 by Contributors
* \file fully_connected.cc
* \brief fully connect operator
*/
#include "./fully_connected-inl.h"
#if MXNET_USE_NNPACK == 1
#include "./nnpack/nnpack_fully_connected-inl.h"
#endif // MXNET_USE_NNPACK
namespace mxnet {
namespace op {
template<>
Operator* CreateOp<cpu>(FullyConnectedParam param, int dtype,
std::vector<TShape> *in_shape,
std::vector<TShape> *out_shape,
Context ctx) {
Operator *op = NULL;
#if MXNET_USE_NNPACK == 1
const size_t batch_size = (*in_shape)[0][0];
// nnp_fully_connected_inference will do optimization for batch-size = 1
// nnp_fully_connected_output will do optimization for batch-size > 1
switch (dtype) {
case mshadow::kFloat32:
return new NNPACKFullyConnectedOp<cpu, float>(param);
default:
break;
}
#endif
switch (dtype) {
case mshadow::kFloat32:
op = new FullyConnectedOp<cpu, float>(param);
break;
case mshadow::kFloat64:
op = new FullyConnectedOp<cpu, double>(param);
break;
case mshadow::kFloat16:
LOG(FATAL) << "float16 fully connected layer is currently"
"only supported by CuDNN version.";
break;
default:
LOG(FATAL) << "Unsupported type " << dtype;
}
return op;
}
// DO_BIND_DISPATCH comes from operator_common.h
Operator *FullyConnectedProp::CreateOperatorEx(Context ctx, std::vector<TShape> *in_shape,
std::vector<int> *in_type) const {
std::vector<TShape> out_shape(1, TShape()), aux_shape;
std::vector<int> out_type(1, -1), aux_type;
CHECK(InferType(in_type, &out_type, &aux_type));
CHECK(InferShape(in_shape, &out_shape, &aux_shape));
DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0], in_shape, &out_shape, ctx);
}
DMLC_REGISTER_PARAMETER(FullyConnectedParam);
MXNET_REGISTER_OP_PROPERTY(FullyConnected, FullyConnectedProp)
.describe(R"code(Apply a linear transformation: :math:`Y = XW^T + b`.
Shapes:
- **data**: `(batch_size, input_dim)`
- **weight**: `(num_hidden, input_dim)`
- **bias**: `(num_hidden,)`
- **out**: `(batch_size, num_hidden)`
The learnable parameters include both ``weight`` and ``bias``.
If ``no_bias`` is set to be true, then the ``bias`` term is ignored.
)code" ADD_FILELINE)
.add_argument("data", "NDArray-or-Symbol", "Input data.")
.add_argument("weight", "NDArray-or-Symbol", "Weight matrix.")
.add_argument("bias", "NDArray-or-Symbol", "Bias parameter.")
.add_arguments(FullyConnectedParam::__FIELDS__());
} // namespace op
} // namespace mxnet
<|endoftext|> |
<commit_before>/*
* avsinfo.hpp
* Declarations of global objects and functions for meta informations
* Copyright (C) 2010 janus_wel<janus.wel.3@gmail.com>
* see LICENSE for redistributing, modifying, and so on.
* */
#ifndef AVSINFO_HPP
#define AVSINFO_HPP
#include <string>
// global object
// version number
extern const std::string version;
// return enumeration
enum {OK = 0, BAD_ARG, BAD_AVS, UNKNOWN};
// typical one
void usage(std::ostream& out);
// the another typical
void version_license(std::ostream& out);
#endif // AVSINFO_HPP
<commit_msg>Fix English<commit_after>/*
* avsinfo.hpp
* Declarations of global objects and functions for meta informations
* Copyright (C) 2010 janus_wel<janus.wel.3@gmail.com>
* see LICENSE for redistributing, modifying, and so on.
* */
#ifndef AVSINFO_HPP
#define AVSINFO_HPP
#include <string>
// global object
// version number
extern const std::string version;
// enumerations for return statements
enum {OK = 0, BAD_ARG, BAD_AVS, UNKNOWN};
// typical one
void usage(std::ostream& out);
// the another typical
void version_license(std::ostream& out);
#endif // AVSINFO_HPP
<|endoftext|> |
<commit_before>// Copyright 2015 Maurice Fallon
// Synchronized Stereo Translator
//
// TODO(tbd):
// rgb bgr conversion
// grey compression
// disparity/depth conversion from device
// rosparam set /compressed_listener/image_transport compressed; rosparam set /ros2lcm/stereo hand; rosrun translators ros2lcm_stereo __name:=ros2lcm_hand
// rosparam set /ros2lcm_head/image_transport compressed; rosparam set /ros2lcm/stereo head; rosrun translators ros2lcm_stereo __name:=ros2lcm_head
// rosparam set /compressed_listener/image_transport compressed
// rosrun translators my_subscriber __name:=compressed_listener
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <ros/ros.h>
#include <ros/console.h>
#include <cstdlib>
#include <sys/time.h>
#include <time.h>
#include <iostream>
#include <string>
#include <vector>
#include <message_filters/subscriber.h>
#include <message_filters/time_synchronizer.h>
#include <message_filters/synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <image_transport/image_transport.h>
#include <image_transport/subscriber_filter.h>
#include <image_geometry/stereo_camera_model.h>
#include <sensor_msgs/image_encodings.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/CameraInfo.h>
#include <sensor_msgs/Imu.h>
#include <std_msgs/Float64.h>
#include <lcm/lcm-cpp.hpp>
#include <lcmtypes/bot_core.hpp>
#include <opencv2/opencv.hpp>
using namespace std;
class App
{
public:
explicit App(ros::NodeHandle node_);
~App();
private:
lcm::LCM lcm_publish_;
ros::NodeHandle node_;
// Combined Stereo Image:
bot_core::images_t images_msg_out_;
bot_core::image_t image_a_lcm_;
bot_core::image_t image_b_lcm_;
void publishStereo(const sensor_msgs::ImageConstPtr& image_a_ros, const sensor_msgs::CameraInfoConstPtr& info_a_ros,
const sensor_msgs::ImageConstPtr& image_ros_b, const sensor_msgs::CameraInfoConstPtr& info_b_ros,
std::string camera_out);
image_transport::ImageTransport it_;
///////////////////////////////////////////////////////////////////////////////
void head_stereo_cb(const sensor_msgs::ImageConstPtr& image_a_ros, const sensor_msgs::CameraInfoConstPtr& info_cam_a,
const sensor_msgs::ImageConstPtr& image_ros_b, const sensor_msgs::CameraInfoConstPtr& info_cam_b);
image_transport::SubscriberFilter image_a_ros_sub_, image_b_ros_sub_;
message_filters::Subscriber<sensor_msgs::CameraInfo> info_a_ros_sub_, info_b_ros_sub_;
message_filters::TimeSynchronizer<sensor_msgs::Image, sensor_msgs::CameraInfo, sensor_msgs::Image,
sensor_msgs::CameraInfo> sync_;
bool do_jpeg_compress_;
int jpeg_quality_;
bool do_zlib_compress_;
int depth_compress_buf_size_;
uint8_t* depth_compress_buf_;
void prepImage(bot_core::image_t& lcm_image, const sensor_msgs::ImageConstPtr& ros_image);
};
App::App(ros::NodeHandle node_) :
node_(node_), it_(node_), sync_(10)
{
if (!lcm_publish_.good())
{
std::cerr << "ERROR: lcm is not good()" << std::endl;
}
std::string image_a_string, info_a_string, image_b_string, info_b_string;
std::string head_stereo_root = "";
image_a_string = head_stereo_root + "/left/image_rect_color";
info_a_string = image_a_string + "/camera_info";
// rim_string = head_stereo_root + "/right/image_rect_color";
image_b_string = head_stereo_root + "/right/image_rect";
info_b_string = image_b_string + "/camera_info";
cout << image_a_string << " is the image_a topic subscription [for stereo]\n";
image_a_ros_sub_.subscribe(it_, ros::names::resolve(image_a_string), 30);
info_a_ros_sub_.subscribe(node_, ros::names::resolve(info_a_string), 30);
image_b_ros_sub_.subscribe(it_, ros::names::resolve(image_b_string), 30);
info_b_ros_sub_.subscribe(node_, ros::names::resolve(info_b_string), 30);
sync_.connectInput(image_a_ros_sub_, info_a_ros_sub_, image_b_ros_sub_, info_b_ros_sub_);
sync_.registerCallback(boost::bind(&App::head_stereo_cb, this, _1, _2, _3, _4));
images_msg_out_.images.push_back(image_a_lcm_);
images_msg_out_.images.push_back(image_b_lcm_);
images_msg_out_.image_types.push_back(0);
images_msg_out_.image_types.push_back(2);
// bot_core::images_t::LEFT
// 0 left, 1 right, 2 DISPARITY, 3 maskzipped, 4 depth mm, 5 DISPARITY_ZIPPED, 6 DEPTH_MM_ZIPPED
// allocate space for zlib compressing depth data
depth_compress_buf_size_ = 800 * 800 * sizeof(int8_t) * 10;
depth_compress_buf_ = (uint8_t*)malloc(depth_compress_buf_size_);
do_jpeg_compress_ = true;
jpeg_quality_ = 95; // 95 is opencv default
do_zlib_compress_ = true;
}
App::~App()
{
}
int stereo_counter = 0;
void App::head_stereo_cb(const sensor_msgs::ImageConstPtr& image_a_ros,
const sensor_msgs::CameraInfoConstPtr& info_a_ros,
const sensor_msgs::ImageConstPtr& image_b_ros,
const sensor_msgs::CameraInfoConstPtr& info_b_ros)
{
int64_t current_utime = (int64_t)floor(image_a_ros->header.stamp.toNSec() / 1000);
publishStereo(image_a_ros, info_a_ros, image_b_ros, info_b_ros, "CAMERA");
if (stereo_counter % 30 == 0)
{
ROS_ERROR("HDCAM [%d]", stereo_counter);
}
stereo_counter++;
}
void App::publishStereo(const sensor_msgs::ImageConstPtr& image_a_ros,
const sensor_msgs::CameraInfoConstPtr& info_a_ros,
const sensor_msgs::ImageConstPtr& image_ros_b,
const sensor_msgs::CameraInfoConstPtr& info_b_ros, std::string camera_out)
{
prepImage(image_a_lcm_, image_a_ros);
prepImage(image_b_lcm_, image_ros_b);
images_msg_out_.images[0] = image_a_lcm_;
images_msg_out_.images[1] = image_b_lcm_;
images_msg_out_.image_types[0] = 0;
images_msg_out_.image_types[1] = 1;
images_msg_out_.n_images = images_msg_out_.images.size();
images_msg_out_.utime = (int64_t)floor(image_a_ros->header.stamp.toNSec() / 1000);
lcm_publish_.publish("CAMERA", &images_msg_out_);
return;
}
void App::prepImage(bot_core::image_t& lcm_image, const sensor_msgs::ImageConstPtr& ros_image)
{
int64_t current_utime = (int64_t)floor(ros_image->header.stamp.toNSec() / 1000);
lcm_image.utime = current_utime;
int isize = ros_image->width * ros_image->height;
int n_colors;
if ((ros_image->encoding.compare("mono8") == 0)
|| ((ros_image->encoding.compare("rgb8") == 0) || (ros_image->encoding.compare("bgr8") == 0)))
{
if (ros_image->encoding.compare("mono8") == 0)
{
n_colors = 1;
}
else if (ros_image->encoding.compare("rgb8") == 0)
{
n_colors = 3;
}
else if (ros_image->encoding.compare("bgr8") == 0)
{
n_colors = 3;
}
else
{
std::cout << "Encoding [" << ros_image->encoding << "] not supported\n";
exit(-1);
}
void* bytes = const_cast<void*>(static_cast<const void*>(ros_image->data.data()));
cv::Mat mat;
if (n_colors == 1)
{
mat = cv::Mat(ros_image->height, ros_image->width, CV_8UC1, bytes, n_colors * ros_image->width);
}
else if (n_colors == 3)
{
mat = cv::Mat(ros_image->height, ros_image->width, CV_8UC3, bytes, n_colors * ros_image->width);
}
else
{
std::cout << "Number of colors [" << n_colors << "] not supported\n";
exit(-1);
}
if (do_jpeg_compress_)
{
if (ros_image->encoding.compare("rgb8") == 0) // non intuative color flip needed here
cv::cvtColor(mat, mat, CV_BGR2RGB);
std::vector<int> params;
params.push_back(cv::IMWRITE_JPEG_QUALITY);
params.push_back(jpeg_quality_);
cv::imencode(".jpg", mat, lcm_image.data, params);
lcm_image.size = lcm_image.data.size();
lcm_image.pixelformat = bot_core::image_t::PIXEL_FORMAT_MJPEG;
}
else
{
if (ros_image->encoding.compare("bgr8") == 0)
cv::cvtColor(mat, mat, CV_BGR2RGB);
lcm_image.data.resize(n_colors * isize);
memcpy(&lcm_image.data[0], mat.data, n_colors * isize);
lcm_image.size = n_colors * isize;
if (n_colors == 1)
{
lcm_image.pixelformat = bot_core::image_t::PIXEL_FORMAT_GRAY;
}
else if (n_colors == 3)
{
lcm_image.pixelformat = bot_core::image_t::PIXEL_FORMAT_RGB;
}
else
{
std::cout << "Number of colors [" << n_colors << "] not supported\n";
exit(-1);
}
}
}
else if (1 == 2)
{
cout << ros_image->encoding << " | encoded not fully working - FIXME\n";
exit(-1);
return;
n_colors = 2; // 2 bytes per pixel
/*
int uncompressed_size = isize;
// Insert proper compression here if needed:
unsigned long compressed_size = depth_compress_buf_size_;
compress2( depth_compress_buf_, &compressed_size, (const Bytef*) imageDataP, uncompressed_size,
Z_BEST_SPEED);
lcm_image.data.resize(compressed_size);
*/
unsigned long zlib_compressed_size = 1000; // fake compressed size
lcm_image.data.resize(zlib_compressed_size);
lcm_image.size = zlib_compressed_size;
// images_msg_out_.image_types[1] = 5;// bot_core::images_t::DISPARITY_ZIPPED );
}
else
{
cout << ros_image->encoding << " | encoded not fully working - FIXME\n";
exit(-1);
return;
n_colors = 2; // 2 bytes per pixel
lcm_image.data.resize(2 * isize);
lcm_image.size = 2 * isize;
//images_msg_out_.image_types[1] = 2;// bot_core::images_t::DISPARITY );
}
lcm_image.width = ros_image->width;
lcm_image.height = ros_image->height;
lcm_image.nmetadata = 0;
lcm_image.row_stride = n_colors * ros_image->width;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "ros2lcm_stereo");
std::string which_camera = "head";
ros::NodeHandle nh;
// Disabled, originally used for jpeg-in-jpeg out:
/*
std::string which_transport;
which_transport = "/ros2lcm_head";
std::string transport;
if (nh.getParam(string( which_transport + "/image_transport"), transport)) {
std::cout << "transport is " << transport << "\n";
}
ROS_ERROR("Stereo Camera Translator: [%s] [%s]", which_camera.c_str() , transport.c_str());
*/
ROS_ERROR("Stereo Camera Translator: [%s]", which_camera.c_str());
new App(nh);
std::cout << "ros2lcm translator ready\n";
ros::spin();
return 0;
}
<commit_msg>less lint on stereo<commit_after>// Copyright 2015 Maurice Fallon
// Synchronized Stereo Translator
//
// TODO(tbd):
// rgb bgr conversion
// grey compression
// disparity/depth conversion from device
// rosparam set /compressed_listener/image_transport compressed; rosparam set /ros2lcm/stereo hand; rosrun translators ros2lcm_stereo __name:=ros2lcm_hand
// rosparam set /ros2lcm_head/image_transport compressed; rosparam set /ros2lcm/stereo head; rosrun translators ros2lcm_stereo __name:=ros2lcm_head
// rosparam set /compressed_listener/image_transport compressed
// rosrun translators my_subscriber __name:=compressed_listener
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <ros/ros.h>
#include <ros/console.h>
#include <cstdlib>
#include <sys/time.h>
#include <time.h>
#include <iostream>
#include <string>
#include <vector>
#include <message_filters/subscriber.h>
#include <message_filters/time_synchronizer.h>
#include <message_filters/synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <image_transport/image_transport.h>
#include <image_transport/subscriber_filter.h>
#include <image_geometry/stereo_camera_model.h>
#include <sensor_msgs/image_encodings.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/CameraInfo.h>
#include <sensor_msgs/Imu.h>
#include <std_msgs/Float64.h>
#include <lcm/lcm-cpp.hpp>
#include <lcmtypes/bot_core.hpp>
#include <opencv2/opencv.hpp>
class App
{
public:
explicit App(ros::NodeHandle node_);
~App();
private:
lcm::LCM lcm_publish_;
ros::NodeHandle node_;
// Combined Stereo Image:
bot_core::images_t images_msg_out_;
bot_core::image_t image_a_lcm_;
bot_core::image_t image_b_lcm_;
void publishStereo(const sensor_msgs::ImageConstPtr& image_a_ros, const sensor_msgs::CameraInfoConstPtr& info_a_ros,
const sensor_msgs::ImageConstPtr& image_ros_b, const sensor_msgs::CameraInfoConstPtr& info_b_ros,
std::string camera_out);
image_transport::ImageTransport it_;
///////////////////////////////////////////////////////////////////////////////
void head_stereo_cb(const sensor_msgs::ImageConstPtr& image_a_ros, const sensor_msgs::CameraInfoConstPtr& info_cam_a,
const sensor_msgs::ImageConstPtr& image_ros_b, const sensor_msgs::CameraInfoConstPtr& info_cam_b);
image_transport::SubscriberFilter image_a_ros_sub_, image_b_ros_sub_;
message_filters::Subscriber<sensor_msgs::CameraInfo> info_a_ros_sub_, info_b_ros_sub_;
message_filters::TimeSynchronizer<sensor_msgs::Image, sensor_msgs::CameraInfo, sensor_msgs::Image,
sensor_msgs::CameraInfo> sync_;
bool do_jpeg_compress_;
int jpeg_quality_;
bool do_zlib_compress_;
int depth_compress_buf_size_;
uint8_t* depth_compress_buf_;
void prepImage(bot_core::image_t& lcm_image, const sensor_msgs::ImageConstPtr& ros_image);
};
App::App(ros::NodeHandle node_) :
node_(node_), it_(node_), sync_(10)
{
if (!lcm_publish_.good())
{
std::cerr << "ERROR: lcm is not good()" << std::endl;
}
std::string image_a_string, info_a_string, image_b_string, info_b_string;
std::string head_stereo_root = "";
image_a_string = head_stereo_root + "/left/image_rect_color";
info_a_string = image_a_string + "/camera_info";
// rim_string = head_stereo_root + "/right/image_rect_color";
image_b_string = head_stereo_root + "/right/image_rect";
info_b_string = image_b_string + "/camera_info";
std::cout << image_a_string << " is the image_a topic subscription [for stereo]\n";
image_a_ros_sub_.subscribe(it_, ros::names::resolve(image_a_string), 30);
info_a_ros_sub_.subscribe(node_, ros::names::resolve(info_a_string), 30);
image_b_ros_sub_.subscribe(it_, ros::names::resolve(image_b_string), 30);
info_b_ros_sub_.subscribe(node_, ros::names::resolve(info_b_string), 30);
sync_.connectInput(image_a_ros_sub_, info_a_ros_sub_, image_b_ros_sub_, info_b_ros_sub_);
sync_.registerCallback(boost::bind(&App::head_stereo_cb, this, _1, _2, _3, _4));
images_msg_out_.images.push_back(image_a_lcm_);
images_msg_out_.images.push_back(image_b_lcm_);
images_msg_out_.image_types.push_back(0);
images_msg_out_.image_types.push_back(2);
// bot_core::images_t::LEFT
// 0 left, 1 right, 2 DISPARITY, 3 maskzipped, 4 depth mm, 5 DISPARITY_ZIPPED, 6 DEPTH_MM_ZIPPED
// allocate space for zlib compressing depth data
depth_compress_buf_size_ = 800 * 800 * sizeof(int8_t) * 10;
depth_compress_buf_ = (uint8_t*)malloc(depth_compress_buf_size_);
do_jpeg_compress_ = true;
jpeg_quality_ = 95; // 95 is opencv default
do_zlib_compress_ = true;
}
App::~App()
{
}
int stereo_counter = 0;
void App::head_stereo_cb(const sensor_msgs::ImageConstPtr& image_a_ros,
const sensor_msgs::CameraInfoConstPtr& info_a_ros,
const sensor_msgs::ImageConstPtr& image_b_ros,
const sensor_msgs::CameraInfoConstPtr& info_b_ros)
{
int64_t current_utime = (int64_t)floor(image_a_ros->header.stamp.toNSec() / 1000);
publishStereo(image_a_ros, info_a_ros, image_b_ros, info_b_ros, "CAMERA");
if (stereo_counter % 30 == 0)
{
ROS_ERROR("HDCAM [%d]", stereo_counter);
}
stereo_counter++;
}
void App::publishStereo(const sensor_msgs::ImageConstPtr& image_a_ros,
const sensor_msgs::CameraInfoConstPtr& info_a_ros,
const sensor_msgs::ImageConstPtr& image_ros_b,
const sensor_msgs::CameraInfoConstPtr& info_b_ros, std::string camera_out)
{
prepImage(image_a_lcm_, image_a_ros);
prepImage(image_b_lcm_, image_ros_b);
images_msg_out_.images[0] = image_a_lcm_;
images_msg_out_.images[1] = image_b_lcm_;
images_msg_out_.image_types[0] = 0;
images_msg_out_.image_types[1] = 1;
images_msg_out_.n_images = images_msg_out_.images.size();
images_msg_out_.utime = (int64_t)floor(image_a_ros->header.stamp.toNSec() / 1000);
lcm_publish_.publish("CAMERA", &images_msg_out_);
return;
}
void App::prepImage(bot_core::image_t& lcm_image, const sensor_msgs::ImageConstPtr& ros_image)
{
int64_t current_utime = (int64_t)floor(ros_image->header.stamp.toNSec() / 1000);
lcm_image.utime = current_utime;
int isize = ros_image->width * ros_image->height;
int n_colors;
if ((ros_image->encoding.compare("mono8") == 0)
|| ((ros_image->encoding.compare("rgb8") == 0) || (ros_image->encoding.compare("bgr8") == 0)))
{
if (ros_image->encoding.compare("mono8") == 0)
{
n_colors = 1;
}
else if (ros_image->encoding.compare("rgb8") == 0)
{
n_colors = 3;
}
else if (ros_image->encoding.compare("bgr8") == 0)
{
n_colors = 3;
}
else
{
std::cout << "Encoding [" << ros_image->encoding << "] not supported\n";
exit(-1);
}
void* bytes = const_cast<void*>(static_cast<const void*>(ros_image->data.data()));
cv::Mat mat;
if (n_colors == 1)
{
mat = cv::Mat(ros_image->height, ros_image->width, CV_8UC1, bytes, n_colors * ros_image->width);
}
else if (n_colors == 3)
{
mat = cv::Mat(ros_image->height, ros_image->width, CV_8UC3, bytes, n_colors * ros_image->width);
}
else
{
std::cout << "Number of colors [" << n_colors << "] not supported\n";
exit(-1);
}
if (do_jpeg_compress_)
{
if (ros_image->encoding.compare("rgb8") == 0) // non intuative color flip needed here
cv::cvtColor(mat, mat, CV_BGR2RGB);
std::vector<int> params;
params.push_back(cv::IMWRITE_JPEG_QUALITY);
params.push_back(jpeg_quality_);
cv::imencode(".jpg", mat, lcm_image.data, params);
lcm_image.size = lcm_image.data.size();
lcm_image.pixelformat = bot_core::image_t::PIXEL_FORMAT_MJPEG;
}
else
{
if (ros_image->encoding.compare("bgr8") == 0)
cv::cvtColor(mat, mat, CV_BGR2RGB);
lcm_image.data.resize(n_colors * isize);
memcpy(&lcm_image.data[0], mat.data, n_colors * isize);
lcm_image.size = n_colors * isize;
if (n_colors == 1)
{
lcm_image.pixelformat = bot_core::image_t::PIXEL_FORMAT_GRAY;
}
else if (n_colors == 3)
{
lcm_image.pixelformat = bot_core::image_t::PIXEL_FORMAT_RGB;
}
else
{
std::cout << "Number of colors [" << n_colors << "] not supported\n";
exit(-1);
}
}
}
else if (1 == 2)
{
std::cout << ros_image->encoding << " | encoded not fully working - FIXME\n";
exit(-1);
return;
n_colors = 2; // 2 bytes per pixel
/*
int uncompressed_size = isize;
// Insert proper compression here if needed:
unsigned long compressed_size = depth_compress_buf_size_;
compress2( depth_compress_buf_, &compressed_size, (const Bytef*) imageDataP, uncompressed_size,
Z_BEST_SPEED);
lcm_image.data.resize(compressed_size);
*/
unsigned long zlib_compressed_size = 1000; // fake compressed size
lcm_image.data.resize(zlib_compressed_size);
lcm_image.size = zlib_compressed_size;
// images_msg_out_.image_types[1] = 5;// bot_core::images_t::DISPARITY_ZIPPED );
}
else
{
std::cout << ros_image->encoding << " | encoded not fully working - FIXME\n";
exit(-1);
return;
n_colors = 2; // 2 bytes per pixel
lcm_image.data.resize(2 * isize);
lcm_image.size = 2 * isize;
//images_msg_out_.image_types[1] = 2;// bot_core::images_t::DISPARITY );
}
lcm_image.width = ros_image->width;
lcm_image.height = ros_image->height;
lcm_image.nmetadata = 0;
lcm_image.row_stride = n_colors * ros_image->width;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "ros2lcm_stereo");
std::string which_camera = "head";
ros::NodeHandle nh;
// Disabled, originally used for jpeg-in-jpeg out:
/*
std::string which_transport;
which_transport = "/ros2lcm_head";
std::string transport;
if (nh.getParam(std::string( which_transport + "/image_transport"), transport)) {
std::cout << "transport is " << transport << "\n";
}
ROS_ERROR("Stereo Camera Translator: [%s] [%s]", which_camera.c_str() , transport.c_str());
*/
ROS_ERROR("Stereo Camera Translator: [%s]", which_camera.c_str());
new App(nh);
std::cout << "ros2lcm translator ready\n";
ros::spin();
return 0;
}
<|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.
*/
#pragma once
#define GRAPHENE_SYMBOL "BTS"
#define GRAPHENE_ADDRESS_PREFIX "BTS"
#define GRAPHENE_MIN_ACCOUNT_NAME_LENGTH 1
#define GRAPHENE_MAX_ACCOUNT_NAME_LENGTH 63
#define GRAPHENE_MIN_ASSET_SYMBOL_LENGTH 3
#define GRAPHENE_MAX_ASSET_SYMBOL_LENGTH 16
#define GRAPHENE_MAX_SHARE_SUPPLY int64_t(1000000000000000ll)
#define GRAPHENE_MAX_SIG_CHECK_DEPTH 2
/**
* Don't allow the committee_members to publish a limit that would
* make the network unable to operate.
*/
#define GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT 1024
#define GRAPHENE_MIN_BLOCK_INTERVAL 1 /* seconds */
#define GRAPHENE_MAX_BLOCK_INTERVAL 30 /* seconds */
#define GRAPHENE_DEFAULT_BLOCK_INTERVAL 5 /* seconds */
#define GRAPHENE_DEFAULT_MAX_TRANSACTION_SIZE 2048
#define GRAPHENE_DEFAULT_MAX_BLOCK_SIZE (2*1000*1000) /* < 2 MiB (less than MAX_MESSAGE_SIZE in graphene/net/config.hpp) */
#define GRAPHENE_DEFAULT_MAX_TIME_UNTIL_EXPIRATION (60*60*24) // seconds, aka: 1 day
#define GRAPHENE_DEFAULT_MAINTENANCE_INTERVAL (60*60*24) // seconds, aka: 1 day
#define GRAPHENE_DEFAULT_MAINTENANCE_SKIP_SLOTS 3 // number of slots to skip for maintenance interval
#define GRAPHENE_MIN_UNDO_HISTORY 10
#define GRAPHENE_MAX_UNDO_HISTORY 10000
#define GRAPHENE_MIN_BLOCK_SIZE_LIMIT (GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT*5) // 5 transactions per block
#define GRAPHENE_BLOCKCHAIN_PRECISION uint64_t( 100000 )
#define GRAPHENE_BLOCKCHAIN_PRECISION_DIGITS 5
/** percentage fields are fixed point with a denominator of 10,000 */
#define GRAPHENE_100_PERCENT 10000
#define GRAPHENE_1_PERCENT (GRAPHENE_100_PERCENT/100)
/** NOTE: making this a power of 2 (say 2^15) would greatly accelerate fee calcs */
#define GRAPHENE_MAX_MARKET_FEE_PERCENT GRAPHENE_100_PERCENT
#define GRAPHENE_DEFAULT_FORCE_SETTLEMENT_DELAY (60*60*24) ///< 1 day
#define GRAPHENE_DEFAULT_FORCE_SETTLEMENT_OFFSET 0 ///< 1%
#define GRAPHENE_DEFAULT_FORCE_SETTLEMENT_MAX_VOLUME (20* GRAPHENE_1_PERCENT) ///< 20%
#define GRAPHENE_DEFAULT_PRICE_FEED_LIFETIME (60*60*24) ///< 1 day
#define GRAPHENE_DEFAULT_MAX_AUTHORITY_MEMBERSHIP 10
#define GRAPHENE_DEFAULT_MAX_ASSET_WHITELIST_AUTHORITIES 10
#define GRAPHENE_DEFAULT_MAX_ASSET_FEED_PUBLISHERS 10
/**
* These ratios are fixed point numbers with a denominator of GRAPHENE_COLLATERAL_RATIO_DENOM, the
* minimum maitenance collateral is therefore 1.001x and the default
* maintenance ratio is 1.75x
*/
///@{
#define GRAPHENE_COLLATERAL_RATIO_DENOM 1000
#define GRAPHENE_MIN_COLLATERAL_RATIO 1001 ///< lower than this could result in divide by 0
#define GRAPHENE_MAX_COLLATERAL_RATIO 32000 ///< higher than this is unnecessary and may exceed int16 storage
#define GRAPHENE_DEFAULT_MAINTENANCE_COLLATERAL_RATIO 1750 ///< Call when collateral only pays off 175% the debt
#define GRAPHENE_DEFAULT_MAX_SHORT_SQUEEZE_RATIO 1500 ///< Stop calling when collateral only pays off 150% of the debt
///@}
#define GRAPHENE_DEFAULT_MARGIN_PERIOD_SEC (30*60*60*24)
#define GRAPHENE_DEFAULT_MIN_WITNESS_COUNT (11)
#define GRAPHENE_DEFAULT_MIN_COMMITTEE_MEMBER_COUNT (11)
#define GRAPHENE_DEFAULT_MAX_WITNESSES (1001) // SHOULD BE ODD
#define GRAPHENE_DEFAULT_MAX_COMMITTEE (1001) // SHOULD BE ODD
#define GRAPHENE_DEFAULT_MAX_PROPOSAL_LIFETIME_SEC (60*60*24*7*4) // Four weeks
#define GRAPHENE_DEFAULT_COMMITTEE_PROPOSAL_REVIEW_PERIOD_SEC (60*60*24*7*2) // Two weeks
#define GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE (20*GRAPHENE_1_PERCENT)
#define GRAPHENE_DEFAULT_LIFETIME_REFERRER_PERCENT_OF_FEE (30*GRAPHENE_1_PERCENT)
#define GRAPHENE_DEFAULT_CASHBACK_VESTING_PERIOD_SEC (60*60*24*365) ///< 1 year
#define GRAPHENE_DEFAULT_CASHBACK_VESTING_THRESHOLD (GRAPHENE_BLOCKCHAIN_PRECISION*int64_t(100))
#define GRAPHENE_DEFAULT_BURN_PERCENT_OF_FEE (20*GRAPHENE_1_PERCENT)
#define GRAPHENE_DEFAULT_MAX_ASSERT_OPCODE 1
#define GRAPHENE_DEFAULT_FEE_LIQUIDATION_THRESHOLD GRAPHENE_BLOCKCHAIN_PRECISION * 100;
#define GRAPHENE_DEFAULT_ACCOUNTS_PER_FEE_SCALE 1000
#define GRAPHENE_DEFAULT_ACCOUNT_FEE_SCALE_BITSHIFTS 4
#define GRAPHENE_DEFAULT_MAX_BUYBACK_MARKETS 4
#define GRAPHENE_MAX_WORKER_NAME_LENGTH 63
#define GRAPHENE_MAX_URL_LENGTH 127
/**
* every second, the fraction of burned core asset which cycles is
* GRAPHENE_CORE_ASSET_CYCLE_RATE / (1 << GRAPHENE_CORE_ASSET_CYCLE_RATE_BITS)
*/
#define GRAPHENE_CORE_ASSET_CYCLE_RATE 17
#define GRAPHENE_CORE_ASSET_CYCLE_RATE_BITS 32
#define GRAPHENE_DEFAULT_WITNESS_PAY_PER_BLOCK (GRAPHENE_BLOCKCHAIN_PRECISION * int64_t( 10) )
#define GRAPHENE_DEFAULT_WITNESS_PAY_VESTING_SECONDS (60*60*24)
#define GRAPHENE_DEFAULT_WORKER_BUDGET_PER_DAY (GRAPHENE_BLOCKCHAIN_PRECISION * int64_t(500) * 1000 )
#define GRAPHENE_DEFAULT_MINIMUM_FEEDS 7
#define GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT 4
#define GRAPHENE_RECENTLY_MISSED_COUNT_DECREMENT 3
#define GRAPHENE_CURRENT_DB_VERSION "BTS2.18"
#define GRAPHENE_IRREVERSIBLE_THRESHOLD (70 * GRAPHENE_1_PERCENT)
/**
* Reserved Account IDs with special meaning
*/
///@{
/// Represents the current committee members, two-week review period
#define GRAPHENE_COMMITTEE_ACCOUNT (graphene::chain::account_id_type(0))
/// Represents the current witnesses
#define GRAPHENE_WITNESS_ACCOUNT (graphene::chain::account_id_type(1))
/// Represents the current committee members
#define GRAPHENE_RELAXED_COMMITTEE_ACCOUNT (graphene::chain::account_id_type(2))
/// Represents the canonical account with NO authority (nobody can access funds in null account)
#define GRAPHENE_NULL_ACCOUNT (graphene::chain::account_id_type(3))
/// Represents the canonical account with WILDCARD authority (anybody can access funds in temp account)
#define GRAPHENE_TEMP_ACCOUNT (graphene::chain::account_id_type(4))
/// Represents the canonical account for specifying you will vote directly (as opposed to a proxy)
#define GRAPHENE_PROXY_TO_SELF_ACCOUNT (graphene::chain::account_id_type(5))
/// Sentinel value used in the scheduler.
#define GRAPHENE_NULL_WITNESS (graphene::chain::witness_id_type(0))
///@}
#define GRAPHENE_FBA_STEALTH_DESIGNATED_ASSET (asset_id_type(743))
#define GRAPHENE_MAX_NESTED_OBJECTS (200)
<commit_msg>bump database<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.
*/
#pragma once
#define GRAPHENE_SYMBOL "BTS"
#define GRAPHENE_ADDRESS_PREFIX "BTS"
#define GRAPHENE_MIN_ACCOUNT_NAME_LENGTH 1
#define GRAPHENE_MAX_ACCOUNT_NAME_LENGTH 63
#define GRAPHENE_MIN_ASSET_SYMBOL_LENGTH 3
#define GRAPHENE_MAX_ASSET_SYMBOL_LENGTH 16
#define GRAPHENE_MAX_SHARE_SUPPLY int64_t(1000000000000000ll)
#define GRAPHENE_MAX_SIG_CHECK_DEPTH 2
/**
* Don't allow the committee_members to publish a limit that would
* make the network unable to operate.
*/
#define GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT 1024
#define GRAPHENE_MIN_BLOCK_INTERVAL 1 /* seconds */
#define GRAPHENE_MAX_BLOCK_INTERVAL 30 /* seconds */
#define GRAPHENE_DEFAULT_BLOCK_INTERVAL 5 /* seconds */
#define GRAPHENE_DEFAULT_MAX_TRANSACTION_SIZE 2048
#define GRAPHENE_DEFAULT_MAX_BLOCK_SIZE (2*1000*1000) /* < 2 MiB (less than MAX_MESSAGE_SIZE in graphene/net/config.hpp) */
#define GRAPHENE_DEFAULT_MAX_TIME_UNTIL_EXPIRATION (60*60*24) // seconds, aka: 1 day
#define GRAPHENE_DEFAULT_MAINTENANCE_INTERVAL (60*60*24) // seconds, aka: 1 day
#define GRAPHENE_DEFAULT_MAINTENANCE_SKIP_SLOTS 3 // number of slots to skip for maintenance interval
#define GRAPHENE_MIN_UNDO_HISTORY 10
#define GRAPHENE_MAX_UNDO_HISTORY 10000
#define GRAPHENE_MIN_BLOCK_SIZE_LIMIT (GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT*5) // 5 transactions per block
#define GRAPHENE_BLOCKCHAIN_PRECISION uint64_t( 100000 )
#define GRAPHENE_BLOCKCHAIN_PRECISION_DIGITS 5
/** percentage fields are fixed point with a denominator of 10,000 */
#define GRAPHENE_100_PERCENT 10000
#define GRAPHENE_1_PERCENT (GRAPHENE_100_PERCENT/100)
/** NOTE: making this a power of 2 (say 2^15) would greatly accelerate fee calcs */
#define GRAPHENE_MAX_MARKET_FEE_PERCENT GRAPHENE_100_PERCENT
#define GRAPHENE_DEFAULT_FORCE_SETTLEMENT_DELAY (60*60*24) ///< 1 day
#define GRAPHENE_DEFAULT_FORCE_SETTLEMENT_OFFSET 0 ///< 1%
#define GRAPHENE_DEFAULT_FORCE_SETTLEMENT_MAX_VOLUME (20* GRAPHENE_1_PERCENT) ///< 20%
#define GRAPHENE_DEFAULT_PRICE_FEED_LIFETIME (60*60*24) ///< 1 day
#define GRAPHENE_DEFAULT_MAX_AUTHORITY_MEMBERSHIP 10
#define GRAPHENE_DEFAULT_MAX_ASSET_WHITELIST_AUTHORITIES 10
#define GRAPHENE_DEFAULT_MAX_ASSET_FEED_PUBLISHERS 10
/**
* These ratios are fixed point numbers with a denominator of GRAPHENE_COLLATERAL_RATIO_DENOM, the
* minimum maitenance collateral is therefore 1.001x and the default
* maintenance ratio is 1.75x
*/
///@{
#define GRAPHENE_COLLATERAL_RATIO_DENOM 1000
#define GRAPHENE_MIN_COLLATERAL_RATIO 1001 ///< lower than this could result in divide by 0
#define GRAPHENE_MAX_COLLATERAL_RATIO 32000 ///< higher than this is unnecessary and may exceed int16 storage
#define GRAPHENE_DEFAULT_MAINTENANCE_COLLATERAL_RATIO 1750 ///< Call when collateral only pays off 175% the debt
#define GRAPHENE_DEFAULT_MAX_SHORT_SQUEEZE_RATIO 1500 ///< Stop calling when collateral only pays off 150% of the debt
///@}
#define GRAPHENE_DEFAULT_MARGIN_PERIOD_SEC (30*60*60*24)
#define GRAPHENE_DEFAULT_MIN_WITNESS_COUNT (11)
#define GRAPHENE_DEFAULT_MIN_COMMITTEE_MEMBER_COUNT (11)
#define GRAPHENE_DEFAULT_MAX_WITNESSES (1001) // SHOULD BE ODD
#define GRAPHENE_DEFAULT_MAX_COMMITTEE (1001) // SHOULD BE ODD
#define GRAPHENE_DEFAULT_MAX_PROPOSAL_LIFETIME_SEC (60*60*24*7*4) // Four weeks
#define GRAPHENE_DEFAULT_COMMITTEE_PROPOSAL_REVIEW_PERIOD_SEC (60*60*24*7*2) // Two weeks
#define GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE (20*GRAPHENE_1_PERCENT)
#define GRAPHENE_DEFAULT_LIFETIME_REFERRER_PERCENT_OF_FEE (30*GRAPHENE_1_PERCENT)
#define GRAPHENE_DEFAULT_CASHBACK_VESTING_PERIOD_SEC (60*60*24*365) ///< 1 year
#define GRAPHENE_DEFAULT_CASHBACK_VESTING_THRESHOLD (GRAPHENE_BLOCKCHAIN_PRECISION*int64_t(100))
#define GRAPHENE_DEFAULT_BURN_PERCENT_OF_FEE (20*GRAPHENE_1_PERCENT)
#define GRAPHENE_DEFAULT_MAX_ASSERT_OPCODE 1
#define GRAPHENE_DEFAULT_FEE_LIQUIDATION_THRESHOLD GRAPHENE_BLOCKCHAIN_PRECISION * 100;
#define GRAPHENE_DEFAULT_ACCOUNTS_PER_FEE_SCALE 1000
#define GRAPHENE_DEFAULT_ACCOUNT_FEE_SCALE_BITSHIFTS 4
#define GRAPHENE_DEFAULT_MAX_BUYBACK_MARKETS 4
#define GRAPHENE_MAX_WORKER_NAME_LENGTH 63
#define GRAPHENE_MAX_URL_LENGTH 127
/**
* every second, the fraction of burned core asset which cycles is
* GRAPHENE_CORE_ASSET_CYCLE_RATE / (1 << GRAPHENE_CORE_ASSET_CYCLE_RATE_BITS)
*/
#define GRAPHENE_CORE_ASSET_CYCLE_RATE 17
#define GRAPHENE_CORE_ASSET_CYCLE_RATE_BITS 32
#define GRAPHENE_DEFAULT_WITNESS_PAY_PER_BLOCK (GRAPHENE_BLOCKCHAIN_PRECISION * int64_t( 10) )
#define GRAPHENE_DEFAULT_WITNESS_PAY_VESTING_SECONDS (60*60*24)
#define GRAPHENE_DEFAULT_WORKER_BUDGET_PER_DAY (GRAPHENE_BLOCKCHAIN_PRECISION * int64_t(500) * 1000 )
#define GRAPHENE_DEFAULT_MINIMUM_FEEDS 7
#define GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT 4
#define GRAPHENE_RECENTLY_MISSED_COUNT_DECREMENT 3
#define GRAPHENE_CURRENT_DB_VERSION "BTS2.19"
#define GRAPHENE_IRREVERSIBLE_THRESHOLD (70 * GRAPHENE_1_PERCENT)
/**
* Reserved Account IDs with special meaning
*/
///@{
/// Represents the current committee members, two-week review period
#define GRAPHENE_COMMITTEE_ACCOUNT (graphene::chain::account_id_type(0))
/// Represents the current witnesses
#define GRAPHENE_WITNESS_ACCOUNT (graphene::chain::account_id_type(1))
/// Represents the current committee members
#define GRAPHENE_RELAXED_COMMITTEE_ACCOUNT (graphene::chain::account_id_type(2))
/// Represents the canonical account with NO authority (nobody can access funds in null account)
#define GRAPHENE_NULL_ACCOUNT (graphene::chain::account_id_type(3))
/// Represents the canonical account with WILDCARD authority (anybody can access funds in temp account)
#define GRAPHENE_TEMP_ACCOUNT (graphene::chain::account_id_type(4))
/// Represents the canonical account for specifying you will vote directly (as opposed to a proxy)
#define GRAPHENE_PROXY_TO_SELF_ACCOUNT (graphene::chain::account_id_type(5))
/// Sentinel value used in the scheduler.
#define GRAPHENE_NULL_WITNESS (graphene::chain::witness_id_type(0))
///@}
#define GRAPHENE_FBA_STEALTH_DESIGNATED_ASSET (asset_id_type(743))
#define GRAPHENE_MAX_NESTED_OBJECTS (200)
<|endoftext|> |
<commit_before>#include "compiler/rewriter/rules/ruleset.h"
#include "context/static_context.h"
#include "types/root_typemanager.h"
#include "types/typemanager.h"
#include "system/globalenv.h"
#define LOOKUP_FN( pfx, local, arity ) static_cast<function *> (rCtx.getStaticContext()->lookup_fn (pfx, local, arity))
#define LOOKUP_OP1( local ) static_cast<function *> (rCtx.getStaticContext()->lookup_builtin_fn (":" local, 1))
using namespace std;
namespace zorba {
RULE_REWRITE_PRE(EliminateTypeEnforcingOperations)
{
TypeManager *ts = rCtx.getStaticContext()->get_typemanager();
fo_expr *fo;
if ((fo = dynamic_cast<fo_expr *>(node)) != NULL) {
function *fnboolen = LOOKUP_FN("fn", "boolean", 1);
if (fo->get_func() == fnboolen) {
expr_t arg = (*fo)[0];
xqtref_t arg_type = arg->return_type(rCtx.getStaticContext());
if (ts->is_subtype(*arg_type, *GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE)) {
return arg;
}
}
function *fndata = LOOKUP_FN("fn", "data", 1);
if (fo->get_func() == fndata) {
expr_t arg = (*fo)[0];
xqtref_t arg_type = arg->return_type(rCtx.getStaticContext());
if (ts->is_subtype(*arg_type, *GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR)) {
return arg;
}
}
}
cast_base_expr *pe;
if ((pe = dynamic_cast<cast_base_expr *>(node)) != NULL) {
expr_t arg = pe->get_input();
xqtref_t arg_type = arg->return_type(rCtx.getStaticContext());
if (ts->is_subtype(*arg_type, *pe->get_target_type())) {
return arg;
}
}
return NULL;
}
RULE_REWRITE_POST(EliminateTypeEnforcingOperations)
{
return NULL;
}
}
/* vim:set ts=2 sw=2: */
<commit_msg>type_rules rewriter: eliminate castable's<commit_after>#include "compiler/rewriter/rules/ruleset.h"
#include "context/static_context.h"
#include "types/root_typemanager.h"
#include "types/typemanager.h"
#include "system/globalenv.h"
#define LOOKUP_FN( pfx, local, arity ) static_cast<function *> (rCtx.getStaticContext()->lookup_fn (pfx, local, arity))
#define LOOKUP_OP1( local ) static_cast<function *> (rCtx.getStaticContext()->lookup_builtin_fn (":" local, 1))
using namespace std;
namespace zorba {
RULE_REWRITE_PRE(EliminateTypeEnforcingOperations)
{
TypeManager *ts = rCtx.getStaticContext()->get_typemanager();
fo_expr *fo;
if ((fo = dynamic_cast<fo_expr *>(node)) != NULL) {
function *fnboolean = LOOKUP_FN("fn", "boolean", 1);
if (fo->get_func() == fnboolean) {
expr_t arg = (*fo)[0];
xqtref_t arg_type = arg->return_type(rCtx.getStaticContext());
if (ts->is_subtype(*arg_type, *GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE))
return arg;
else return NULL;
}
function *fndata = LOOKUP_FN("fn", "data", 1);
if (fo->get_func() == fndata) {
expr_t arg = (*fo)[0];
xqtref_t arg_type = arg->return_type(rCtx.getStaticContext());
if (ts->is_subtype(*arg_type, *GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR))
return arg;
else return NULL;
}
}
cast_base_expr *pe;
if ((pe = dynamic_cast<cast_base_expr *>(node)) != NULL) {
expr_t arg = pe->get_input();
xqtref_t arg_type = arg->return_type(rCtx.getStaticContext());
if (ts->is_subtype(*arg_type, *pe->get_target_type()))
return arg;
else return NULL;
}
castable_base_expr *cbe;
if ((cbe = dynamic_cast<castable_base_expr *>(node)) != NULL) {
expr_t arg = cbe->get_expr();
xqtref_t arg_type = arg->return_type(rCtx.getStaticContext());
if (ts->is_subtype(*arg_type, *cbe->get_type()))
return new const_expr (node->get_loc (), true);
else return NULL;
}
return NULL;
}
RULE_REWRITE_POST(EliminateTypeEnforcingOperations)
{
return NULL;
}
}
/* vim:set ts=2 sw=2: */
<|endoftext|> |
<commit_before>#include "read.h"
#include <boost/dynamic_bitset.hpp>
#include <numeric>
std::string ReadBase::bit_to_str(const BitSet &bits) {
size_t str_len = bits.size()/2;
std::string out;
out.resize(str_len);
size_t i = bits.size() -1;
for(size_t stridx = 0; stridx < str_len; ++stridx) {
if (bits[i] == 0 && bits[i-1] == 0) {
out[stridx] = 'A';
} else if (bits[i] == 0 && bits[i-1] == 1) {
out[stridx] = 'C';
} else if (bits[i] == 1 && bits[i-1] == 0) {
out[stridx] = 'G';
} else {
out[stridx] = 'T';
}
i -= 2;
}
return out;
}
// Read
Read Read::subread(size_t _start, size_t _length){
return Read(seq.substr(_start, _length), qual.substr(_start,_length), id);
}
std::string Read::subseq(size_t _start, size_t _length){
return seq.substr(_start, _length);
}
//PairedEndRead
boost::optional<BitSet> PairedEndRead::get_key(size_t _start, size_t _length){
if (one.getLength() <= (_start+_length) || two.getLength() <= (_start+_length)){
return boost::none;
} else {
return std::max(str_to_bit(one.subseq(_start, _length) + two.subseq(_start, _length)),
str_to_bit(two.subseq(_start, _length) + one.subseq(_start, _length)));
}
}
boost::optional<BitSet> ReadBase::reverse_complement(const std::string& str, int start, int length) {
auto rstart = str.rbegin() + start;
auto rend = str.rbegin() + start + length;
auto rv = str_to_bit(std::string(rstart, rend));
if (rv) {
return ~(*rv);
} else {
return rv;
}
}
//SingleEndRead
boost::optional<BitSet> SingleEndRead::get_key(size_t _start, size_t _length){
//The C ensures no PE and SE are mapped to the same location
if (one.getLength() <= (_start+_length*2)){
return boost::none;
} else {
return str_to_bit("C" + one.subseq(_start, _length*2));
}
}
inline double qual_sum(double s, const char c) {
return (double(c) - 33) + s; //need ascii offset
}
double SingleEndRead::avg_q_score()
{
double sum = std::accumulate(one.get_qual().begin(), one.get_qual().end(), double(0), qual_sum);
return sum/double(one.get_qual().length());
}
double PairedEndRead::avg_q_score()
{
double sum = std::accumulate(one.get_qual().begin(), one.get_qual().end(), double(0), qual_sum);
sum += std::accumulate(one.get_qual().begin(), one.get_qual().end(), double(0), qual_sum);
return sum/double(one.get_qual().length() + two.get_qual().length());
}
char Read::complement(char bp) {
switch(bp) {
case 'A':
return 'T';
case 'T':
return 'A';
case 'G':
return 'C';
case 'C':
return 'G';
}
return 'N';
}
<commit_msg>change or to min<commit_after>#include "read.h"
#include <boost/dynamic_bitset.hpp>
#include <numeric>
std::string ReadBase::bit_to_str(const BitSet &bits) {
size_t str_len = bits.size()/2;
std::string out;
out.resize(str_len);
size_t i = bits.size() -1;
for(size_t stridx = 0; stridx < str_len; ++stridx) {
if (bits[i] == 0 && bits[i-1] == 0) {
out[stridx] = 'A';
} else if (bits[i] == 0 && bits[i-1] == 1) {
out[stridx] = 'C';
} else if (bits[i] == 1 && bits[i-1] == 0) {
out[stridx] = 'G';
} else {
out[stridx] = 'T';
}
i -= 2;
}
return out;
}
// Read
Read Read::subread(size_t _start, size_t _length){
return Read(seq.substr(_start, _length), qual.substr(_start,_length), id);
}
std::string Read::subseq(size_t _start, size_t _length){
return seq.substr(_start, _length);
}
//PairedEndRead
boost::optional<BitSet> PairedEndRead::get_key(size_t _start, size_t _length){
if (std::min(one.getLength(), two.getLength()) <= _start+_length){
return boost::none;
} else {
return std::max(str_to_bit(one.subseq(_start, _length) + two.subseq(_start, _length)),
str_to_bit(two.subseq(_start, _length) + one.subseq(_start, _length)));
}
}
boost::optional<BitSet> ReadBase::reverse_complement(const std::string& str, int start, int length) {
auto rstart = str.rbegin() + start;
auto rend = str.rbegin() + start + length;
auto rv = str_to_bit(std::string(rstart, rend));
if (rv) {
return ~(*rv);
} else {
return rv;
}
}
//SingleEndRead
boost::optional<BitSet> SingleEndRead::get_key(size_t _start, size_t _length){
//The C ensures no PE and SE are mapped to the same location
if (one.getLength() <= (_start+_length*2)){
return boost::none;
} else {
return str_to_bit("C" + one.subseq(_start, _length*2));
}
}
inline double qual_sum(double s, const char c) {
return (double(c) - 33) + s; //need ascii offset
}
double SingleEndRead::avg_q_score()
{
double sum = std::accumulate(one.get_qual().begin(), one.get_qual().end(), double(0), qual_sum);
return sum/double(one.get_qual().length());
}
double PairedEndRead::avg_q_score()
{
double sum = std::accumulate(one.get_qual().begin(), one.get_qual().end(), double(0), qual_sum);
sum += std::accumulate(one.get_qual().begin(), one.get_qual().end(), double(0), qual_sum);
return sum/double(one.get_qual().length() + two.get_qual().length());
}
char Read::complement(char bp) {
switch(bp) {
case 'A':
return 'T';
case 'T':
return 'A';
case 'G':
return 'C';
case 'C':
return 'G';
}
return 'N';
}
<|endoftext|> |
<commit_before>/*
* This file is part of CSSTidy.
*
* CSSTidy 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.
*
* CSSTidy 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 CSSTidy; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "csspp_globals.hpp"
using namespace std;
extern vector<string> number_values,color_values;
extern map<string,string> replace_colors,all_properties;
string shorthand(string value)
{
string important = "";
if(is_important(value))
{
value = gvw_important(value);
important = " !important";
}
vector<string> values = explode(" ",value);
switch(values.size())
{
case 4:
if(values[0] == values[1] && values[0] == values[2] && values[0] == values[3])
{
return values[0] + important;
}
else if(values[1] == values[3] && values[0] == values[2])
{
return values[0] + " " + values[1] + important;
}
else if(values[1] == values[3])
{
return values[0] + " " + values[1] + " " + values[2] + important;
}
else return value + important;
break;
case 3:
if(values[0] == values[1] && values[0] == values[2])
{
return values[0] + important;
}
else if(values[0] == values[2])
{
return values[0] + " " + values[1] + important;
}
else return value + important;
break;
case 2:
if(values[0] == values[1])
{
return values[0] + important;
}
else return value + important;
break;
default:
return value + important;
}
}
string compress_numbers(string subvalue, string property)
{
string units[] = {"in", "cm", "mm", "pt", "pc", "px", "rem", "%", "ex", "gd", "em", "vw", "vh",
"vm", "deg", "grad", "rad", "ms", "s", "khz", "hz" }; // sync for loop
vector<string> temp;
if(property == "font")
{
temp = explode("/",subvalue);
}
else
{
temp.push_back(subvalue);
}
for (int i = 0; i < temp.size(); ++i)
{
if(!(temp[i].length() > 0 && (ctype_digit(temp[i][0]) || temp[i][0] == '+' || temp[i][0] == '-' ) ))
{
continue;
}
if(in_str_array(color_values,property))
{
temp[i] = "#" + temp[i];
}
if(str2f(temp[i]) == 0)
{
temp[i] = "0";
}
else
{
bool unit_found = false;
temp[i] = strtolower(temp[i]);
for(int j = 0; j < 21; ++j )
{
if(temp[i].find(units[j]) != string::npos)
{
temp[i] = f2str(str2f(temp[i])) + units[j];
unit_found = true;
break;
}
}
if(!unit_found && !in_str_array(number_values,property))
{
temp[i] = f2str(str2f(temp[i]));
temp[i] += "px";
}
else if(!unit_found)
{
temp[i] = f2str(str2f(temp[i]));
}
}
}
return (temp.size() > 1) ? temp[0] + "/" + temp[1] : temp[0];
}
bool property_is_next(string istring, int pos)
{
istring = istring.substr(pos,istring.length()-pos);
pos = istring.find_first_of(':',0);
if(pos == string::npos)
{
return false;
}
istring = strtolower(trim(istring.substr(0,pos)));
return (all_properties.count(istring) > 0);
}
string cut_color(string color)
{
if(strtolower(color.substr(0,4)) == "rgb(")
{
vector<string> color_tmp = explode(",",color.substr(4,color.length()-5));
for (int i = 0; i < color_tmp.size(); ++i)
{
color_tmp[i] = trim(color_tmp[i]);
if(color_tmp[i].at(color_tmp[i].length()-1) == '%')
{
color_tmp[i] = f2str(round(255 * atoi(color_tmp[i].c_str())/100,0));
}
if(atoi(color_tmp[i].c_str()) > 255) color_tmp[i] = 255;
}
color = "#";
for (int i = 0; i < color_tmp.size(); ++i)
{
if(atoi(color_tmp[i].c_str()) < 16)
{
color += "0" + dechex(atoi(color_tmp[i].c_str()));
}
else
{
color += dechex(atoi(color_tmp[i].c_str()));
}
}
}
// Fix bad color names
if(replace_colors.count(strtolower(color)) > 0)
{
color = replace_colors[strtolower(color)];
}
if(color.length() == 7)
{
string color_temp = strtoupper(color);
if(color_temp[0] == '#' && color_temp[1] == color_temp[2] && color_temp[3] == color_temp[4] && color_temp[5] == color_temp[6])
{
color = "#";
color += color_temp[2];
color += color_temp[3];
color += color_temp[5];
}
}
string temp = strtolower(color);
/* color name -> hex code */
if(temp == "black") return "#000";
if(temp == "fuchsia") return "#F0F";
if(temp == "white") return "#FFF";
if(temp == "yellow") return "#FF0";
/* hex code -> color name */
if(temp == "#800000") return "maroon";
if(temp == "#ffa500") return "orange";
if(temp == "#808000") return "olive";
if(temp == "#800080") return "purple";
if(temp == "#008000") return "green";
if(temp == "#000080") return "navy";
if(temp == "#008080") return "teal";
if(temp == "#c0c0c0") return "silver";
if(temp == "#808080") return "gray";
if(temp == "#f00") return "red";
return color;
}
int c_font_weight(string& value)
{
string important = "";
if(is_important(value))
{
important = " !important";
value = gvw_important(value);
}
if(value == "bold")
{
value = "700"+important;
return 700;
}
else if(value == "normal")
{
value = "400"+important;
return 400;
}
return 0;
}
void merge_selectors(sstore& input)
{
for(sstore::iterator i = input.begin(), e = input.end(); i != e;)
{
string newsel = "";
// Check if properties also exist in another selector
vector<string> keys;
for(sstore::iterator j = input.begin(); j != input.end(); j++ )
{
if(j->first == i->first)
{
continue;
}
if(input[j->first] == input[i->first])
{
keys.push_back(j->first);
}
}
if(keys.size() > 0)
{
newsel = i->first;
for(int k = 0; k < keys.size(); ++k)
{
input.erase(keys[k]);
newsel += "," + keys[k];
}
input[newsel] = i->second;
input.erase(i);
e = input.end();
} else {
i++;
}
}
}
<commit_msg>FS#143: Save some more bytes<commit_after>/*
* This file is part of CSSTidy.
*
* CSSTidy 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.
*
* CSSTidy 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 CSSTidy; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "csspp_globals.hpp"
using namespace std;
extern vector<string> number_values,color_values;
extern map<string,string> replace_colors,all_properties;
string shorthand(string value)
{
string important = "";
if(is_important(value))
{
value = gvw_important(value);
important = " !important";
}
vector<string> values = explode(" ",value);
switch(values.size())
{
case 4:
if(values[0] == values[1] && values[0] == values[2] && values[0] == values[3])
{
return values[0] + important;
}
else if(values[1] == values[3] && values[0] == values[2])
{
return values[0] + " " + values[1] + important;
}
else if(values[1] == values[3])
{
return values[0] + " " + values[1] + " " + values[2] + important;
}
else return value + important;
break;
case 3:
if(values[0] == values[1] && values[0] == values[2])
{
return values[0] + important;
}
else if(values[0] == values[2])
{
return values[0] + " " + values[1] + important;
}
else return value + important;
break;
case 2:
if(values[0] == values[1])
{
return values[0] + important;
}
else return value + important;
break;
default:
return value + important;
}
}
string compress_numbers(string subvalue, string property)
{
string units[] = {"in", "cm", "mm", "pt", "pc", "px", "rem", "%", "ex", "gd", "em", "vw", "vh",
"vm", "deg", "grad", "rad", "ms", "s", "khz", "hz" }; // sync for loop
vector<string> temp;
if(property == "font")
{
temp = explode("/",subvalue);
}
else
{
temp.push_back(subvalue);
}
for (int i = 0; i < temp.size(); ++i)
{
if(!(temp[i].length() > 0 && (ctype_digit(temp[i][0]) || temp[i][0] == '+' || temp[i][0] == '-' ) ))
{
continue;
}
if(in_str_array(color_values,property))
{
temp[i] = "#" + temp[i];
}
if(str2f(temp[i]) == 0)
{
temp[i] = "0";
}
else
{
bool unit_found = false;
temp[i] = strtolower(temp[i]);
for(int j = 0; j < 21; ++j )
{
if(temp[i].find(units[j]) != string::npos)
{
temp[i] = f2str(str2f(temp[i])) + units[j];
unit_found = true;
break;
}
}
if(!unit_found && !in_str_array(number_values,property))
{
temp[i] = f2str(str2f(temp[i]));
temp[i] += "px";
}
else if(!unit_found)
{
temp[i] = f2str(str2f(temp[i]));
}
// Remove leading zero
if (abs( (int) str2f(temp[i])) < 1) {
if (str2f(temp[i]) < 0) {
temp[i] = '-' + temp[i].substr(2);
} else {
temp[i] = temp[i].substr(1);
}
}
}
}
return (temp.size() > 1) ? temp[0] + "/" + temp[1] : temp[0];
}
bool property_is_next(string istring, int pos)
{
istring = istring.substr(pos,istring.length()-pos);
pos = istring.find_first_of(':',0);
if(pos == string::npos)
{
return false;
}
istring = strtolower(trim(istring.substr(0,pos)));
return (all_properties.count(istring) > 0);
}
string cut_color(string color)
{
if(strtolower(color.substr(0,4)) == "rgb(")
{
vector<string> color_tmp = explode(",",color.substr(4,color.length()-5));
for (int i = 0; i < color_tmp.size(); ++i)
{
color_tmp[i] = trim(color_tmp[i]);
if(color_tmp[i].at(color_tmp[i].length()-1) == '%')
{
color_tmp[i] = f2str(round(255 * atoi(color_tmp[i].c_str())/100,0));
}
if(atoi(color_tmp[i].c_str()) > 255) color_tmp[i] = 255;
}
color = "#";
for (int i = 0; i < color_tmp.size(); ++i)
{
if(atoi(color_tmp[i].c_str()) < 16)
{
color += "0" + dechex(atoi(color_tmp[i].c_str()));
}
else
{
color += dechex(atoi(color_tmp[i].c_str()));
}
}
}
// Fix bad color names
if(replace_colors.count(strtolower(color)) > 0)
{
color = replace_colors[strtolower(color)];
}
if(color.length() == 7)
{
string color_temp = strtoupper(color);
if(color_temp[0] == '#' && color_temp[1] == color_temp[2] && color_temp[3] == color_temp[4] && color_temp[5] == color_temp[6])
{
color = "#";
color += color_temp[2];
color += color_temp[3];
color += color_temp[5];
}
}
string temp = strtolower(color);
/* color name -> hex code */
if(temp == "black") return "#000";
if(temp == "fuchsia") return "#F0F";
if(temp == "white") return "#FFF";
if(temp == "yellow") return "#FF0";
/* hex code -> color name */
if(temp == "#800000") return "maroon";
if(temp == "#ffa500") return "orange";
if(temp == "#808000") return "olive";
if(temp == "#800080") return "purple";
if(temp == "#008000") return "green";
if(temp == "#000080") return "navy";
if(temp == "#008080") return "teal";
if(temp == "#c0c0c0") return "silver";
if(temp == "#808080") return "gray";
if(temp == "#f00") return "red";
return color;
}
int c_font_weight(string& value)
{
string important = "";
if(is_important(value))
{
important = " !important";
value = gvw_important(value);
}
if(value == "bold")
{
value = "700"+important;
return 700;
}
else if(value == "normal")
{
value = "400"+important;
return 400;
}
return 0;
}
void merge_selectors(sstore& input)
{
for(sstore::iterator i = input.begin(), e = input.end(); i != e;)
{
string newsel = "";
// Check if properties also exist in another selector
vector<string> keys;
for(sstore::iterator j = input.begin(); j != input.end(); j++ )
{
if(j->first == i->first)
{
continue;
}
if(input[j->first] == input[i->first])
{
keys.push_back(j->first);
}
}
if(keys.size() > 0)
{
newsel = i->first;
for(int k = 0; k < keys.size(); ++k)
{
input.erase(keys[k]);
newsel += "," + keys[k];
}
input[newsel] = i->second;
input.erase(i);
e = input.end();
} else {
i++;
}
}
}
<|endoftext|> |
<commit_before>#include "DrawCallBatching.h"
#include "dataset/Image.h"
#include "render/ShaderMgr.h"
#include <dtex_facade.h>
#include <gl/glew.h>
namespace d2d
{
DrawCallBatching* DrawCallBatching::m_instance = NULL;
//////////////////////////////////////////////////////////////////////////
static int TEX_ID = 0;
void program(int n)
{
switch (n)
{
case DTEX_PROGRAM_NULL:
ShaderMgr::Instance()->null();
break;
case DTEX_PROGRAM_NORMAL:
ShaderMgr::Instance()->sprite();
break;
default:
assert(0);
}
}
void blend(int mode)
{
assert(mode == 0);
// ShaderMgr::Instance()->SetBlendMode(0);
}
void set_texture(int id)
{
TEX_ID = id;
ShaderMgr::Instance()->SetTexture(id);
}
int get_texture()
{
return ShaderMgr::Instance()->GetTexID();
}
void set_target(int id)
{
ShaderMgr::Instance()->SetFBO(id);
}
int get_target()
{
return ShaderMgr::Instance()->GetFboID();
}
static int ori_width, ori_height;
static Vector ori_offset;
static float ori_scale;
void draw_begin()
{
ShaderMgr* shader = ShaderMgr::Instance();
int viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
ori_width = viewport[2];
ori_height = viewport[3];
shader->GetModelView(ori_offset, ori_scale);
shader->SetModelView(Vector(0, 0), 1);
shader->SetProjection(2, 2);
// glViewport(0, 0, 2, 2);
}
void draw(const float vb[16])
{
ShaderMgr* shader = ShaderMgr::Instance();
shader->Draw(vb, TEX_ID);
}
void draw_end()
{
ShaderMgr* shader = ShaderMgr::Instance();
shader->Flush();
shader->SetModelView(ori_offset, ori_scale);
shader->SetProjection(ori_width, ori_height);
// glViewport(0, 0, ori_width, ori_height);
}
//////////////////////////////////////////////////////////////////////////
static const char* CFG =
"{ \n"
" \"open_c1\" : false, \n"
" \"open_c2\" : true, \n"
" \"open_c3\" : false, \n"
" \"open_cg\" : true, \n"
" \"c2_tex_size\" : 2048 \n"
"} \n"
;
DrawCallBatching::DrawCallBatching()
{
dtex_shader_init(&program, &blend, &set_texture, &get_texture, &set_target, &get_target,
&draw_begin, &draw, &draw_end);
dtexf_create(CFG);
// dtex_shader_load();
// dtex_render_init();
//
// m_loader = dtexloader_create();
// m_c2 = dtex_c2_create(4096, true, 1, false);
}
DrawCallBatching::~DrawCallBatching()
{
// dtexloader_release(m_loader);
// dtex_c2_release(m_c2);
}
void DrawCallBatching::Begin()
{
dtexf_c2_load_begin();
}
int DrawCallBatching::Add(const Image* img)
{
const std::string& filepath = img->GetFilepath();
std::map<std::string, int>::iterator itr = m_path2id.find(filepath);
if (itr != m_path2id.end()) {
return itr->second;
}
int key = m_path2id.size();
m_path2id.insert(std::make_pair(filepath, key));
dtexf_c2_load_tex(img->GetTexID(), img->GetOriginWidth(), img->GetOriginHeight(), key);
return key;
}
void DrawCallBatching::End()
{
dtexf_c2_load_end();
}
float* DrawCallBatching::Query(const Image* img, int* id)
{
int key;
std::map<std::string, int>::iterator itr = m_path2id.find(img->GetFilepath());
if (itr != m_path2id.end()) {
key = itr->second;
} else {
key = Add(img);
}
return dtexf_c2_query_tex(key, id);
}
DrawCallBatching* DrawCallBatching::Instance()
{
if (!m_instance) {
m_instance = new DrawCallBatching();
}
return m_instance;
}
}<commit_msg>[FIXED] dtex init<commit_after>#include "DrawCallBatching.h"
#include "dataset/Image.h"
#include "render/ShaderMgr.h"
#include <dtex_facade.h>
#include <gl/glew.h>
namespace d2d
{
DrawCallBatching* DrawCallBatching::m_instance = NULL;
//////////////////////////////////////////////////////////////////////////
static int TEX_ID = 0;
static void _program(int n)
{
switch (n)
{
case DTEX_PROGRAM_NULL:
ShaderMgr::Instance()->null();
break;
case DTEX_PROGRAM_NORMAL:
ShaderMgr::Instance()->sprite();
break;
default:
assert(0);
}
}
static void _blend(int mode)
{
assert(mode == 0);
// ShaderMgr::Instance()->SetBlendMode(0);
}
static void _set_texture(int id)
{
TEX_ID = id;
ShaderMgr::Instance()->SetTexture(id);
}
static int _get_texture()
{
return ShaderMgr::Instance()->GetTexID();
}
static void _set_target(int id)
{
ShaderMgr::Instance()->SetFBO(id);
}
static int _get_target()
{
return ShaderMgr::Instance()->GetFboID();
}
static int ori_width, ori_height;
static Vector ori_offset;
static float ori_scale;
static void _draw_begin()
{
ShaderMgr* shader = ShaderMgr::Instance();
int viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
ori_width = viewport[2];
ori_height = viewport[3];
shader->GetModelView(ori_offset, ori_scale);
shader->SetModelView(Vector(0, 0), 1);
shader->SetProjection(2, 2);
// glViewport(0, 0, 2, 2);
}
static void _draw(const float vb[16])
{
ShaderMgr* shader = ShaderMgr::Instance();
shader->Draw(vb, TEX_ID);
}
static void _draw_end()
{
ShaderMgr* shader = ShaderMgr::Instance();
shader->Flush();
shader->SetModelView(ori_offset, ori_scale);
shader->SetProjection(ori_width, ori_height);
// glViewport(0, 0, ori_width, ori_height);
}
#define IS_POT(x) ((x) > 0 && ((x) & ((x) -1)) == 0)
static int _texture_create(int type, int width, int height, const void* data, int channel) {
assert(type == DTEX_TF_RGBA8);
// todo
if ((type == DTEX_TF_RGBA8) || (IS_POT(width) && IS_POT(height))) {
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
} else {
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
}
GLint _format = GL_RGBA;
GLenum _type = GL_UNSIGNED_BYTE;
bool is_compressed = false;
unsigned int size = 0;
uint8_t* uncompressed = NULL;
switch (type) {
case DTEX_TF_RGBA8:
is_compressed = false;
_format = GL_RGBA;
_type = GL_UNSIGNED_BYTE;
break;
case DTEX_TF_RGBA4:
is_compressed = false;
_format = GL_RGBA;
_type = GL_UNSIGNED_SHORT_4_4_4_4;
break;
case DTEX_TF_PVR2:
#ifdef __APPLE__
is_compressed = true;
_type = COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
size = width * height * 8 * _type / 16;
#endif // __APPLE__
break;
case DTEX_TF_PVR4:
#ifdef __APPLE__
is_compressed = true;
_type = COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
size = width * height * 8 * _type / 16;
#else
// is_compressed = false;
// _format = GL_RGBA;
// _type = GL_UNSIGNED_BYTE;
// uncompressed = dtex_pvr_decode(data, width, height);
#endif // __APPLE__
break;
case DTEX_TF_ETC1:
#ifdef __ANDROID__
is_compressed = true;
_type = GL_ETC1_RGB8_OES;
size = width * height * 4 / 8;
#else
is_compressed = false;
_format = GL_RGBA;
_type = GL_UNSIGNED_BYTE;
#ifdef USED_IN_EDITOR
// uncompressed = dtex_etc1_decode(data, width, height);
#endif // USED_IN_EDITOR
#endif // __ANDROID__
break;
default:
dtex_fault("dtex_gl_create_texture: unknown texture type.");
}
glActiveTexture(GL_TEXTURE0 + channel);
GLuint id;
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
if (is_compressed) {
glCompressedTexImage2D(GL_TEXTURE_2D, 0, _type, width, height, 0, size, data);
} else {
if (uncompressed) {
glTexImage2D(GL_TEXTURE_2D, 0, _format, (GLsizei)width, (GLsizei)height, 0, _format, _type, uncompressed);
free(uncompressed);
} else {
glTexImage2D(GL_TEXTURE_2D, 0, _format, (GLsizei)width, (GLsizei)height, 0, _format, _type, data);
}
}
return id;
}
static void
_texture_release(int id) {
GLuint texid = (GLuint)id;
glActiveTexture(GL_TEXTURE0);
glDeleteTextures(1, &texid);
}
static void
_texture_update(const void* pixels, int x, int y, int w, int h, unsigned int id) {
int old_id = ShaderMgr::Instance()->GetTexID();
glBindTexture(GL_TEXTURE_2D, id);
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
glBindTexture(GL_TEXTURE_2D, old_id);
}
static int
_texture_id(int id) {
return id;
}
//////////////////////////////////////////////////////////////////////////
static const char* CFG =
"{ \n"
" \"open_c1\" : false, \n"
" \"open_c2\" : true, \n"
" \"open_c3\" : false, \n"
" \"open_cg\" : true, \n"
" \"c2_tex_size\" : 2048 \n"
"} \n"
;
DrawCallBatching::DrawCallBatching()
{
dtex_shader_init(&_program, &_blend, &_set_texture, &_get_texture, &_set_target, &_get_target,
&_draw_begin, &_draw, &_draw_end);
dtex_gl_texture_init(&_texture_create, &_texture_release, &_texture_update, &_texture_id);
dtexf_create(CFG);
// dtex_shader_load();
// dtex_render_init();
//
// m_loader = dtexloader_create();
// m_c2 = dtex_c2_create(4096, true, 1, false);
}
DrawCallBatching::~DrawCallBatching()
{
// dtexloader_release(m_loader);
// dtex_c2_release(m_c2);
}
void DrawCallBatching::Begin()
{
dtexf_c2_load_begin();
}
int DrawCallBatching::Add(const Image* img)
{
const std::string& filepath = img->GetFilepath();
std::map<std::string, int>::iterator itr = m_path2id.find(filepath);
if (itr != m_path2id.end()) {
return itr->second;
}
int key = m_path2id.size();
m_path2id.insert(std::make_pair(filepath, key));
dtexf_c2_load_tex(img->GetTexID(), img->GetOriginWidth(), img->GetOriginHeight(), key);
return key;
}
void DrawCallBatching::End()
{
dtexf_c2_load_end();
}
float* DrawCallBatching::Query(const Image* img, int* id)
{
int key;
std::map<std::string, int>::iterator itr = m_path2id.find(img->GetFilepath());
if (itr != m_path2id.end()) {
key = itr->second;
} else {
key = Add(img);
}
return dtexf_c2_query_tex(key, id);
}
DrawCallBatching* DrawCallBatching::Instance()
{
if (!m_instance) {
m_instance = new DrawCallBatching();
}
return m_instance;
}
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_SPARC_INTERRUPT_HH__
#define __ARCH_SPARC_INTERRUPT_HH__
#include "arch/sparc/faults.hh"
namespace SparcISA
{
class Interrupts
{
protected:
Fault interrupts[NumInterruptLevels];
bool requested[NumInterruptLevels];
public:
Interrupts()
{
for(int x = 0; x < NumInterruptLevels; x++)
{
interrupts[x] = new InterruptLevelN(x);
requested[x] = false;
}
}
void post(int int_num, int index)
{
if(int_num < 0 || int_num >= NumInterruptLevels)
panic("int_num out of bounds\n");
requested[int_num] = true;
}
void clear(int int_num, int index)
{
requested[int_num] = false;
}
void clear_all()
{
for(int x = 0; x < NumInterruptLevels; x++)
requested[x] = false;
}
bool check_interrupts(ThreadContext * tc) const
{
return true;
}
Fault getInterrupt(ThreadContext * tc)
{
return NoFault;
}
void serialize(std::ostream &os)
{
}
void unserialize(Checkpoint *cp, const std::string §ion)
{
}
};
}
#endif // __ARCH_SPARC_INTERRUPT_HH__
<commit_msg>interrupts.hh: make a likewise updateIntrInfo for Sparc that's blank so it doesn't fart on build<commit_after>/*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_SPARC_INTERRUPT_HH__
#define __ARCH_SPARC_INTERRUPT_HH__
#include "arch/sparc/faults.hh"
namespace SparcISA
{
class Interrupts
{
protected:
Fault interrupts[NumInterruptLevels];
bool requested[NumInterruptLevels];
public:
Interrupts()
{
for(int x = 0; x < NumInterruptLevels; x++)
{
interrupts[x] = new InterruptLevelN(x);
requested[x] = false;
}
}
void post(int int_num, int index)
{
if(int_num < 0 || int_num >= NumInterruptLevels)
panic("int_num out of bounds\n");
requested[int_num] = true;
}
void clear(int int_num, int index)
{
requested[int_num] = false;
}
void clear_all()
{
for(int x = 0; x < NumInterruptLevels; x++)
requested[x] = false;
}
bool check_interrupts(ThreadContext * tc) const
{
return true;
}
Fault getInterrupt(ThreadContext * tc)
{
return NoFault;
}
void updateIntrInfo(ThreadContext * tc)
{
}
void serialize(std::ostream &os)
{
}
void unserialize(Checkpoint *cp, const std::string §ion)
{
}
};
}
#endif // __ARCH_SPARC_INTERRUPT_HH__
<|endoftext|> |
<commit_before>/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */
/*
* MODB inspection command-line tool
*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
#include <unistd.h>
#include <signal.h>
#include <string>
#include <vector>
#include <iostream>
#include <boost/program_options.hpp>
#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <modelgbp/dmtree/Root.hpp>
#include <modelgbp/metadata/metadata.hpp>
#include <opflex/ofcore/OFFramework.h>
#include <opflex/modb/URI.h>
#include <opflex/ofcore/OFConstants.h>
#include <opflex/ofcore/InspectorClient.h>
#include "logging.h"
#include "cmd.h"
#include <signal.h>
using std::string;
using boost::scoped_ptr;
namespace po = boost::program_options;
using opflex::ofcore::InspectorClient;
using opflex::modb::URI;
using boost::iostreams::stream;
using boost::iostreams::close_handle;
using boost::iostreams::file_descriptor_sink;
using namespace ovsagent;
void sighandler(int sig) {
LOG(INFO) << "Got " << strsignal(sig) << " signal";
}
#define DEF_SOCKET LOCALSTATEDIR"/run/opflex-agent-ovs-inspect.sock"
int main(int argc, char** argv) {
signal(SIGPIPE, SIG_IGN);
// Parse command line options
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Print this help message")
("log", po::value<string>()->default_value(""),
"Log to the specified file (default standard out)")
("level", po::value<string>()->default_value("error"),
"Use the specified log level (default info)")
("syslog", "Log to syslog instead of file or standard out")
("socket", po::value<string>()->default_value(DEF_SOCKET),
"Connect to the specified UNIX domain socket (default "DEF_SOCKET")")
("query,q", po::value<std::vector<string> >(),
"Query for a specific object with subjectname,uri or all objects "
"of a specific type with subjectname")
("recursive,r", "Retrieve the whole subtree for each returned object")
("follow-refs,f", "Follow references in returned objects")
("load", po::value<std::string>()->default_value(""),
"Load managed objects from the specified file into the MODB view")
("output,o", po::value<std::string>()->default_value(""),
"Output the results to the specified file (default standard out)")
("type,t", po::value<std::string>()->default_value("tree"),
"Specify the output format: tree, list, or dump (default tree)")
("props,p", "Include object properties in output")
;
bool log_to_syslog = false;
string log_file;
string level_str;
string socket;
std::vector<string> queries;
string out_file;
string load_file;
string type;
bool props = false;
bool recursive = false;
bool followRefs = false;
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).
options(desc).run(), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << "Usage: " << argv[0] << " [options]\n";
std::cout << desc;
return 0;
}
if (vm.count("props"))
props = true;
if (vm.count("recursive"))
recursive = true;
if (vm.count("follow-refs"))
followRefs = true;
log_file = vm["log"].as<string>();
level_str = vm["level"].as<string>();
if (vm.count("syslog")) {
log_to_syslog = true;
}
socket = vm["socket"].as<string>();
out_file = vm["output"].as<string>();
load_file = vm["load"].as<string>();
type = vm["type"].as<string>();
if (vm.count("query"))
queries = vm["query"].as<std::vector<string> >();
} catch (po::unknown_option e) {
std::cerr << e.what() << std::endl;
return 1;
}
initLogging(level_str, log_to_syslog, log_file);
if (queries.size() == 0 && load_file == "") {
LOG(ERROR) << "No queries specified";
return 1;
}
if (type != "tree" && type != "dump" && type != "list") {
LOG(ERROR) << "Invalid output type: " << type;
return 1;
}
try {
scoped_ptr<InspectorClient>
client(InspectorClient::newInstance(socket,
modelgbp::getMetadata()));
client->setRecursive(recursive);
client->setFollowRefs(followRefs);
BOOST_FOREACH(string query, queries) {
size_t ci = query.find_first_of(",");
if (ci == string::npos) {
client->addClassQuery(query);
} else {
if (ci == 0 || ci >= (query.size()-1)) {
LOG(ERROR) << "Invalid query: " << query <<
": must be in the form subject,uri or subject";
continue;
}
client->addQuery(query.substr(0, ci),
URI(query.substr(ci+1, string::npos)));
}
}
if (load_file != "") {
FILE* inf = fopen(load_file.c_str(), "r");
if (inf == NULL) {
LOG(ERROR) << "Could not input file "
<< load_file << " for reading";
return 1;
}
client->loadFromFile(inf);
}
if (queries.size() > 0)
client->execute();
FILE* outf = stdout;
if (out_file != "") {
outf = fopen(out_file.c_str(), "w");
if (outf == NULL) {
LOG(ERROR) << "Could not open file "
<< out_file << " for writing";
return 1;
}
}
stream<file_descriptor_sink> outs(fileno(outf), close_handle);
if (type == "dump")
client->dumpToFile(outf);
else if (type == "list")
client->prettyPrint(outs, false, props);
else
client->prettyPrint(outs, true, props);
fclose(outf);
} catch (const std::exception& e) {
LOG(ERROR) << "Fatal error: " << e.what();
return 2;
} catch (...) {
LOG(ERROR) << "Unknown fatal error";
return 3;
}
}
<commit_msg>Change default log level to warning so the underlying errors from socket connections will be shown rather than just a generic 'Unknown system error'<commit_after>/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */
/*
* MODB inspection command-line tool
*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
#include <unistd.h>
#include <signal.h>
#include <string>
#include <vector>
#include <iostream>
#include <boost/program_options.hpp>
#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <modelgbp/dmtree/Root.hpp>
#include <modelgbp/metadata/metadata.hpp>
#include <opflex/ofcore/OFFramework.h>
#include <opflex/modb/URI.h>
#include <opflex/ofcore/OFConstants.h>
#include <opflex/ofcore/InspectorClient.h>
#include "logging.h"
#include "cmd.h"
#include <signal.h>
using std::string;
using boost::scoped_ptr;
namespace po = boost::program_options;
using opflex::ofcore::InspectorClient;
using opflex::modb::URI;
using boost::iostreams::stream;
using boost::iostreams::close_handle;
using boost::iostreams::file_descriptor_sink;
using namespace ovsagent;
void sighandler(int sig) {
LOG(INFO) << "Got " << strsignal(sig) << " signal";
}
#define DEF_SOCKET LOCALSTATEDIR"/run/opflex-agent-ovs-inspect.sock"
int main(int argc, char** argv) {
signal(SIGPIPE, SIG_IGN);
// Parse command line options
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Print this help message")
("log", po::value<string>()->default_value(""),
"Log to the specified file (default standard out)")
("level", po::value<string>()->default_value("warning"),
"Use the specified log level (default info)")
("syslog", "Log to syslog instead of file or standard out")
("socket", po::value<string>()->default_value(DEF_SOCKET),
"Connect to the specified UNIX domain socket (default "DEF_SOCKET")")
("query,q", po::value<std::vector<string> >(),
"Query for a specific object with subjectname,uri or all objects "
"of a specific type with subjectname")
("recursive,r", "Retrieve the whole subtree for each returned object")
("follow-refs,f", "Follow references in returned objects")
("load", po::value<std::string>()->default_value(""),
"Load managed objects from the specified file into the MODB view")
("output,o", po::value<std::string>()->default_value(""),
"Output the results to the specified file (default standard out)")
("type,t", po::value<std::string>()->default_value("tree"),
"Specify the output format: tree, list, or dump (default tree)")
("props,p", "Include object properties in output")
;
bool log_to_syslog = false;
string log_file;
string level_str;
string socket;
std::vector<string> queries;
string out_file;
string load_file;
string type;
bool props = false;
bool recursive = false;
bool followRefs = false;
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).
options(desc).run(), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << "Usage: " << argv[0] << " [options]\n";
std::cout << desc;
return 0;
}
if (vm.count("props"))
props = true;
if (vm.count("recursive"))
recursive = true;
if (vm.count("follow-refs"))
followRefs = true;
log_file = vm["log"].as<string>();
level_str = vm["level"].as<string>();
if (vm.count("syslog")) {
log_to_syslog = true;
}
socket = vm["socket"].as<string>();
out_file = vm["output"].as<string>();
load_file = vm["load"].as<string>();
type = vm["type"].as<string>();
if (vm.count("query"))
queries = vm["query"].as<std::vector<string> >();
} catch (po::unknown_option e) {
std::cerr << e.what() << std::endl;
return 1;
}
initLogging(level_str, log_to_syslog, log_file);
if (queries.size() == 0 && load_file == "") {
LOG(ERROR) << "No queries specified";
return 1;
}
if (type != "tree" && type != "dump" && type != "list") {
LOG(ERROR) << "Invalid output type: " << type;
return 1;
}
try {
scoped_ptr<InspectorClient>
client(InspectorClient::newInstance(socket,
modelgbp::getMetadata()));
client->setRecursive(recursive);
client->setFollowRefs(followRefs);
BOOST_FOREACH(string query, queries) {
size_t ci = query.find_first_of(",");
if (ci == string::npos) {
client->addClassQuery(query);
} else {
if (ci == 0 || ci >= (query.size()-1)) {
LOG(ERROR) << "Invalid query: " << query <<
": must be in the form subject,uri or subject";
continue;
}
client->addQuery(query.substr(0, ci),
URI(query.substr(ci+1, string::npos)));
}
}
if (load_file != "") {
FILE* inf = fopen(load_file.c_str(), "r");
if (inf == NULL) {
LOG(ERROR) << "Could not input file "
<< load_file << " for reading";
return 1;
}
client->loadFromFile(inf);
}
if (queries.size() > 0)
client->execute();
FILE* outf = stdout;
if (out_file != "") {
outf = fopen(out_file.c_str(), "w");
if (outf == NULL) {
LOG(ERROR) << "Could not open file "
<< out_file << " for writing";
return 1;
}
}
stream<file_descriptor_sink> outs(fileno(outf), close_handle);
if (type == "dump")
client->dumpToFile(outf);
else if (type == "list")
client->prettyPrint(outs, false, props);
else
client->prettyPrint(outs, true, props);
fclose(outf);
} catch (const std::exception& e) {
LOG(ERROR) << "Fatal error: " << e.what();
return 2;
} catch (...) {
LOG(ERROR) << "Unknown fatal error";
return 3;
}
}
<|endoftext|> |
<commit_before>/*
avdeviceconfig.cpp - Kopete Video Device Configuration Panel
Copyright (c) 2005-2006 by Cláudio da Silveira Pinheiro <taupter@gmail.com>
Copyright (c) 2010 by Frank Schaefer <fschaefer.oss@googlemail.com>
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include "avdeviceconfig.h"
#include <qcheckbox.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qbuttongroup.h>
#include <qspinbox.h>
#include <qcombobox.h>
#include <qslider.h>
//Added by qt3to4:
#include <QVBoxLayout>
#include <kplugininfo.h>
#include <klocale.h>
#include <kpushbutton.h>
#include <kpluginfactory.h>
#include <ktrader.h>
#include <kconfig.h>
#include <kcombobox.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qtabwidget.h>
#include "IdGuiElements.h"
K_PLUGIN_FACTORY( KopeteAVDeviceConfigFactory,
registerPlugin<AVDeviceConfig>(); )
K_EXPORT_PLUGIN( KopeteAVDeviceConfigFactory("kcm_kopete_avdeviceconfig") )
AVDeviceConfig::AVDeviceConfig(QWidget *parent, const QVariantList &args)
: KCModule( KopeteAVDeviceConfigFactory::componentData(), parent, args )
{
kDebug() << "kopete:config (avdevice): KopeteAVDeviceConfigFactory::componentData() called. ";
// "Video" TAB ============================================================
mPrfsVideoDevice = new Ui_AVDeviceConfig_VideoDevice();
mPrfsVideoDevice->setupUi(this);
// set a default image for the webcam widget, in case the user does not have a video device
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(false);
mPrfsVideoDevice->mVideoImageLabel->setPixmap(KIcon("camera-web").pixmap(128,128));
connect(mPrfsVideoDevice->mDeviceKComboBox, SIGNAL(activated(int)), this, SLOT(slotDeviceKComboBoxChanged(int)));
connect(mPrfsVideoDevice->mInputKComboBox, SIGNAL(activated(int)), this, SLOT(slotInputKComboBoxChanged(int)));
connect(mPrfsVideoDevice->mStandardKComboBox, SIGNAL(activated(int)), this, SLOT(slotStandardKComboBoxChanged(int)));
mVideoDevicePool = Kopete::AV::VideoDevicePool::self();
startCapturing();
mVideoDevicePool->fillDeviceKComboBox(mPrfsVideoDevice->mDeviceKComboBox);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
connect(mVideoDevicePool, SIGNAL(deviceRegistered(const QString &) ),
SLOT(deviceRegistered(const QString &)) );
connect(mVideoDevicePool, SIGNAL(deviceUnregistered(const QString &) ),
SLOT(deviceUnregistered(const QString &)) );
connect(&qtimer, SIGNAL(timeout()), this, SLOT(slotUpdateImage()) );
}
AVDeviceConfig::~AVDeviceConfig()
{
mVideoDevicePool->close();
clearControlGUIElements();
}
void AVDeviceConfig::setupControls()
{
int k = 0;
qint32 cval = 0;
clearControlGUIElements();
QList<Kopete::AV::NumericVideoControl> numericCtrls;
QList<Kopete::AV::BooleanVideoControl> booleanCtrls;
QList<Kopete::AV::MenuVideoControl> menuCtrls;
QList<Kopete::AV::ActionVideoControl> actionCtrls;
numericCtrls = mVideoDevicePool->getSupportedNumericControls();
booleanCtrls = mVideoDevicePool->getSupportedBooleanControls();
menuCtrls = mVideoDevicePool->getSupportedMenuControls();
actionCtrls = mVideoDevicePool->getSupportedActionControls();
kDebug() << "Supported controls:" << numericCtrls.size() << "numeric," << booleanCtrls.size()
<< "boolean," << menuCtrls.size() << "menus," << actionCtrls.size() << "actions.";
/* SETUP GUI-elements */
// Numeric Controls: => Slider
for (k=0; k<numericCtrls.size(); k++)
{
mVideoDevicePool->getControlValue(numericCtrls.at(k).id, &cval);
addSliderControlElement(numericCtrls.at(k).id, numericCtrls.at(k).name, numericCtrls.at(k).value_min, numericCtrls.at(k).value_max, numericCtrls.at(k).value_step, cval);
}
// Boolean Controls: => Checkbox
for (k=0; k<booleanCtrls.size(); k++)
{
mVideoDevicePool->getControlValue(booleanCtrls.at(k).id, &cval);
addCheckBoxControlElement(booleanCtrls.at(k).id, booleanCtrls.at(k).name, cval);
}
// Menu Controls: => Combobox
for (k=0; k<menuCtrls.size(); k++)
{
mVideoDevicePool->getControlValue(menuCtrls.at(k).id, &cval);
addPopupMenuControlElement(menuCtrls.at(k).id, menuCtrls.at(k).name, menuCtrls.at(k).options, cval);
}
// Action Controls: => Button
for (k=0; k<actionCtrls.size(); k++)
addButtonControlElement(actionCtrls.at(k).id, actionCtrls.at(k).name);
/* TODO: check success of mVideoDevicePool->getControlValue() */
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(1, numericCtrls.size());
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(2, booleanCtrls.size() + menuCtrls.size());
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(3, actionCtrls.size());
}
void AVDeviceConfig::clearControlGUIElements()
{
for (int k=0; k<ctrlWidgets.size(); k++)
delete ctrlWidgets.at(k);
ctrlWidgets.clear();
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(1, false);
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(2, false);
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(3, false);
}
void AVDeviceConfig::addSliderControlElement(int cid, QString title, int min, int max, int step, int value)
{
int insert_row = mPrfsVideoDevice->sliders_gridLayout->rowCount();
QLabel *label = new QLabel( title + ":", mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->sliders_gridLayout->addWidget( label, insert_row, 0 );
IdSlider *slider = new IdSlider(cid, Qt::Horizontal, mPrfsVideoDevice->VideoTabWidget);
mPrfsVideoDevice->sliders_gridLayout->addWidget( slider, insert_row, 1 );
slider->setMinimum( min );
slider->setMaximum( max );
slider->setSliderPosition( value );
slider->setTickInterval( step );
connect( slider, SIGNAL( valueChanged(uint, int) ), this, SLOT( changeVideoControlValue(uint, int) ) );
ctrlWidgets.push_back(label);
ctrlWidgets.push_back(slider);
}
void AVDeviceConfig::addCheckBoxControlElement(int cid, QString title, bool value)
{
IdCheckBox *checkbox = new IdCheckBox( cid, mPrfsVideoDevice->VideoTabWidget );
checkbox->setText( title );
mPrfsVideoDevice->checkboxOptions_verticalLayout->addWidget( checkbox );
checkbox->setChecked( value );
connect( checkbox, SIGNAL( stateChanged(uint, int) ), this, SLOT( changeVideoControlValue(uint, int) ) );
ctrlWidgets.push_back(checkbox);
}
void AVDeviceConfig::addPopupMenuControlElement(int cid, QString title, QStringList options, int menuindex)
{
int insert_row = mPrfsVideoDevice->menuOptions_gridLayout->rowCount();
QLabel *label = new QLabel( title + ":", mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->menuOptions_gridLayout->addWidget( label, insert_row, 0 );
IdComboBox *combobox = new IdComboBox( cid, mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->menuOptions_gridLayout->addWidget( combobox, insert_row, 1 );
combobox->addItems( options );
combobox->setCurrentIndex( menuindex );
connect( combobox, SIGNAL( currentIndexChanged(uint, int) ), this, SLOT( changeVideoControlValue(uint, int) ) );
ctrlWidgets.push_back(label);
ctrlWidgets.push_back(combobox);
}
void AVDeviceConfig::addButtonControlElement(int cid, QString title)
{
int insert_row = mPrfsVideoDevice->actions_gridLayout->rowCount();
QLabel *label = new QLabel( title + ":", mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->actions_gridLayout->addWidget( label, insert_row, 0 );
IdPushButton *button = new IdPushButton( cid, mPrfsVideoDevice->VideoTabWidget );
button->setText( i18n("Execute") );
mPrfsVideoDevice->actions_gridLayout->addWidget( button, insert_row, 1 );
connect( button, SIGNAL( pressed(uint) ), this, SLOT( changeVideoControlValue(uint) ) );
ctrlWidgets.push_back(label);
ctrlWidgets.push_back(button);
}
/*!
\fn VideoDeviceConfig::save()
*/
void AVDeviceConfig::save()
{
/// @todo implement me
kDebug() << "kopete:config (avdevice): save() called. ";
mVideoDevicePool->saveCurrentDeviceConfig();
}
/*!
\fn VideoDeviceConfig::load()
*/
void AVDeviceConfig::load()
{
/// @todo implement me
}
void AVDeviceConfig::slotSettingsChanged(bool)
{
emit changed(true);
}
void AVDeviceConfig::slotValueChanged(int)
{
emit changed( true );
}
void AVDeviceConfig::slotDeviceKComboBoxChanged(int)
{
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) called. ";
int newdevice = mPrfsVideoDevice->mDeviceKComboBox->currentIndex();
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) Current device: " << mVideoDevicePool->currentDevice() << "New device: " << newdevice;
if ((newdevice >= 0 && newdevice < mVideoDevicePool->size()) && (newdevice != mVideoDevicePool->currentDevice()))
{
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) should change device. ";
stopCapturing();
mVideoDevicePool->open(newdevice);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
startCapturing();
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) called. ";
emit changed( true );
}
}
void AVDeviceConfig::slotInputKComboBoxChanged(int)
{
int newinput = mPrfsVideoDevice->mInputKComboBox->currentIndex();
if ((newinput < mVideoDevicePool->inputs()) && (newinput != mVideoDevicePool->currentInput()))
{
stopCapturing();
mVideoDevicePool->selectInput(mPrfsVideoDevice->mInputKComboBox->currentIndex());
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
startCapturing();
emit changed( true );
}
}
void AVDeviceConfig::slotStandardKComboBoxChanged(int)
{
emit changed( true );
}
void AVDeviceConfig::changeVideoControlValue(unsigned int id, int value)
{
mVideoDevicePool->setControlValue(id, value);
emit changed( true );
/* TODO: Check success, fallback */
}
void AVDeviceConfig::slotUpdateImage()
{
mVideoDevicePool->getFrame();
mVideoDevicePool->getImage(&qimage);
mPrfsVideoDevice->mVideoImageLabel->setPixmap(QPixmap::fromImage(qimage));
//kDebug() << "kopete (avdeviceconfig_videoconfig): Image updated.";
}
void AVDeviceConfig::deviceRegistered( const QString & udi )
{
mVideoDevicePool->fillDeviceKComboBox(mPrfsVideoDevice->mDeviceKComboBox);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
if (mVideoDevicePool->size() < 2) // otherwise we are already capturing
startCapturing();
}
void AVDeviceConfig::deviceUnregistered( const QString & udi )
{
mVideoDevicePool->fillDeviceKComboBox(mPrfsVideoDevice->mDeviceKComboBox);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
if (capturingDevice_udi == udi)
{
qtimer.stop();
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(false);
mPrfsVideoDevice->mVideoImageLabel->setPixmap(KIcon("camera-web").pixmap(128,128));
capturingDevice_udi.clear();
clearControlGUIElements();
if (mVideoDevicePool->size())
startCapturing();
}
}
void AVDeviceConfig::startCapturing()
{
if (EXIT_SUCCESS == mVideoDevicePool->open())
{
mVideoDevicePool->setSize(320, 240);
mVideoDevicePool->startCapturing();
setupControls();
capturingDevice_udi = mVideoDevicePool->currentDeviceUdi();
qtimer.start(40);
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(true);
}
}
void AVDeviceConfig::stopCapturing()
{
qtimer.stop();
mVideoDevicePool->stopCapturing();
mVideoDevicePool->close();
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(false);
mPrfsVideoDevice->mVideoImageLabel->setPixmap(KIcon("camera-web").pixmap(128,128));
capturingDevice_udi.clear();
}
<commit_msg>video-config-dialog: fix another m_clients-bug<commit_after>/*
avdeviceconfig.cpp - Kopete Video Device Configuration Panel
Copyright (c) 2005-2006 by Cláudio da Silveira Pinheiro <taupter@gmail.com>
Copyright (c) 2010 by Frank Schaefer <fschaefer.oss@googlemail.com>
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include "avdeviceconfig.h"
#include <qcheckbox.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qbuttongroup.h>
#include <qspinbox.h>
#include <qcombobox.h>
#include <qslider.h>
//Added by qt3to4:
#include <QVBoxLayout>
#include <kplugininfo.h>
#include <klocale.h>
#include <kpushbutton.h>
#include <kpluginfactory.h>
#include <ktrader.h>
#include <kconfig.h>
#include <kcombobox.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qtabwidget.h>
#include "IdGuiElements.h"
K_PLUGIN_FACTORY( KopeteAVDeviceConfigFactory,
registerPlugin<AVDeviceConfig>(); )
K_EXPORT_PLUGIN( KopeteAVDeviceConfigFactory("kcm_kopete_avdeviceconfig") )
AVDeviceConfig::AVDeviceConfig(QWidget *parent, const QVariantList &args)
: KCModule( KopeteAVDeviceConfigFactory::componentData(), parent, args )
{
kDebug() << "kopete:config (avdevice): KopeteAVDeviceConfigFactory::componentData() called. ";
// "Video" TAB ============================================================
mPrfsVideoDevice = new Ui_AVDeviceConfig_VideoDevice();
mPrfsVideoDevice->setupUi(this);
// set a default image for the webcam widget, in case the user does not have a video device
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(false);
mPrfsVideoDevice->mVideoImageLabel->setPixmap(KIcon("camera-web").pixmap(128,128));
connect(mPrfsVideoDevice->mDeviceKComboBox, SIGNAL(activated(int)), this, SLOT(slotDeviceKComboBoxChanged(int)));
connect(mPrfsVideoDevice->mInputKComboBox, SIGNAL(activated(int)), this, SLOT(slotInputKComboBoxChanged(int)));
connect(mPrfsVideoDevice->mStandardKComboBox, SIGNAL(activated(int)), this, SLOT(slotStandardKComboBoxChanged(int)));
mVideoDevicePool = Kopete::AV::VideoDevicePool::self();
if (EXIT_SUCCESS == mVideoDevicePool->open())
{
setupControls();
startCapturing();
}
mVideoDevicePool->fillDeviceKComboBox(mPrfsVideoDevice->mDeviceKComboBox);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
connect(mVideoDevicePool, SIGNAL(deviceRegistered(const QString &) ),
SLOT(deviceRegistered(const QString &)) );
connect(mVideoDevicePool, SIGNAL(deviceUnregistered(const QString &) ),
SLOT(deviceUnregistered(const QString &)) );
connect(&qtimer, SIGNAL(timeout()), this, SLOT(slotUpdateImage()) );
}
AVDeviceConfig::~AVDeviceConfig()
{
mVideoDevicePool->close();
clearControlGUIElements();
}
void AVDeviceConfig::setupControls()
{
int k = 0;
qint32 cval = 0;
clearControlGUIElements();
QList<Kopete::AV::NumericVideoControl> numericCtrls;
QList<Kopete::AV::BooleanVideoControl> booleanCtrls;
QList<Kopete::AV::MenuVideoControl> menuCtrls;
QList<Kopete::AV::ActionVideoControl> actionCtrls;
numericCtrls = mVideoDevicePool->getSupportedNumericControls();
booleanCtrls = mVideoDevicePool->getSupportedBooleanControls();
menuCtrls = mVideoDevicePool->getSupportedMenuControls();
actionCtrls = mVideoDevicePool->getSupportedActionControls();
kDebug() << "Supported controls:" << numericCtrls.size() << "numeric," << booleanCtrls.size()
<< "boolean," << menuCtrls.size() << "menus," << actionCtrls.size() << "actions.";
/* SETUP GUI-elements */
// Numeric Controls: => Slider
for (k=0; k<numericCtrls.size(); k++)
{
mVideoDevicePool->getControlValue(numericCtrls.at(k).id, &cval);
addSliderControlElement(numericCtrls.at(k).id, numericCtrls.at(k).name, numericCtrls.at(k).value_min, numericCtrls.at(k).value_max, numericCtrls.at(k).value_step, cval);
}
// Boolean Controls: => Checkbox
for (k=0; k<booleanCtrls.size(); k++)
{
mVideoDevicePool->getControlValue(booleanCtrls.at(k).id, &cval);
addCheckBoxControlElement(booleanCtrls.at(k).id, booleanCtrls.at(k).name, cval);
}
// Menu Controls: => Combobox
for (k=0; k<menuCtrls.size(); k++)
{
mVideoDevicePool->getControlValue(menuCtrls.at(k).id, &cval);
addPopupMenuControlElement(menuCtrls.at(k).id, menuCtrls.at(k).name, menuCtrls.at(k).options, cval);
}
// Action Controls: => Button
for (k=0; k<actionCtrls.size(); k++)
addButtonControlElement(actionCtrls.at(k).id, actionCtrls.at(k).name);
/* TODO: check success of mVideoDevicePool->getControlValue() */
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(1, numericCtrls.size());
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(2, booleanCtrls.size() + menuCtrls.size());
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(3, actionCtrls.size());
}
void AVDeviceConfig::clearControlGUIElements()
{
for (int k=0; k<ctrlWidgets.size(); k++)
delete ctrlWidgets.at(k);
ctrlWidgets.clear();
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(1, false);
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(2, false);
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(3, false);
}
void AVDeviceConfig::addSliderControlElement(int cid, QString title, int min, int max, int step, int value)
{
int insert_row = mPrfsVideoDevice->sliders_gridLayout->rowCount();
QLabel *label = new QLabel( title + ":", mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->sliders_gridLayout->addWidget( label, insert_row, 0 );
IdSlider *slider = new IdSlider(cid, Qt::Horizontal, mPrfsVideoDevice->VideoTabWidget);
mPrfsVideoDevice->sliders_gridLayout->addWidget( slider, insert_row, 1 );
slider->setMinimum( min );
slider->setMaximum( max );
slider->setSliderPosition( value );
slider->setTickInterval( step );
connect( slider, SIGNAL( valueChanged(uint, int) ), this, SLOT( changeVideoControlValue(uint, int) ) );
ctrlWidgets.push_back(label);
ctrlWidgets.push_back(slider);
}
void AVDeviceConfig::addCheckBoxControlElement(int cid, QString title, bool value)
{
IdCheckBox *checkbox = new IdCheckBox( cid, mPrfsVideoDevice->VideoTabWidget );
checkbox->setText( title );
mPrfsVideoDevice->checkboxOptions_verticalLayout->addWidget( checkbox );
checkbox->setChecked( value );
connect( checkbox, SIGNAL( stateChanged(uint, int) ), this, SLOT( changeVideoControlValue(uint, int) ) );
ctrlWidgets.push_back(checkbox);
}
void AVDeviceConfig::addPopupMenuControlElement(int cid, QString title, QStringList options, int menuindex)
{
int insert_row = mPrfsVideoDevice->menuOptions_gridLayout->rowCount();
QLabel *label = new QLabel( title + ":", mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->menuOptions_gridLayout->addWidget( label, insert_row, 0 );
IdComboBox *combobox = new IdComboBox( cid, mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->menuOptions_gridLayout->addWidget( combobox, insert_row, 1 );
combobox->addItems( options );
combobox->setCurrentIndex( menuindex );
connect( combobox, SIGNAL( currentIndexChanged(uint, int) ), this, SLOT( changeVideoControlValue(uint, int) ) );
ctrlWidgets.push_back(label);
ctrlWidgets.push_back(combobox);
}
void AVDeviceConfig::addButtonControlElement(int cid, QString title)
{
int insert_row = mPrfsVideoDevice->actions_gridLayout->rowCount();
QLabel *label = new QLabel( title + ":", mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->actions_gridLayout->addWidget( label, insert_row, 0 );
IdPushButton *button = new IdPushButton( cid, mPrfsVideoDevice->VideoTabWidget );
button->setText( i18n("Execute") );
mPrfsVideoDevice->actions_gridLayout->addWidget( button, insert_row, 1 );
connect( button, SIGNAL( pressed(uint) ), this, SLOT( changeVideoControlValue(uint) ) );
ctrlWidgets.push_back(label);
ctrlWidgets.push_back(button);
}
/*!
\fn VideoDeviceConfig::save()
*/
void AVDeviceConfig::save()
{
/// @todo implement me
kDebug() << "kopete:config (avdevice): save() called. ";
mVideoDevicePool->saveCurrentDeviceConfig();
}
/*!
\fn VideoDeviceConfig::load()
*/
void AVDeviceConfig::load()
{
/// @todo implement me
}
void AVDeviceConfig::slotSettingsChanged(bool)
{
emit changed(true);
}
void AVDeviceConfig::slotValueChanged(int)
{
emit changed( true );
}
void AVDeviceConfig::slotDeviceKComboBoxChanged(int)
{
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) called. ";
int newdevice = mPrfsVideoDevice->mDeviceKComboBox->currentIndex();
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) Current device: " << mVideoDevicePool->currentDevice() << "New device: " << newdevice;
if ((newdevice >= 0 && newdevice < mVideoDevicePool->size()) && (newdevice != mVideoDevicePool->currentDevice()))
{
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) should change device. ";
stopCapturing();
mVideoDevicePool->close();
mVideoDevicePool->open(newdevice);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
setupControls();
startCapturing();
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) called. ";
emit changed( true );
}
}
void AVDeviceConfig::slotInputKComboBoxChanged(int)
{
int newinput = mPrfsVideoDevice->mInputKComboBox->currentIndex();
if ((newinput < mVideoDevicePool->inputs()) && (newinput != mVideoDevicePool->currentInput()))
{
stopCapturing();
mVideoDevicePool->selectInput(mPrfsVideoDevice->mInputKComboBox->currentIndex());
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
setupControls();
startCapturing();
emit changed( true );
}
}
void AVDeviceConfig::slotStandardKComboBoxChanged(int)
{
emit changed( true );
}
void AVDeviceConfig::changeVideoControlValue(unsigned int id, int value)
{
mVideoDevicePool->setControlValue(id, value);
emit changed( true );
/* TODO: Check success, fallback */
}
void AVDeviceConfig::slotUpdateImage()
{
mVideoDevicePool->getFrame();
mVideoDevicePool->getImage(&qimage);
mPrfsVideoDevice->mVideoImageLabel->setPixmap(QPixmap::fromImage(qimage));
//kDebug() << "kopete (avdeviceconfig_videoconfig): Image updated.";
}
void AVDeviceConfig::deviceRegistered( const QString & udi )
{
mVideoDevicePool->fillDeviceKComboBox(mPrfsVideoDevice->mDeviceKComboBox);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
if (mVideoDevicePool->size() < 2) // otherwise we are already capturing
{
if (EXIT_SUCCESS == mVideoDevicePool->open())
{
setupControls();
startCapturing();
}
}
}
void AVDeviceConfig::deviceUnregistered( const QString & udi )
{
mVideoDevicePool->fillDeviceKComboBox(mPrfsVideoDevice->mDeviceKComboBox);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
if (capturingDevice_udi == udi)
{
qtimer.stop();
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(false);
mPrfsVideoDevice->mVideoImageLabel->setPixmap(KIcon("camera-web").pixmap(128,128));
capturingDevice_udi.clear();
clearControlGUIElements();
if (mVideoDevicePool->size())
{
if (EXIT_SUCCESS == mVideoDevicePool->open())
{
setupControls();
startCapturing();
}
}
}
}
void AVDeviceConfig::startCapturing()
{
mVideoDevicePool->setSize(320, 240);
mVideoDevicePool->startCapturing();
capturingDevice_udi = mVideoDevicePool->currentDeviceUdi();
qtimer.start(40);
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(true);
}
void AVDeviceConfig::stopCapturing()
{
qtimer.stop();
mVideoDevicePool->stopCapturing();
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(false);
mPrfsVideoDevice->mVideoImageLabel->setPixmap(KIcon("camera-web").pixmap(128,128));
capturingDevice_udi.clear();
}
<|endoftext|> |
<commit_before>#include <Render/Pipelining/Pipelines/CustomPipeline/BasicPipeline.hh>
#include <Render/ProgramResources/Types/Uniform/Mat4.hh>
#include <Render/ProgramResources/Types/Uniform/Mat4Array255.hh>
#include <Render/ProgramResources/Types/Uniform/Vec1.hh>
#include <Render/Program.hh>
#include <Render/Pipelining/Render/Rendering.hh>
#include <Render/OpenGLTask/Tasks.hh>
#include <Render/GeometryManagement/Painting/Painter.hh>
#include <Render/Properties/Properties.hh>
#include <Render/GeometryManagement/Painting/PaintingManager.hh>
#include <SpacePartitioning/Ouptut/RenderPipeline.hh>
#include <SpacePartitioning/Ouptut/RenderPainter.hh>
#include <SpacePartitioning/Ouptut/RenderCamera.hh>
#include <vector>
#include <memory>
#define VERTEX_SHADER_BASIC "../../Shaders/test_pipeline_1.vp", GL_VERTEX_SHADER
#define FRAGMENT_SHADER_BASIC "../../Shaders/test_pipeline_1.fp", GL_FRAGMENT_SHADER
#define VERTEX_SHADER_SKIN "../../Shaders/test_pipeline_1_skinning.vp", GL_VERTEX_SHADER
#define FRAGMENT_SHADER_SKIN "../../Shaders/test_pipeline_1.fp", GL_FRAGMENT_SHADER
namespace AGE
{
BasicPipeline::BasicPipeline(std::shared_ptr<PaintingManager> const &painter_manager) :
ARenderingPipeline(std::string("BasicName"), painter_manager)
{
_programs.resize(TOTAL);
std::vector<std::shared_ptr<UnitProg>> unitsBasic = { std::make_shared<UnitProg>(VERTEX_SHADER_BASIC), std::make_shared<UnitProg>(FRAGMENT_SHADER_BASIC) };
std::vector<std::shared_ptr<UnitProg>> unitsSkin = { std::make_shared<UnitProg>(VERTEX_SHADER_SKIN), std::make_shared<UnitProg>(FRAGMENT_SHADER_SKIN) };
_programs[RENDER_SKINNED] = std::make_shared<Program>(Program(std::string("basic program skin"), unitsSkin));
_programs[RENDER_BASIC] = std::make_shared<Program>(Program(std::string("basic program"), unitsBasic));
_rendering_list.resize(TOTAL);
_rendering_list[RENDER_SKINNED] = std::make_shared<Rendering>([&](FUNCTION_ARGS) {
// painter->draw(GL_TRIANGLES, _programs[RENDER_SKINNED], properties, vertices);
});
_rendering_list[RENDER_BASIC] = std::make_shared<Rendering>([&](FUNCTION_ARGS) {
// painter->draw(GL_TRIANGLES, _programs[RENDER_BASIC], properties, vertices);
});
// auto &rendering = std::static_pointer_cast<Rendering>(_rendering_list[RENDER]);
}
BasicPipeline::BasicPipeline(BasicPipeline &&move) :
ARenderingPipeline(std::move(move))
{
}
IRenderingPipeline &BasicPipeline::render(ARGS_FUNCTION_RENDER)
{
OpenGLTasks::set_depth_test(true);
OpenGLTasks::set_clear_color(glm::vec4(0, 0, 0.2, 1));
OpenGLTasks::clear_buffer();
//*_programs[RENDER]->get_resource<Mat4Array255>("bones") = &(infos.view);
//*_programs[RENDER]->get_resource<Vec1>("skinned") = 0.0f;
for (auto key : pipeline.keys) {
auto &curPainter = _painter_manager->get_painter(key.painter);
int currentRenderIdx = -1;
if (curPainter->coherent(_programs[RENDER_SKINNED]))
{
currentRenderIdx = RENDER_SKINNED;
}
else if (curPainter->coherent(_programs[RENDER_BASIC]))
{
currentRenderIdx = RENDER_BASIC;
}
assert(currentRenderIdx != -1);
_programs[currentRenderIdx]->use();
*_programs[currentRenderIdx]->get_resource<Mat4>("projection_matrix") = infos.projection;
*_programs[currentRenderIdx]->get_resource<Mat4>("view_matrix") = infos.view;
_rendering_list[currentRenderIdx]->render(key.properties, key.vertices, curPainter);
}
return (*this);
}
}<commit_msg>Still draw nothing<commit_after>#include <Render/Pipelining/Pipelines/CustomPipeline/BasicPipeline.hh>
#include <Render/ProgramResources/Types/Uniform/Mat4.hh>
#include <Render/ProgramResources/Types/Uniform/Mat4Array255.hh>
#include <Render/ProgramResources/Types/Uniform/Vec1.hh>
#include <Render/Program.hh>
#include <Render/Pipelining/Render/Rendering.hh>
#include <Render/OpenGLTask/Tasks.hh>
#include <Render/GeometryManagement/Painting/Painter.hh>
#include <Render/Properties/Properties.hh>
#include <Render/GeometryManagement/Painting/PaintingManager.hh>
#include <SpacePartitioning/Ouptut/RenderPipeline.hh>
#include <SpacePartitioning/Ouptut/RenderPainter.hh>
#include <SpacePartitioning/Ouptut/RenderCamera.hh>
#include <vector>
#include <memory>
#define VERTEX_SHADER_BASIC "../../Shaders/test_pipeline_1.vp", GL_VERTEX_SHADER
#define FRAGMENT_SHADER_BASIC "../../Shaders/test_pipeline_1.fp", GL_FRAGMENT_SHADER
#define VERTEX_SHADER_SKIN "../../Shaders/test_pipeline_1_skinning.vp", GL_VERTEX_SHADER
#define FRAGMENT_SHADER_SKIN "../../Shaders/test_pipeline_1.fp", GL_FRAGMENT_SHADER
namespace AGE
{
BasicPipeline::BasicPipeline(std::shared_ptr<PaintingManager> const &painter_manager) :
ARenderingPipeline(std::string("BasicName"), painter_manager)
{
_programs.resize(TOTAL);
std::vector<std::shared_ptr<UnitProg>> unitsBasic = { std::make_shared<UnitProg>(VERTEX_SHADER_BASIC), std::make_shared<UnitProg>(FRAGMENT_SHADER_BASIC) };
std::vector<std::shared_ptr<UnitProg>> unitsSkin = { std::make_shared<UnitProg>(VERTEX_SHADER_SKIN), std::make_shared<UnitProg>(FRAGMENT_SHADER_SKIN) };
_programs[RENDER_SKINNED] = std::make_shared<Program>(Program(std::string("basic program skin"), unitsSkin));
_programs[RENDER_BASIC] = std::make_shared<Program>(Program(std::string("basic program"), unitsBasic));
_rendering_list.resize(TOTAL);
_rendering_list[RENDER_SKINNED] = std::make_shared<Rendering>([&](FUNCTION_ARGS) {
painter->draw(GL_TRIANGLES, _programs[RENDER_SKINNED], properties, vertices);
});
_rendering_list[RENDER_BASIC] = std::make_shared<Rendering>([&](FUNCTION_ARGS) {
painter->draw(GL_TRIANGLES, _programs[RENDER_BASIC], properties, vertices);
});
// auto &rendering = std::static_pointer_cast<Rendering>(_rendering_list[RENDER]);
}
BasicPipeline::BasicPipeline(BasicPipeline &&move) :
ARenderingPipeline(std::move(move))
{
}
IRenderingPipeline &BasicPipeline::render(ARGS_FUNCTION_RENDER)
{
OpenGLTasks::set_depth_test(true);
OpenGLTasks::set_clear_color(glm::vec4(0, 0, 0.2, 1));
OpenGLTasks::clear_buffer();
//*_programs[RENDER]->get_resource<Mat4Array255>("bones") = &(infos.view);
//*_programs[RENDER]->get_resource<Vec1>("skinned") = 0.0f;
for (auto key : pipeline.keys) {
auto &curPainter = _painter_manager->get_painter(key.painter);
int currentRenderIdx = -1;
if (curPainter->coherent(_programs[RENDER_SKINNED]))
{
currentRenderIdx = RENDER_SKINNED;
}
else if (curPainter->coherent(_programs[RENDER_BASIC]))
{
currentRenderIdx = RENDER_BASIC;
}
assert(currentRenderIdx != -1);
_programs[currentRenderIdx]->use();
*_programs[currentRenderIdx]->get_resource<Mat4>("projection_matrix") = infos.projection;
*_programs[currentRenderIdx]->get_resource<Mat4>("view_matrix") = infos.view;
_rendering_list[currentRenderIdx]->render(key.properties, key.vertices, curPainter);
}
return (*this);
}
}<|endoftext|> |
<commit_before>/*
* File: RSTNode.hpp
* Author: Joshua Yuen cs100vbc
* Author: Jay Dey cs100vaj
*/
#ifndef RSTNODE_HPP
#define RSTNODE_HPP
#include "BSTNode.hpp"
#include <stdlib.h>
template <typename Data>
class RSTNode : public BSTNode<Data>
{
protected:
unsigned int priority;
public:
//TODO: implement this constructor
RSTNode(Data const & d) : BSTNode<Data>(d)
{
priority = rand();
}
};
#endif // RSTNODE_HPP
<commit_msg>Stored priority variable of RSTNode inside info field of BSTNode object<commit_after>/*
* File: RSTNode.hpp
* Author: Joshua Yuen cs100vbc
* Author: Jay Dey cs100vaj
*/
#ifndef RSTNODE_HPP
#define RSTNODE_HPP
#include "BSTNode.hpp"
#include <stdlib.h>
template <typename Data>
class RSTNode : public BSTNode<Data>
{
protected:
unsigned int priority;
public:
//TODO: implement this constructor
RSTNode(Data const & d) : BSTNode<Data>(d)
{
priority = rand(); //maybe need to bound this somehow?
this->info = priority;
}
};
#endif // RSTNODE_HPP
<|endoftext|> |
<commit_before>#include <mist/io/raw.h>
#include <mist/draw.h>
#include <iostream>
#include "ct_image_window.h"
#include <FL/Fl_File_Chooser.H>
#include <mist/filter/median.h>
#include <mist/filter/distance.h>
#include <mist/filter/labeling.h>
#include <mist/filter/morphology.h>
#include <mist/filter/linear.h>
#include <mist/filter/decomposition.h>
#include <mist/timer.h>
struct progress_callback
{
Fl_Progress *f_;
bool operator()( double percent ) const
{
if( percent > 100.0 )
{
f_->hide( );
Fl::wait( 0 );
return( true );
}
else if( !f_->visible( ) )
{
f_->show( );
}
f_->value( static_cast< float >( percent ) );
Fl::wait( 0 );
return( true );
}
progress_callback( Fl_Progress *f = NULL ) : f_( f ){ }
};
struct fd_progress_callback
{
/// @brief }`̐isԂ
//!
//! @param[in] loop c ݂̌JԂ
//! @param[in] label_num c ݂̍ő僉xԍ
//! @param[in] radius c ݏ̔a
//! @param[in] in c ͉摜
//! @param[in] out c o̓x摜
//!
template < class Array >
void operator()( size_t loop, size_t label_num, double radius, const Array &in, const Array &out ) const
{
std::cerr << " \r";
std::cerr << "looping ... " << loop << ", label = " << label_num << ", radius = " << radius << "\r";
}
};
void ct_draw_area::draw( )
{
mist::draw_image( buff, w( ), h( ) );
}
void ct_draw_area::draw_image( )
{
if( ct.empty( ) )
{
return;
}
if( draw_flag_ )
{
return;
}
draw_flag_ = true;
if( buff.width( ) != ct.width( ) || buff.height( ) != ct.height( ) )
{
buff.resize( ct.width( ), ct.height( ) );
}
buff.reso1( ct.reso1( ) );
buff.reso2( ct.reso2( ) );
mist::array3< short >::size_type i, j;
double pixel;
for( j = 0 ; j < ct.height( ) ; j++ )
{
for( i = 0 ; i < ct.width( ) ; i++ )
{
pixel = ( ct( i, j, index_ ) - window_level_ ) / window_width_ * 256.0 + 128.0;
pixel = pixel < 0.0 ? 0.0 : pixel;
pixel = pixel > 255.0 ? 255.0 : pixel;
buff( i, j ) = static_cast< unsigned char >( pixel );
}
}
draw_flag_ = false;
}
void ct_draw_area::read_image( ct_image_window *wnd )
{
const char *filename = fl_file_chooser( "Open", "*", "" );
if( filename == NULL ) return;
size_type w = 512;
size_type h = 512;
size_type d = 189;
double x = 0.625;
double y = 0.625;
double z = 1.0;
ct_value_type offset = 0;
parameter_window window;
window.width->value( w );
window.height->value( h );
window.depth->value( d );
window.sizeX->value( x );
window.sizeY->value( y );
window.sizeZ->value( z );
window.offset->value( offset );
if( window.show( ) )
{
w = static_cast< size_type >( window.width->value( ) );
h = static_cast< size_type >( window.height->value( ) );
d = static_cast< size_type >( window.depth->value( ) );
x = window.sizeX->value( );
y = window.sizeY->value( );
z = window.sizeZ->value( );
offset = static_cast< ct_value_type >( window.offset->value( ) );
if( mist::read_raw( ct, filename, w, h, d, x, y, z, offset, false, progress_callback( wnd->progress_bar ) ) )
{
wnd->Indx->range( 0, ct.depth( ) - 1 );
}
else
{
wnd->Indx->range( 0, 0 );
}
wnd->Indx->value( 0 );
change_index( 0 );
}
}
void ct_draw_area::write_image( ct_image_window *w )
{
const char *filename = fl_file_chooser( "Save", "*", "" );
if( filename == NULL ) return;
mist::write_raw_gz( ct, filename, 0, false, progress_callback( w->progress_bar ) );
}
void ct_draw_area::change_index( size_type index )
{
if( 0 <= index && index < ct.depth( ) )
{
index_ = index;
draw_image( );
redraw( );
}
}
void ct_draw_area::change_window_level( double wl )
{
window_level_ = wl;
draw_image( );
redraw( );
}
void ct_draw_area::change_window_width( double ww )
{
window_width_ = ww;
draw_image( );
redraw( );
}
void ct_draw_area::median_filter1D( ct_image_window *wnd )
{
mist::array< double > a( 7 ), b( 7 );
a[ 0 ] = 0.2;
a[ 1 ] = 4.1;
a[ 2 ] = 2.5;
a[ 3 ] = 3.6;
a[ 4 ] = 2.2;
a[ 5 ] = 4.3;
a[ 6 ] = 0.1;
std::cout << a << std::endl;
mist::median( a, b, 3 );
std::cout << b << std::endl;
mist::array< int > aa( a ), bb( 7 );
std::cout << aa << std::endl;
mist::median( aa, bb, 3 );
std::cout << bb << std::endl;
}
void ct_draw_area::median_filter2D( ct_image_window *wnd )
{
mist::array2< double > a( 5, 5 ), b( 5, 5 );
a( 0, 0 ) = 0.1; a( 0, 1 ) = 0.2; a( 0, 2 ) = 0.1; a( 0, 3 ) = 0.6; a( 0, 4 ) = 0.4;
a( 1, 0 ) = 0.3; a( 1, 1 ) = 4.1; a( 1, 2 ) = 5.2; a( 1, 3 ) = 4.7; a( 1, 4 ) = 0.3;
a( 2, 0 ) = 0.2; a( 2, 1 ) = 3.5; a( 2, 2 ) = 2.8; a( 2, 3 ) = 3.9; a( 2, 4 ) = 0.8;
a( 3, 0 ) = 0.4; a( 3, 1 ) = 4.2; a( 3, 2 ) = 5.9; a( 3, 3 ) = 4.2; a( 3, 4 ) = 0.9;
a( 4, 0 ) = 0.2; a( 4, 1 ) = 0.3; a( 4, 2 ) = 0.1; a( 4, 3 ) = 0.1; a( 4, 4 ) = 0.4;
std::cout << a << std::endl;
mist::median( a, b, 3, 1 );
std::cout << b << std::endl;
mist::array2< int > aa( a );
mist::array2< unsigned int > bb;
std::cout << aa << std::endl;
mist::median( aa, bb, 3, 1 );
std::cout << bb << std::endl;
}
void ct_draw_area::median_filter3D( ct_image_window *wnd )
{
if( ct.empty( ) ) return;
mist::array3< short > tmp = ct;
{
mist::timer t;
mist::median( tmp, ct, 3, 3, 3, progress_callback( wnd->progress_bar ), 0 );
std::cout << "Computation Time: " << t.elapse( ) << std::endl;
}
redraw( );
Fl::wait( 0 );
}
void ct_draw_area::normalization_filter3D( ct_image_window *wnd )
{
if( ct.empty( ) ) return;
mist::array3< short > tmp = ct;
{
mist::timer t;
mist::gaussian( tmp, ct );
std::cout << "Computation Time: " << t.elapse( ) << std::endl;
}
redraw( );
Fl::wait( 0 );
}
void ct_draw_area::euclidean_distance_transform( ct_image_window *wnd )
{
if( ct.empty( ) ) return;
mist::array3< double > tmp1 = ct, tmp2 = ct;
{
mist::timer t;
mist::calvin::distance_transform( tmp1, tmp1 );
std::cout << "Computation time for Calvin: " << t << " sec" << std::endl;
}
{
mist::timer t;
mist::euclidean::distance_transform( tmp2, tmp2 );
std::cout << "Computation time for Saito: " << t << " sec" << std::endl;
}
double err = 0.0;
for( size_t i = 0 ; i < tmp1.size( ) ; i++ )
{
err += ( tmp1[ i ] - tmp2[ i ] ) * ( tmp1[ i ] - tmp2[ i ] );
ct[ i ] = static_cast< short >( tmp1[ i ] - tmp2[ i ] );
}
std::cout << "Error: " << err << std::endl;
redraw( );
Fl::wait( 0 );
}
void ct_draw_area::labeling6( ct_image_window *wnd )
{
if( ct.empty( ) ) return;
size_t label_num = mist::labeling6( ct, ct );
printf( "label_num = %d\n", label_num );
redraw( );
Fl::wait( 0 );
}
void ct_draw_area::labeling26( ct_image_window *wnd )
{
if( ct.empty( ) ) return;
size_t label_num = mist::labeling26( ct, ct );
printf( "label_num = %d\n", label_num );
redraw( );
Fl::wait( 0 );
}
void ct_draw_area::erosion( ct_image_window *wnd )
{
{
mist::timer t;
mist::erosion( ct, 7 );
std::cout << "Computation Time: " << t.elapse( ) << std::endl;
}
}
void ct_draw_area::dilation( ct_image_window *wnd )
{
{
mist::timer t;
mist::dilation( ct, 7 );
std::cout << "Computation Time: " << t.elapse( ) << std::endl;
}
}
void ct_draw_area::opening( ct_image_window *wnd )
{
{
mist::timer t;
mist::opening( ct, 7 );
std::cout << "Computation Time: " << t.elapse( ) << std::endl;
}
}
void ct_draw_area::closing( ct_image_window *wnd )
{
{
mist::timer t;
mist::closing( ct, 7 );
std::cout << "Computation Time: " << t.elapse( ) << std::endl;
}
}
void ct_draw_area::figure_decomposition( ct_image_window *wnd )
{
{
mist::timer t;
size_t label_num = mist::figure_decomposition( ct, ct, fd_progress_callback( ) );
std::cerr << std::endl << "Label: " << label_num << ", Computation time: " << t << " sec" << std::endl;
}
}
int main( int argc, char *argv[] )
{
ct_image_window window;
Fl::gl_visual( FL_RGB );
window.show( );
Fl::background( 212, 208, 200 );
Fl::run();
return( 0 );
}
<commit_msg>図形分割のコンパイル引数の変更に伴う修正<commit_after>#include <mist/io/raw.h>
#include <mist/draw.h>
#include <iostream>
#include "ct_image_window.h"
#include <FL/Fl_File_Chooser.H>
#include <mist/filter/median.h>
#include <mist/filter/distance.h>
#include <mist/filter/labeling.h>
#include <mist/filter/morphology.h>
#include <mist/filter/linear.h>
#include <mist/filter/decomposition.h>
#include <mist/timer.h>
struct progress_callback
{
Fl_Progress *f_;
bool operator()( double percent ) const
{
if( percent > 100.0 )
{
f_->hide( );
Fl::wait( 0 );
return( true );
}
else if( !f_->visible( ) )
{
f_->show( );
}
f_->value( static_cast< float >( percent ) );
Fl::wait( 0 );
return( true );
}
progress_callback( Fl_Progress *f = NULL ) : f_( f ){ }
};
struct fd_progress_callback
{
/// @brief }`̐isԂ
//!
//! @param[in] loop c ݂̌JԂ
//! @param[in] label_num c ݂̍ő僉xԍ
//! @param[in] radius c ݏ̔a
//! @param[in] in c ͉摜
//! @param[in] out c o̓x摜
//!
template < class Array >
void operator()( size_t loop, size_t label_num, double radius, const Array &in, const Array &out ) const
{
std::cerr << " \r";
std::cerr << "looping ... " << loop << ", label = " << label_num << ", radius = " << radius << "\r";
}
};
void ct_draw_area::draw( )
{
mist::draw_image( buff, w( ), h( ) );
}
void ct_draw_area::draw_image( )
{
if( ct.empty( ) )
{
return;
}
if( draw_flag_ )
{
return;
}
draw_flag_ = true;
if( buff.width( ) != ct.width( ) || buff.height( ) != ct.height( ) )
{
buff.resize( ct.width( ), ct.height( ) );
}
buff.reso1( ct.reso1( ) );
buff.reso2( ct.reso2( ) );
mist::array3< short >::size_type i, j;
double pixel;
for( j = 0 ; j < ct.height( ) ; j++ )
{
for( i = 0 ; i < ct.width( ) ; i++ )
{
pixel = ( ct( i, j, index_ ) - window_level_ ) / window_width_ * 256.0 + 128.0;
pixel = pixel < 0.0 ? 0.0 : pixel;
pixel = pixel > 255.0 ? 255.0 : pixel;
buff( i, j ) = static_cast< unsigned char >( pixel );
}
}
draw_flag_ = false;
}
void ct_draw_area::read_image( ct_image_window *wnd )
{
const char *filename = fl_file_chooser( "Open", "*", "" );
if( filename == NULL ) return;
size_type w = 512;
size_type h = 512;
size_type d = 189;
double x = 0.625;
double y = 0.625;
double z = 1.0;
ct_value_type offset = 0;
parameter_window window;
window.width->value( w );
window.height->value( h );
window.depth->value( d );
window.sizeX->value( x );
window.sizeY->value( y );
window.sizeZ->value( z );
window.offset->value( offset );
if( window.show( ) )
{
w = static_cast< size_type >( window.width->value( ) );
h = static_cast< size_type >( window.height->value( ) );
d = static_cast< size_type >( window.depth->value( ) );
x = window.sizeX->value( );
y = window.sizeY->value( );
z = window.sizeZ->value( );
offset = static_cast< ct_value_type >( window.offset->value( ) );
if( mist::read_raw( ct, filename, w, h, d, x, y, z, offset, false, progress_callback( wnd->progress_bar ) ) )
{
wnd->Indx->range( 0, ct.depth( ) - 1 );
}
else
{
wnd->Indx->range( 0, 0 );
}
wnd->Indx->value( 0 );
change_index( 0 );
}
}
void ct_draw_area::write_image( ct_image_window *w )
{
const char *filename = fl_file_chooser( "Save", "*", "" );
if( filename == NULL ) return;
mist::write_raw_gz( ct, filename, 0, false, progress_callback( w->progress_bar ) );
}
void ct_draw_area::change_index( size_type index )
{
if( 0 <= index && index < ct.depth( ) )
{
index_ = index;
draw_image( );
redraw( );
}
}
void ct_draw_area::change_window_level( double wl )
{
window_level_ = wl;
draw_image( );
redraw( );
}
void ct_draw_area::change_window_width( double ww )
{
window_width_ = ww;
draw_image( );
redraw( );
}
void ct_draw_area::median_filter1D( ct_image_window *wnd )
{
mist::array< double > a( 7 ), b( 7 );
a[ 0 ] = 0.2;
a[ 1 ] = 4.1;
a[ 2 ] = 2.5;
a[ 3 ] = 3.6;
a[ 4 ] = 2.2;
a[ 5 ] = 4.3;
a[ 6 ] = 0.1;
std::cout << a << std::endl;
mist::median( a, b, 3 );
std::cout << b << std::endl;
mist::array< int > aa( a ), bb( 7 );
std::cout << aa << std::endl;
mist::median( aa, bb, 3 );
std::cout << bb << std::endl;
}
void ct_draw_area::median_filter2D( ct_image_window *wnd )
{
mist::array2< double > a( 5, 5 ), b( 5, 5 );
a( 0, 0 ) = 0.1; a( 0, 1 ) = 0.2; a( 0, 2 ) = 0.1; a( 0, 3 ) = 0.6; a( 0, 4 ) = 0.4;
a( 1, 0 ) = 0.3; a( 1, 1 ) = 4.1; a( 1, 2 ) = 5.2; a( 1, 3 ) = 4.7; a( 1, 4 ) = 0.3;
a( 2, 0 ) = 0.2; a( 2, 1 ) = 3.5; a( 2, 2 ) = 2.8; a( 2, 3 ) = 3.9; a( 2, 4 ) = 0.8;
a( 3, 0 ) = 0.4; a( 3, 1 ) = 4.2; a( 3, 2 ) = 5.9; a( 3, 3 ) = 4.2; a( 3, 4 ) = 0.9;
a( 4, 0 ) = 0.2; a( 4, 1 ) = 0.3; a( 4, 2 ) = 0.1; a( 4, 3 ) = 0.1; a( 4, 4 ) = 0.4;
std::cout << a << std::endl;
mist::median( a, b, 3, 1 );
std::cout << b << std::endl;
mist::array2< int > aa( a );
mist::array2< unsigned int > bb;
std::cout << aa << std::endl;
mist::median( aa, bb, 3, 1 );
std::cout << bb << std::endl;
}
void ct_draw_area::median_filter3D( ct_image_window *wnd )
{
if( ct.empty( ) ) return;
mist::array3< short > tmp = ct;
{
mist::timer t;
mist::median( tmp, ct, 3, 3, 3, progress_callback( wnd->progress_bar ), 0 );
std::cout << "Computation Time: " << t.elapse( ) << std::endl;
}
redraw( );
Fl::wait( 0 );
}
void ct_draw_area::normalization_filter3D( ct_image_window *wnd )
{
if( ct.empty( ) ) return;
mist::array3< short > tmp = ct;
{
mist::timer t;
mist::gaussian( tmp, ct );
std::cout << "Computation Time: " << t.elapse( ) << std::endl;
}
redraw( );
Fl::wait( 0 );
}
void ct_draw_area::euclidean_distance_transform( ct_image_window *wnd )
{
if( ct.empty( ) ) return;
mist::array3< double > tmp1 = ct, tmp2 = ct;
{
mist::timer t;
mist::calvin::distance_transform( tmp1, tmp1 );
std::cout << "Computation time for Calvin: " << t << " sec" << std::endl;
}
{
mist::timer t;
mist::euclidean::distance_transform( tmp2, tmp2 );
std::cout << "Computation time for Saito: " << t << " sec" << std::endl;
}
double err = 0.0;
for( size_t i = 0 ; i < tmp1.size( ) ; i++ )
{
err += ( tmp1[ i ] - tmp2[ i ] ) * ( tmp1[ i ] - tmp2[ i ] );
ct[ i ] = static_cast< short >( tmp1[ i ] - tmp2[ i ] );
}
std::cout << "Error: " << err << std::endl;
redraw( );
Fl::wait( 0 );
}
void ct_draw_area::labeling6( ct_image_window *wnd )
{
if( ct.empty( ) ) return;
size_t label_num = mist::labeling6( ct, ct );
printf( "label_num = %d\n", label_num );
redraw( );
Fl::wait( 0 );
}
void ct_draw_area::labeling26( ct_image_window *wnd )
{
if( ct.empty( ) ) return;
size_t label_num = mist::labeling26( ct, ct );
printf( "label_num = %d\n", label_num );
redraw( );
Fl::wait( 0 );
}
void ct_draw_area::erosion( ct_image_window *wnd )
{
{
mist::timer t;
mist::erosion( ct, 7 );
std::cout << "Computation Time: " << t.elapse( ) << std::endl;
}
}
void ct_draw_area::dilation( ct_image_window *wnd )
{
{
mist::timer t;
mist::dilation( ct, 7 );
std::cout << "Computation Time: " << t.elapse( ) << std::endl;
}
}
void ct_draw_area::opening( ct_image_window *wnd )
{
{
mist::timer t;
mist::opening( ct, 7 );
std::cout << "Computation Time: " << t.elapse( ) << std::endl;
}
}
void ct_draw_area::closing( ct_image_window *wnd )
{
{
mist::timer t;
mist::closing( ct, 7 );
std::cout << "Computation Time: " << t.elapse( ) << std::endl;
}
}
void ct_draw_area::figure_decomposition( ct_image_window *wnd )
{
{
mist::timer t;
size_t label_num = mist::figure_decomposition( ct, ct, -1, fd_progress_callback( ) );
std::cerr << std::endl << "Label: " << label_num << ", Computation time: " << t << " sec" << std::endl;
}
}
int main( int argc, char *argv[] )
{
ct_image_window window;
Fl::gl_visual( FL_RGB );
window.show( );
Fl::background( 212, 208, 200 );
Fl::run();
return( 0 );
}
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2006 Ulrich von Zadow
//
// 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
//
// Current versions can be found at www.libavg.de
//
// Original author of this file is Nick Hebner (hebnern@gmail.com).
//
#include "SDLAudioEngine.h"
#include "Dynamics.h"
#include "../base/Exception.h"
#include "../base/Logger.h"
#include "../base/ScopeTimer.h"
#include "../base/Profiler.h"
#include <iostream>
namespace avg {
using namespace std;
using namespace boost;
SDLAudioEngine::SDLAudioEngine()
: m_pTempBuffer(),
m_pMixBuffer(0),
m_pLimiter(0)
{
if (SDL_InitSubSystem(SDL_INIT_AUDIO)==-1) {
AVG_TRACE(Logger::ERROR, "Can't init SDL audio subsystem.");
exit(-1);
}
}
SDLAudioEngine::~SDLAudioEngine()
{
SDL_QuitSubSystem(SDL_INIT_AUDIO);
}
int SDLAudioEngine::getChannels()
{
return m_AP.m_Channels;
}
int SDLAudioEngine::getSampleRate()
{
return m_AP.m_SampleRate;
}
const AudioParams & SDLAudioEngine::getParams()
{
return m_AP;
}
void SDLAudioEngine::init(const AudioParams& AP, double volume)
{
AudioEngine::init(AP, volume);
m_AP = AP;
Dynamics<double, 2>* pLimiter = new Dynamics<double, 2>(m_AP.m_SampleRate);
pLimiter->setThreshold(0.); // in dB
pLimiter->setAttackTime(0.); // in seconds
pLimiter->setReleaseTime(0.05); // in seconds
pLimiter->setRmsTime(0.); // in seconds
pLimiter->setRatio(std::numeric_limits<double>::infinity());
pLimiter->setMakeupGain(0.); // in dB
m_pLimiter = pLimiter;
SDL_AudioSpec desired;
desired.freq = m_AP.m_SampleRate;
desired.format = AUDIO_S16SYS;
desired.channels = m_AP.m_Channels;
desired.silence = 0;
desired.samples = m_AP.m_OutputBufferSamples;
desired.callback = audioCallback;
desired.userdata = this;
if (SDL_OpenAudio(&desired, 0) < 0) {
//throw new Exception("Cannot open audio device");
}
}
void SDLAudioEngine::teardown()
{
mutex::scoped_lock Lock(m_Mutex);
SDL_PauseAudio(1);
SDL_CloseAudio();
getSources().clear();
if (m_pLimiter) {
delete m_pLimiter;
m_pLimiter = 0;
}
}
void SDLAudioEngine::setAudioEnabled(bool bEnabled)
{
mutex::scoped_lock Lock(m_Mutex);
AudioEngine::setAudioEnabled(bEnabled);
}
void SDLAudioEngine::play()
{
SDL_PauseAudio(0);
}
void SDLAudioEngine::pause()
{
SDL_PauseAudio(1);
}
void SDLAudioEngine::addSource(IAudioSource* pSource)
{
mutex::scoped_lock Lock(m_Mutex);
AudioEngine::addSource(pSource);
}
void SDLAudioEngine::removeSource(IAudioSource* pSource)
{
mutex::scoped_lock Lock(m_Mutex);
AudioEngine::removeSource(pSource);
}
void SDLAudioEngine::setVolume(double volume)
{
mutex::scoped_lock Lock(m_Mutex);
AudioEngine::setVolume(volume);
}
void SDLAudioEngine::mixAudio(Uint8 *pDestBuffer, int destBufferLen)
{
mutex::scoped_lock Lock(m_Mutex);
int numFrames = destBufferLen/(2*getChannels()); // 16 bit samples.
if (getSources().size() == 0) {
return;
}
if (!m_pTempBuffer || m_pTempBuffer->getNumFrames() < numFrames) {
if (m_pTempBuffer) {
delete m_pMixBuffer;
}
m_pTempBuffer = AudioBufferPtr(new AudioBuffer(numFrames, m_AP));
m_pMixBuffer = new double[getChannels()*numFrames];
}
for (int i=0; i<getChannels()*numFrames; ++i) {
m_pMixBuffer[i]=0;
}
AudioSourceList::iterator it;
for(it = getSources().begin(); it != getSources().end(); it++) {
m_pTempBuffer->clear();
(*it)->fillAudioBuffer(m_pTempBuffer);
addBuffers(m_pMixBuffer, m_pTempBuffer);
}
calcVolume(m_pMixBuffer, numFrames*getChannels(), getVolume());
for (int i=0; i<numFrames; ++i) {
m_pLimiter->process(m_pMixBuffer+i*getChannels());
for (int j=0; j<getChannels(); ++j) {
((short*)pDestBuffer)[i*2+j]=short(m_pMixBuffer[i*2+j]*32768);
}
}
}
void SDLAudioEngine::audioCallback(void *userData, Uint8 *audioBuffer, int audioBufferLen)
{
SDLAudioEngine *pThis = (SDLAudioEngine*)userData;
pThis->mixAudio(audioBuffer, audioBufferLen);
}
void SDLAudioEngine::addBuffers(double *pDest, AudioBufferPtr pSrc)
{
int numFrames = pSrc->getNumFrames();
short * pData = pSrc->getData();
for(int i = 0; i < numFrames*getChannels(); ++i) {
pDest[i] += pData[i]/32768.0;
}
}
void SDLAudioEngine::calcVolume(double *pBuffer, int numSamples, double volume)
{
// TODO: We need a VolumeFader class that keeps state.
for(int i = 0; i < numSamples; ++i) {
pBuffer[i] *= volume;
}
}
}
<commit_msg>Fixed mem leak in SDLAudioEngine.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2006 Ulrich von Zadow
//
// 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
//
// Current versions can be found at www.libavg.de
//
// Original author of this file is Nick Hebner (hebnern@gmail.com).
//
#include "SDLAudioEngine.h"
#include "Dynamics.h"
#include "../base/Exception.h"
#include "../base/Logger.h"
#include "../base/ScopeTimer.h"
#include "../base/Profiler.h"
#include <iostream>
namespace avg {
using namespace std;
using namespace boost;
SDLAudioEngine::SDLAudioEngine()
: m_pTempBuffer(),
m_pMixBuffer(0),
m_pLimiter(0)
{
if (SDL_InitSubSystem(SDL_INIT_AUDIO)==-1) {
AVG_TRACE(Logger::ERROR, "Can't init SDL audio subsystem.");
exit(-1);
}
}
SDLAudioEngine::~SDLAudioEngine()
{
if (m_pMixBuffer) {
delete[] m_pMixBuffer;
}
SDL_QuitSubSystem(SDL_INIT_AUDIO);
}
int SDLAudioEngine::getChannels()
{
return m_AP.m_Channels;
}
int SDLAudioEngine::getSampleRate()
{
return m_AP.m_SampleRate;
}
const AudioParams & SDLAudioEngine::getParams()
{
return m_AP;
}
void SDLAudioEngine::init(const AudioParams& AP, double volume)
{
AudioEngine::init(AP, volume);
m_AP = AP;
Dynamics<double, 2>* pLimiter = new Dynamics<double, 2>(m_AP.m_SampleRate);
pLimiter->setThreshold(0.); // in dB
pLimiter->setAttackTime(0.); // in seconds
pLimiter->setReleaseTime(0.05); // in seconds
pLimiter->setRmsTime(0.); // in seconds
pLimiter->setRatio(std::numeric_limits<double>::infinity());
pLimiter->setMakeupGain(0.); // in dB
m_pLimiter = pLimiter;
SDL_AudioSpec desired;
desired.freq = m_AP.m_SampleRate;
desired.format = AUDIO_S16SYS;
desired.channels = m_AP.m_Channels;
desired.silence = 0;
desired.samples = m_AP.m_OutputBufferSamples;
desired.callback = audioCallback;
desired.userdata = this;
if (SDL_OpenAudio(&desired, 0) < 0) {
//throw new Exception("Cannot open audio device");
}
}
void SDLAudioEngine::teardown()
{
mutex::scoped_lock Lock(m_Mutex);
SDL_PauseAudio(1);
SDL_CloseAudio();
getSources().clear();
if (m_pLimiter) {
delete m_pLimiter;
m_pLimiter = 0;
}
}
void SDLAudioEngine::setAudioEnabled(bool bEnabled)
{
mutex::scoped_lock Lock(m_Mutex);
AudioEngine::setAudioEnabled(bEnabled);
}
void SDLAudioEngine::play()
{
SDL_PauseAudio(0);
}
void SDLAudioEngine::pause()
{
SDL_PauseAudio(1);
}
void SDLAudioEngine::addSource(IAudioSource* pSource)
{
mutex::scoped_lock Lock(m_Mutex);
AudioEngine::addSource(pSource);
}
void SDLAudioEngine::removeSource(IAudioSource* pSource)
{
mutex::scoped_lock Lock(m_Mutex);
AudioEngine::removeSource(pSource);
}
void SDLAudioEngine::setVolume(double volume)
{
mutex::scoped_lock Lock(m_Mutex);
AudioEngine::setVolume(volume);
}
void SDLAudioEngine::mixAudio(Uint8 *pDestBuffer, int destBufferLen)
{
mutex::scoped_lock Lock(m_Mutex);
int numFrames = destBufferLen/(2*getChannels()); // 16 bit samples.
if (getSources().size() == 0) {
return;
}
if (!m_pTempBuffer || m_pTempBuffer->getNumFrames() < numFrames) {
if (m_pTempBuffer) {
delete[] m_pMixBuffer;
}
m_pTempBuffer = AudioBufferPtr(new AudioBuffer(numFrames, m_AP));
m_pMixBuffer = new double[getChannels()*numFrames];
}
for (int i=0; i<getChannels()*numFrames; ++i) {
m_pMixBuffer[i]=0;
}
AudioSourceList::iterator it;
for(it = getSources().begin(); it != getSources().end(); it++) {
m_pTempBuffer->clear();
(*it)->fillAudioBuffer(m_pTempBuffer);
addBuffers(m_pMixBuffer, m_pTempBuffer);
}
calcVolume(m_pMixBuffer, numFrames*getChannels(), getVolume());
for (int i=0; i<numFrames; ++i) {
m_pLimiter->process(m_pMixBuffer+i*getChannels());
for (int j=0; j<getChannels(); ++j) {
((short*)pDestBuffer)[i*2+j]=short(m_pMixBuffer[i*2+j]*32768);
}
}
}
void SDLAudioEngine::audioCallback(void *userData, Uint8 *audioBuffer, int audioBufferLen)
{
SDLAudioEngine *pThis = (SDLAudioEngine*)userData;
pThis->mixAudio(audioBuffer, audioBufferLen);
}
void SDLAudioEngine::addBuffers(double *pDest, AudioBufferPtr pSrc)
{
int numFrames = pSrc->getNumFrames();
short * pData = pSrc->getData();
for(int i = 0; i < numFrames*getChannels(); ++i) {
pDest[i] += pData[i]/32768.0;
}
}
void SDLAudioEngine::calcVolume(double *pBuffer, int numSamples, double volume)
{
// TODO: We need a VolumeFader class that keeps state.
for(int i = 0; i < numSamples; ++i) {
pBuffer[i] *= volume;
}
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <functional>
#include <stdexcept>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <boost/optional.hpp>
#include "../util/html_parser.hpp"
#include "../util/html_watcher.hpp"
#include "../util/html_recorder.hpp"
#include "../util/util.hpp"
namespace supermarx
{
class category_parser : public html_parser::default_handler
{
public:
typedef std::string category_uri_t;
typedef std::function<void(category_uri_t)> category_callback_t;
private:
enum state_e {
S_INIT,
S_CATEGORIES,
S_DONE
};
category_callback_t category_callback;
html_watcher_collection wc;
state_e state;
public:
category_parser(category_callback_t category_callback_)
: category_callback(category_callback_)
, wc()
, state(S_INIT)
{}
template<typename T>
void parse(T source)
{
html_parser::parse(source, *this);
}
virtual void startElement(const std::string& /* namespaceURI */, const std::string& /* localName */, const std::string& qName, const AttributesT& atts)
{
wc.startElement();
switch(state)
{
case S_INIT:
if(atts.getValue("data-appie") == "categoryscroll")
{
state = S_CATEGORIES;
wc.add([&]() {
state = S_DONE;
});
}
break;
case S_CATEGORIES:
if(qName == "a")
category_callback(atts.getValue("href"));
break;
case S_DONE:
break;
}
}
virtual void endElement(const std::string& /* namespaceURI */, const std::string& /* localName */, const std::string& /* qName */)
{
wc.endElement();
}
};
}
<commit_msg>category_parser: updated after changes in website<commit_after>#pragma once
#include <functional>
#include <stdexcept>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <boost/optional.hpp>
#include "../util/html_parser.hpp"
#include "../util/html_watcher.hpp"
#include "../util/html_recorder.hpp"
#include "../util/util.hpp"
namespace supermarx
{
class category_parser : public html_parser::default_handler
{
public:
typedef std::string category_uri_t;
typedef std::function<void(category_uri_t)> category_callback_t;
private:
enum state_e {
S_INIT,
S_CATEGORIES,
S_DONE
};
category_callback_t category_callback;
html_watcher_collection wc;
state_e state;
public:
category_parser(category_callback_t category_callback_)
: category_callback(category_callback_)
, wc()
, state(S_INIT)
{}
template<typename T>
void parse(T source)
{
html_parser::parse(source, *this);
}
virtual void startElement(const std::string& /* namespaceURI */, const std::string& /* localName */, const std::string& qName, const AttributesT& atts)
{
wc.startElement();
switch(state)
{
case S_INIT:
if(atts.getValue("data-class") == "category-navigation-items")
{
state = S_CATEGORIES;
wc.add([&]() {
state = S_DONE;
});
}
break;
case S_CATEGORIES:
if(qName == "a")
category_callback(atts.getValue("href"));
break;
case S_DONE:
break;
}
}
virtual void endElement(const std::string& /* namespaceURI */, const std::string& /* localName */, const std::string& /* qName */)
{
wc.endElement();
}
};
}
<|endoftext|> |
<commit_before>/******************************************************************************
*
* Copyright (C) 1990-2018, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#if defined( LINUX )
#include <sys/inotify.h>
#include <poll.h>
#endif /* defined( LINUX ) */
#include "utc_time.h"
#include "file_modified_trigger.h"
FileModifiedTrigger::FileModifiedTrigger( const std::string & f ) :
filename( f ), initialized( false ),
statfd( -1 ), lastSize( 0 )
{
statfd = open( filename.c_str(), O_RDONLY );
if( statfd == -1 ) {
dprintf( D_ALWAYS, "FileModifiedTrigger( %s ): open() failed: %s (%d).\n", filename.c_str(), strerror(errno), errno );
return;
}
#if defined( LINUX )
inotify_fd = inotify_init1( IN_NONBLOCK );
if( inotify_fd == -1 ) {
dprintf( D_ALWAYS, "FileModifiedTrigger( %s ): inotify_init() failed: %s (%d).\n", filename.c_str(), strerror(errno), errno );
return;
}
int wd = inotify_add_watch( inotify_fd, filename.c_str(), IN_MODIFY );
if( wd == -1 ) {
dprintf( D_ALWAYS, "FileModifiedTrigger( %s ): inotify_add_watch() failed: %s (%d).\n", filename.c_str(), strerror( errno ), errno );
return;
}
#endif /* defined( LINUX ) */
initialized = true;
}
FileModifiedTrigger::~FileModifiedTrigger() {
releaseResources();
}
void
FileModifiedTrigger::releaseResources() {
if( initialized && statfd != -1 ) {
close( statfd );
statfd = -1;
}
#if defined( LINUX )
if( initialized && inotify_fd != -1 ) {
close( inotify_fd );
inotify_fd = -1;
}
#endif /* defined( LINUX ) */
initialized = false;
}
//
// We would like to support the Linux and Windows -specific nonpolling
// solutions for detecting changes to the log file, but inotify blocks
// forever on network filesystems, and there's no Linux API which will
// let us know that ahead of time. Instead, we use a polling approach
// on all platforms, but instead of sleeping on some platforms, we use
// inotify with the sleep duration as its timeout.
//
// On Linux, this means that notify_or_sleep() "sleeps" in poll(), and
// if the inotify fd goes hot, uses read_inotify_events() to clear the
// fd for the next time.
//
#if defined( LINUX )
int
FileModifiedTrigger::read_inotify_events( void ) {
// Magic from 'man inotify'.
char buf[ sizeof(struct inotify_event) + NAME_MAX + 1 ]
__attribute__ ((aligned(__alignof__(struct inotify_event))));
while( true ) {
ssize_t len = read( inotify_fd, buf, sizeof( buf ) );
if( len == -1 && errno != EAGAIN ) {
dprintf( D_ALWAYS, "FileModifiedTrigger::read_inotify_events(%s): failed to ready from inotify fd.\n", filename.c_str() );
return -1;
}
// We're done reading events for now.
if( len <= 0 ) { return 1; }
char * ptr = buf;
for( ; ptr < buf + len; ptr += sizeof(struct inotify_event) + ((struct inotify_event *)ptr)->len ) {
const struct inotify_event * event = (struct inotify_event *)ptr;
if(! (event->mask & IN_MODIFY) ) {
dprintf( D_ALWAYS, "FileModifiedTrigger::read_inotify_events(%s): inotify gave me an event I didn't ask for.\n", filename.c_str() );
return -1;
}
}
// We don't worry about partial reads because we're only watching
// one file for one event type, and the kernel will coalesce
// identical events, so we should only ever see one. Nonetheless,
// we'll verify here that we read only complete events.
if( ptr != buf + len ) {
dprintf( D_ALWAYS, "FileModifiedTrigger::read_inotify_events(%s): partial inotify read.\n", filename.c_str() );
return -1;
}
}
return 1;
}
int
FileModifiedTrigger::notify_or_sleep( int timeout_in_ms ) {
struct pollfd pollfds[1];
pollfds[0].fd = inotify_fd;
pollfds[0].events = POLLIN;
pollfds[0].revents = 0;
int events = poll( pollfds, 1, timeout_in_ms );
switch( events ) {
case -1:
return -1;
case 0:
return 0;
default:
if( pollfds[0].revents & POLLIN ) {
return read_inotify_events();
} else {
dprintf( D_ALWAYS, "FileModifiedTrigger::wait(): inotify returned an event I didn't ask for.\n" );
return -1;
}
}
}
#else
#if defined(WINDOWS)
int usleep( long long microseconds ) {
HANDLE timer;
LARGE_INTEGER timerIntervals = { microseconds * -10 };
timer = CreateWaitableTimer( NULL, true, NULL );
SetWaitableTimer( timer, & timerIntervals, 0, NULL, NULL, false );
WaitForSingleObject( timer, INFINITE );
CloseHandle( timer );
return 0;
}
#endif /* defined(WINDOWS) */
int
FileModifiedTrigger::notify_or_sleep( int timeout_in_ms ) {
return usleep( timeout_in_ms * 1000 );
}
#endif /* defined( LINUX ) */
int
FileModifiedTrigger::wait( int timeout_in_ms ) {
if(! initialized) {
return -1;
}
struct timeval deadline;
condor_gettimestamp( deadline );
deadline.tv_sec += timeout_in_ms / 1000;
deadline.tv_usec += (timeout_in_ms % 1000) * 1000;
deadline.tv_usec = deadline.tv_usec % 1000000;
while( true ) {
struct stat statbuf;
int rv = fstat( statfd, & statbuf );
if( rv != 0 ) {
dprintf( D_ALWAYS, "FileModifiedTrigger::wait(): fstat() failure on previously-valid fd: %s (%d).\n", strerror(errno), errno );
return -1;
}
bool changed = statbuf.st_size != lastSize;
lastSize = statbuf.st_size;
if( changed ) { return 1; }
struct timeval now;
condor_gettimestamp( now );
if( deadline.tv_sec < now.tv_sec ) { return 0; }
else if( deadline.tv_sec == now.tv_sec &&
deadline.tv_usec < now.tv_usec ) { return 0; }
int waitfor = ((deadline.tv_sec - now.tv_sec) * 1000) +
((deadline.tv_usec - now.tv_usec) / 1000);
if( waitfor > 5000 ) { waitfor = 5000; }
int events = notify_or_sleep( waitfor );
if( events == 1 ) { return 1; }
if( events == 0 ) { continue; }
return -1;
}
}
<commit_msg>initialize uninitted variable #6992<commit_after>/******************************************************************************
*
* Copyright (C) 1990-2018, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#if defined( LINUX )
#include <sys/inotify.h>
#include <poll.h>
#endif /* defined( LINUX ) */
#include "utc_time.h"
#include "file_modified_trigger.h"
FileModifiedTrigger::FileModifiedTrigger( const std::string & f ) :
filename( f ), initialized( false ),
#ifdef LINUX
inotify_fd(-1),
#endif
statfd( -1 ), lastSize( 0 )
{
statfd = open( filename.c_str(), O_RDONLY );
if( statfd == -1 ) {
dprintf( D_ALWAYS, "FileModifiedTrigger( %s ): open() failed: %s (%d).\n", filename.c_str(), strerror(errno), errno );
return;
}
#if defined( LINUX )
inotify_fd = inotify_init1( IN_NONBLOCK );
if( inotify_fd == -1 ) {
dprintf( D_ALWAYS, "FileModifiedTrigger( %s ): inotify_init() failed: %s (%d).\n", filename.c_str(), strerror(errno), errno );
return;
}
int wd = inotify_add_watch( inotify_fd, filename.c_str(), IN_MODIFY );
if( wd == -1 ) {
dprintf( D_ALWAYS, "FileModifiedTrigger( %s ): inotify_add_watch() failed: %s (%d).\n", filename.c_str(), strerror( errno ), errno );
return;
}
#endif /* defined( LINUX ) */
initialized = true;
}
FileModifiedTrigger::~FileModifiedTrigger() {
releaseResources();
}
void
FileModifiedTrigger::releaseResources() {
if( initialized && statfd != -1 ) {
close( statfd );
statfd = -1;
}
#if defined( LINUX )
if( initialized && inotify_fd != -1 ) {
close( inotify_fd );
inotify_fd = -1;
}
#endif /* defined( LINUX ) */
initialized = false;
}
//
// We would like to support the Linux and Windows -specific nonpolling
// solutions for detecting changes to the log file, but inotify blocks
// forever on network filesystems, and there's no Linux API which will
// let us know that ahead of time. Instead, we use a polling approach
// on all platforms, but instead of sleeping on some platforms, we use
// inotify with the sleep duration as its timeout.
//
// On Linux, this means that notify_or_sleep() "sleeps" in poll(), and
// if the inotify fd goes hot, uses read_inotify_events() to clear the
// fd for the next time.
//
#if defined( LINUX )
int
FileModifiedTrigger::read_inotify_events( void ) {
// Magic from 'man inotify'.
char buf[ sizeof(struct inotify_event) + NAME_MAX + 1 ]
__attribute__ ((aligned(__alignof__(struct inotify_event))));
while( true ) {
ssize_t len = read( inotify_fd, buf, sizeof( buf ) );
if( len == -1 && errno != EAGAIN ) {
dprintf( D_ALWAYS, "FileModifiedTrigger::read_inotify_events(%s): failed to ready from inotify fd.\n", filename.c_str() );
return -1;
}
// We're done reading events for now.
if( len <= 0 ) { return 1; }
char * ptr = buf;
for( ; ptr < buf + len; ptr += sizeof(struct inotify_event) + ((struct inotify_event *)ptr)->len ) {
const struct inotify_event * event = (struct inotify_event *)ptr;
if(! (event->mask & IN_MODIFY) ) {
dprintf( D_ALWAYS, "FileModifiedTrigger::read_inotify_events(%s): inotify gave me an event I didn't ask for.\n", filename.c_str() );
return -1;
}
}
// We don't worry about partial reads because we're only watching
// one file for one event type, and the kernel will coalesce
// identical events, so we should only ever see one. Nonetheless,
// we'll verify here that we read only complete events.
if( ptr != buf + len ) {
dprintf( D_ALWAYS, "FileModifiedTrigger::read_inotify_events(%s): partial inotify read.\n", filename.c_str() );
return -1;
}
}
return 1;
}
int
FileModifiedTrigger::notify_or_sleep( int timeout_in_ms ) {
struct pollfd pollfds[1];
pollfds[0].fd = inotify_fd;
pollfds[0].events = POLLIN;
pollfds[0].revents = 0;
int events = poll( pollfds, 1, timeout_in_ms );
switch( events ) {
case -1:
return -1;
case 0:
return 0;
default:
if( pollfds[0].revents & POLLIN ) {
return read_inotify_events();
} else {
dprintf( D_ALWAYS, "FileModifiedTrigger::wait(): inotify returned an event I didn't ask for.\n" );
return -1;
}
}
}
#else
#if defined(WINDOWS)
int usleep( long long microseconds ) {
HANDLE timer;
LARGE_INTEGER timerIntervals = { microseconds * -10 };
timer = CreateWaitableTimer( NULL, true, NULL );
SetWaitableTimer( timer, & timerIntervals, 0, NULL, NULL, false );
WaitForSingleObject( timer, INFINITE );
CloseHandle( timer );
return 0;
}
#endif /* defined(WINDOWS) */
int
FileModifiedTrigger::notify_or_sleep( int timeout_in_ms ) {
return usleep( timeout_in_ms * 1000 );
}
#endif /* defined( LINUX ) */
int
FileModifiedTrigger::wait( int timeout_in_ms ) {
if(! initialized) {
return -1;
}
struct timeval deadline;
condor_gettimestamp( deadline );
deadline.tv_sec += timeout_in_ms / 1000;
deadline.tv_usec += (timeout_in_ms % 1000) * 1000;
deadline.tv_usec = deadline.tv_usec % 1000000;
while( true ) {
struct stat statbuf;
int rv = fstat( statfd, & statbuf );
if( rv != 0 ) {
dprintf( D_ALWAYS, "FileModifiedTrigger::wait(): fstat() failure on previously-valid fd: %s (%d).\n", strerror(errno), errno );
return -1;
}
bool changed = statbuf.st_size != lastSize;
lastSize = statbuf.st_size;
if( changed ) { return 1; }
struct timeval now;
condor_gettimestamp( now );
if( deadline.tv_sec < now.tv_sec ) { return 0; }
else if( deadline.tv_sec == now.tv_sec &&
deadline.tv_usec < now.tv_usec ) { return 0; }
int waitfor = ((deadline.tv_sec - now.tv_sec) * 1000) +
((deadline.tv_usec - now.tv_usec) / 1000);
if( waitfor > 5000 ) { waitfor = 5000; }
int events = notify_or_sleep( waitfor );
if( events == 1 ) { return 1; }
if( events == 0 ) { continue; }
return -1;
}
}
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS changefileheader (1.3.246); FILE MERGED 2008/04/01 15:05:23 thb 1.3.246.3: #i85898# Stripping all external header guards 2008/04/01 12:26:26 thb 1.3.246.2: #i85898# Stripping all external header guards 2008/03/31 12:19:29 rt 1.3.246.1: #i87441# Change license header to LPGL v3.<commit_after><|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 "config.h"
#include "common/errno.h"
#include "include/types.h"
#include "armor.h"
#include "include/Spinlock.h"
#include <errno.h>
#include <fstream>
#include <sstream>
#include <sys/uio.h>
#include <limits.h>
namespace ceph {
Spinlock buffer_lock("buffer_lock");
atomic_t buffer_total_alloc;
void buffer::list::encode_base64(buffer::list& o)
{
bufferptr bp(length() * 4 / 3 + 3);
int l = ceph_armor(bp.c_str(), bp.c_str() + bp.length(), c_str(), c_str() + length());
bp.set_length(l);
o.push_back(bp);
}
void buffer::list::decode_base64(buffer::list& e)
{
bufferptr bp(4 + ((e.length() * 3) / 4));
int l = ceph_unarmor(bp.c_str(), bp.c_str() + bp.length(), e.c_str(), e.c_str() + e.length());
if (l < 0) {
std::ostringstream oss;
oss << "decode_base64: decoding failed:\n";
hexdump(oss);
throw buffer::malformed_input(oss.str().c_str());
}
assert(l <= (int)bp.length());
bp.set_length(l);
push_back(bp);
}
void buffer::list::rebuild_page_aligned()
{
std::list<ptr>::iterator p = _buffers.begin();
while (p != _buffers.end()) {
// keep anything that's already page sized+aligned
if (p->is_page_aligned() && p->is_n_page_sized()) {
/*generic_dout(0) << " segment " << (void*)p->c_str()
<< " offset " << ((unsigned long)p->c_str() & ~PAGE_MASK)
<< " length " << p->length()
<< " " << (p->length() & ~PAGE_MASK) << " ok" << dendl;
*/
p++;
continue;
}
// consolidate unaligned items, until we get something that is sized+aligned
list unaligned;
unsigned offset = 0;
do {
/*generic_dout(0) << " segment " << (void*)p->c_str()
<< " offset " << ((unsigned long)p->c_str() & ~PAGE_MASK)
<< " length " << p->length() << " " << (p->length() & ~PAGE_MASK)
<< " overall offset " << offset << " " << (offset & ~PAGE_MASK)
<< " not ok" << dendl;
*/
offset += p->length();
unaligned.push_back(*p);
_buffers.erase(p++);
} while (p != _buffers.end() &&
(!p->is_page_aligned() ||
!p->is_n_page_sized() ||
(offset & ~PAGE_MASK)));
unaligned.rebuild();
_buffers.insert(p, unaligned._buffers.front());
}
}
int buffer::list::read_file(const char *fn, bool silent)
{
struct stat st;
int fd = TEMP_FAILURE_RETRY(::open(fn, O_RDONLY));
if (fd < 0) {
int err = errno;
if (!silent) {
derr << "can't open " << fn << ": " << cpp_strerror(err) << dendl;
}
return -err;
}
::fstat(fd, &st);
int s = ROUND_UP_TO(st.st_size, PAGE_SIZE);
bufferptr bp = buffer::create_page_aligned(s);
int left = st.st_size;
int got = 0;
while (left > 0) {
int r = ::read(fd, (void *)(bp.c_str() + got), left);
if (r == 0) {
// Premature EOF.
// Perhaps the file changed between stat() and read()?
if (!silent) {
derr << "bufferlist::read_file(" << fn << "): warning: got premature "
<< "EOF:" << dendl;
}
break;
}
else if (r < 0) {
int err = errno;
if (err == EINTR) {
// ignore EINTR, 'tis a silly error
continue;
}
if (!silent) {
derr << "bufferlist::read_file(" << fn << "): read error:"
<< cpp_strerror(err) << dendl;
}
TEMP_FAILURE_RETRY(::close(fd));
return -err;
}
got += r;
left -= r;
}
TEMP_FAILURE_RETRY(::close(fd));
bp.set_length(got);
append(bp);
return 0;
}
int buffer::list::write_file(const char *fn, int mode)
{
int fd = TEMP_FAILURE_RETRY(::open(fn, O_WRONLY|O_CREAT|O_TRUNC, mode));
if (fd < 0) {
int err = errno;
cerr << "bufferlist::write_file(" << fn << "): failed to open file: "
<< cpp_strerror(err) << std::endl;
return -err;
}
int ret = write_fd(fd);
if (ret) {
cerr << "bufferlist::write_fd(" << fn << "): write_fd error: "
<< cpp_strerror(ret) << std::endl;
TEMP_FAILURE_RETRY(::close(fd));
return ret;
}
if (TEMP_FAILURE_RETRY(::close(fd))) {
int err = errno;
cerr << "bufferlist::write_file(" << fn << "): close error: "
<< cpp_strerror(err) << std::endl;
return -err;
}
return 0;
}
int buffer::list::write_fd(int fd) const
{
// write buffer piecewise
if (false) {
for (std::list<ptr>::const_iterator it = _buffers.begin();
it != _buffers.end();
++it) {
int left = it->length();
if (!left)
continue;
const char *c = it->c_str();
while (left > 0) {
int r = ::write(fd, c, left);
if (r < 0) {
int err = errno;
if (err == EINTR)
continue;
return -err;
}
c += r;
left -= r;
}
}
return 0;
}
// use writev!
iovec iov[IOV_MAX];
int iovlen = 0;
ssize_t bytes = 0;
std::list<ptr>::const_iterator p = _buffers.begin();
while (p != _buffers.end()) {
if (p->length() > 0) {
iov[iovlen].iov_base = (void *)p->c_str();
iov[iovlen].iov_len = p->length();
bytes += p->length();
iovlen++;
}
p++;
if (iovlen == IOV_MAX-1 ||
p == _buffers.end()) {
iovec *start = iov;
int num = iovlen;
ssize_t wrote;
retry:
wrote = ::writev(fd, start, num);
if (wrote < 0) {
int err = errno;
if (err == EINTR)
goto retry;
return -err;
}
if (wrote < bytes) {
// partial write, recover!
while ((size_t)wrote >= start[0].iov_len) {
wrote -= start[0].iov_len;
bytes -= start[0].iov_len;
start++;
num--;
}
if (wrote > 0) {
start[0].iov_len -= wrote;
start[0].iov_base = (char *)start[0].iov_base + wrote;
bytes -= wrote;
}
goto retry;
}
iovlen = 0;
bytes = 0;
}
}
return 0;
}
void buffer::list::hexdump(std::ostream &out) const
{
out.setf(std::ios::right);
out.fill('0');
unsigned per = 16;
for (unsigned o=0; o<length(); o += per) {
out << std::hex << std::setw(4) << o << " :";
unsigned i;
for (i=0; i<per && o+i<length(); i++) {
out << " " << std::setw(2) << ((unsigned)(*this)[o+i] & 0xff);
}
for (; i<per; i++)
out << " ";
out << " : ";
for (i=0; i<per && o+i<length(); i++) {
char c = (*this)[o+i];
if (isupper(c) || islower(c) || isdigit(c) || c == ' ' || ispunct(c))
out << c;
else
out << '.';
}
out << std::dec << std::endl;
}
out.unsetf(std::ios::right);
}
}
<commit_msg>common/buffer.cc: kill deadcode<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 "config.h"
#include "common/errno.h"
#include "include/types.h"
#include "armor.h"
#include "include/Spinlock.h"
#include <errno.h>
#include <fstream>
#include <sstream>
#include <sys/uio.h>
#include <limits.h>
namespace ceph {
Spinlock buffer_lock("buffer_lock");
atomic_t buffer_total_alloc;
void buffer::list::encode_base64(buffer::list& o)
{
bufferptr bp(length() * 4 / 3 + 3);
int l = ceph_armor(bp.c_str(), bp.c_str() + bp.length(), c_str(), c_str() + length());
bp.set_length(l);
o.push_back(bp);
}
void buffer::list::decode_base64(buffer::list& e)
{
bufferptr bp(4 + ((e.length() * 3) / 4));
int l = ceph_unarmor(bp.c_str(), bp.c_str() + bp.length(), e.c_str(), e.c_str() + e.length());
if (l < 0) {
std::ostringstream oss;
oss << "decode_base64: decoding failed:\n";
hexdump(oss);
throw buffer::malformed_input(oss.str().c_str());
}
assert(l <= (int)bp.length());
bp.set_length(l);
push_back(bp);
}
void buffer::list::rebuild_page_aligned()
{
std::list<ptr>::iterator p = _buffers.begin();
while (p != _buffers.end()) {
// keep anything that's already page sized+aligned
if (p->is_page_aligned() && p->is_n_page_sized()) {
/*generic_dout(0) << " segment " << (void*)p->c_str()
<< " offset " << ((unsigned long)p->c_str() & ~PAGE_MASK)
<< " length " << p->length()
<< " " << (p->length() & ~PAGE_MASK) << " ok" << dendl;
*/
p++;
continue;
}
// consolidate unaligned items, until we get something that is sized+aligned
list unaligned;
unsigned offset = 0;
do {
/*generic_dout(0) << " segment " << (void*)p->c_str()
<< " offset " << ((unsigned long)p->c_str() & ~PAGE_MASK)
<< " length " << p->length() << " " << (p->length() & ~PAGE_MASK)
<< " overall offset " << offset << " " << (offset & ~PAGE_MASK)
<< " not ok" << dendl;
*/
offset += p->length();
unaligned.push_back(*p);
_buffers.erase(p++);
} while (p != _buffers.end() &&
(!p->is_page_aligned() ||
!p->is_n_page_sized() ||
(offset & ~PAGE_MASK)));
unaligned.rebuild();
_buffers.insert(p, unaligned._buffers.front());
}
}
int buffer::list::read_file(const char *fn, bool silent)
{
struct stat st;
int fd = TEMP_FAILURE_RETRY(::open(fn, O_RDONLY));
if (fd < 0) {
int err = errno;
if (!silent) {
derr << "can't open " << fn << ": " << cpp_strerror(err) << dendl;
}
return -err;
}
::fstat(fd, &st);
int s = ROUND_UP_TO(st.st_size, PAGE_SIZE);
bufferptr bp = buffer::create_page_aligned(s);
int left = st.st_size;
int got = 0;
while (left > 0) {
int r = ::read(fd, (void *)(bp.c_str() + got), left);
if (r == 0) {
// Premature EOF.
// Perhaps the file changed between stat() and read()?
if (!silent) {
derr << "bufferlist::read_file(" << fn << "): warning: got premature "
<< "EOF:" << dendl;
}
break;
}
else if (r < 0) {
int err = errno;
if (err == EINTR) {
// ignore EINTR, 'tis a silly error
continue;
}
if (!silent) {
derr << "bufferlist::read_file(" << fn << "): read error:"
<< cpp_strerror(err) << dendl;
}
TEMP_FAILURE_RETRY(::close(fd));
return -err;
}
got += r;
left -= r;
}
TEMP_FAILURE_RETRY(::close(fd));
bp.set_length(got);
append(bp);
return 0;
}
int buffer::list::write_file(const char *fn, int mode)
{
int fd = TEMP_FAILURE_RETRY(::open(fn, O_WRONLY|O_CREAT|O_TRUNC, mode));
if (fd < 0) {
int err = errno;
cerr << "bufferlist::write_file(" << fn << "): failed to open file: "
<< cpp_strerror(err) << std::endl;
return -err;
}
int ret = write_fd(fd);
if (ret) {
cerr << "bufferlist::write_fd(" << fn << "): write_fd error: "
<< cpp_strerror(ret) << std::endl;
TEMP_FAILURE_RETRY(::close(fd));
return ret;
}
if (TEMP_FAILURE_RETRY(::close(fd))) {
int err = errno;
cerr << "bufferlist::write_file(" << fn << "): close error: "
<< cpp_strerror(err) << std::endl;
return -err;
}
return 0;
}
int buffer::list::write_fd(int fd) const
{
// use writev!
iovec iov[IOV_MAX];
int iovlen = 0;
ssize_t bytes = 0;
std::list<ptr>::const_iterator p = _buffers.begin();
while (p != _buffers.end()) {
if (p->length() > 0) {
iov[iovlen].iov_base = (void *)p->c_str();
iov[iovlen].iov_len = p->length();
bytes += p->length();
iovlen++;
}
p++;
if (iovlen == IOV_MAX-1 ||
p == _buffers.end()) {
iovec *start = iov;
int num = iovlen;
ssize_t wrote;
retry:
wrote = ::writev(fd, start, num);
if (wrote < 0) {
int err = errno;
if (err == EINTR)
goto retry;
return -err;
}
if (wrote < bytes) {
// partial write, recover!
while ((size_t)wrote >= start[0].iov_len) {
wrote -= start[0].iov_len;
bytes -= start[0].iov_len;
start++;
num--;
}
if (wrote > 0) {
start[0].iov_len -= wrote;
start[0].iov_base = (char *)start[0].iov_base + wrote;
bytes -= wrote;
}
goto retry;
}
iovlen = 0;
bytes = 0;
}
}
return 0;
}
void buffer::list::hexdump(std::ostream &out) const
{
out.setf(std::ios::right);
out.fill('0');
unsigned per = 16;
for (unsigned o=0; o<length(); o += per) {
out << std::hex << std::setw(4) << o << " :";
unsigned i;
for (i=0; i<per && o+i<length(); i++) {
out << " " << std::setw(2) << ((unsigned)(*this)[o+i] & 0xff);
}
for (; i<per; i++)
out << " ";
out << " : ";
for (i=0; i<per && o+i<length(); i++) {
char c = (*this)[o+i];
if (isupper(c) || islower(c) || isdigit(c) || c == ' ' || ispunct(c))
out << c;
else
out << '.';
}
out << std::dec << std::endl;
}
out.unsetf(std::ios::right);
}
}
<|endoftext|> |
<commit_before>#include <reactive/buffer.hpp>
#include <reactive/process.hpp>
#include <reactive/variant.hpp>
#include <reactive/coroutine.hpp>
#include <reactive/generate.hpp>
#include <reactive/consume.hpp>
#include <reactive/tuple.hpp>
#include <reactive/ptr_observable.hpp>
#include <reactive/transform.hpp>
#include <reactive/bridge.hpp>
#include <reactive/take.hpp>
#include <reactive/enumerate.hpp>
#include <reactive/cache.hpp>
#include <reactive/connector.hpp>
#include <reactive/receiver.hpp>
#include <reactive/deref_optional.hpp>
#include <boost/container/string.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/container/flat_map.hpp>
namespace rx
{
template <class Element>
struct empty : observable<Element>
{
virtual void async_get_one(observer<Element> &receiver) SILICIUM_OVERRIDE
{
return receiver.ended();
}
virtual void cancel() SILICIUM_OVERRIDE
{
throw std::logic_error("empty observable cannot be cancelled");
}
};
}
namespace Si
{
#if SILICIUM_RX_TUPLE_AVAILABLE
BOOST_AUTO_TEST_CASE(reactive_take)
{
auto zeros = rx::generate([]{ return 0; });
auto ones = rx::generate([]{ return 1; });
auto both = rx::make_tuple(zeros, ones);
std::vector<std::tuple<int, int>> const expected(4, std::make_tuple(0, 1));
std::vector<std::tuple<int, int>> const generated = rx::take(both, expected.size());
BOOST_CHECK(expected == generated);
}
#endif
#if SILICIUM_RX_TUPLE_AVAILABLE
BOOST_AUTO_TEST_CASE(reactive_transform)
{
auto twos = rx::generate([]{ return 2; });
auto ones = rx::generate([]{ return 1; });
auto both = rx::make_tuple(twos, ones);
auto added = rx::transform(both, [](std::tuple<int, int> const &element)
{
return std::get<0>(element) + std::get<1>(element);
});
std::vector<int> const expected(4, 3);
std::vector<int> const generated = rx::take(added, expected.size());
BOOST_CHECK(expected == generated);
}
#endif
#if SILICIUM_RX_TUPLE_AVAILABLE
BOOST_AUTO_TEST_CASE(reactive_bridge)
{
auto bridge = std::make_shared<rx::bridge<int>>();
rx::ptr_observable<int, std::shared_ptr<rx::observable<int>>> first(bridge);
auto ones = rx::generate([]{ return 1; });
auto both = rx::make_tuple(first, ones);
auto added = rx::transform(both, [](std::tuple<int, int> const &element)
{
return std::get<0>(element) + std::get<1>(element);
});
std::vector<int> generated;
auto consumer = rx::consume<int>([&generated](int element)
{
generated.emplace_back(element);
});
BOOST_CHECK(generated.empty());
added.async_get_one(consumer);
BOOST_CHECK(generated.empty());
bridge->got_element(2);
std::vector<int> const expected(1, 3);
BOOST_CHECK(expected == generated);
}
#endif
BOOST_AUTO_TEST_CASE(reactive_make_buffer)
{
auto bridge = std::make_shared<rx::bridge<int>>();
rx::ptr_observable<int, std::shared_ptr<rx::observable<int>>> first{bridge};
auto buf = rx::make_buffer(first, 2);
std::vector<int> generated;
auto consumer = rx::consume<int>([&generated](int element)
{
generated.emplace_back(element);
});
BOOST_CHECK(generated.empty());
for (size_t i = 0; i < 2; ++i)
{
BOOST_REQUIRE(bridge->is_waiting());
bridge->got_element(7);
}
BOOST_CHECK(!bridge->is_waiting());
BOOST_CHECK(generated.empty());
buf.async_get_one(consumer);
std::vector<int> expected(1, 7);
BOOST_CHECK(expected == generated);
buf.async_get_one(consumer);
expected.emplace_back(7);
BOOST_CHECK(expected == generated);
buf.async_get_one(consumer);
BOOST_CHECK(expected == generated);
}
BOOST_AUTO_TEST_CASE(reactive_coroutine_generate)
{
auto co = rx::make_coroutine<int>([](rx::yield_context<int> &yield) -> void
{
yield(1);
yield(2);
});
std::vector<int> generated;
auto collector = rx::consume<int>([&generated](int element)
{
generated.emplace_back(element);
});
for (;;)
{
auto old_size = generated.size();
co.async_get_one(collector);
if (generated.size() == old_size)
{
break;
}
BOOST_REQUIRE(generated.size() == old_size + 1);
}
std::vector<int> const expected{1, 2};
BOOST_CHECK(expected == generated);
}
BOOST_AUTO_TEST_CASE(reactive_coroutine_get_one)
{
rx::bridge<int> asyncs;
bool exited_cleanly = false;
auto co = rx::make_coroutine<int>([&asyncs, &exited_cleanly](rx::yield_context<int> &yield) -> void
{
auto a = yield.get_one(asyncs);
BOOST_REQUIRE(a);
yield(*a - 1);
exited_cleanly = true;
});
std::vector<int> generated;
auto collector = rx::consume<int>([&generated](int element)
{
generated.emplace_back(element);
});
co.async_get_one(collector);
BOOST_REQUIRE(generated.empty());
asyncs.got_element(4);
//TODO: reading past the end should not be the required way to avoid a force unwind of the coroutine
// because the unwinding is done by throwing an exception.
co.async_get_one(collector);
BOOST_CHECK(exited_cleanly);
std::vector<int> const expected{3};
BOOST_CHECK(expected == generated);
}
#if SILICIUM_RX_VARIANT_AVAILABLE
BOOST_AUTO_TEST_CASE(reactive_make_variant)
{
rx::bridge<int> first;
rx::bridge<boost::container::string> second;
auto variants = make_variant(rx::ref(first), rx::ref(second));
typedef Si::fast_variant<int, boost::container::string> variant;
std::vector<variant> produced;
auto consumer = rx::consume<variant>([&produced](variant element)
{
produced.emplace_back(std::move(element));
});
variants.async_get_one(consumer);
BOOST_CHECK(produced.empty());
first.got_element(4);
variants.async_get_one(consumer);
BOOST_CHECK_EQUAL(1,produced.size());
second.got_element("Hi");
std::vector<variant> const expected
{
4,
boost::container::string("Hi")
};
BOOST_CHECK(expected == produced);
BOOST_CHECK(!rx::get_immediate(variants));
}
#endif
template <class Element, class Action>
struct blocking_then_state : rx::observer<Element>
{
boost::asio::io_service &dispatcher;
boost::optional<boost::asio::io_service::work> blocker;
Action action;
rx::observable<Element> *from = nullptr;
explicit blocking_then_state(boost::asio::io_service &dispatcher, Action action)
: dispatcher(dispatcher)
, blocker(boost::in_place(boost::ref(dispatcher)))
, action(std::move(action))
{
}
~blocking_then_state()
{
if (!from)
{
return;
}
from->cancel();
}
virtual void got_element(Element value) SILICIUM_OVERRIDE
{
dispatcher.post(boost::bind<void>(action, boost::make_optional(std::move(value))));
blocker.reset();
}
virtual void ended() SILICIUM_OVERRIDE
{
dispatcher.post(boost::bind<void>(action, boost::optional<Element>()));
blocker.reset();
}
};
template <class Element, class Action>
auto blocking_then(boost::asio::io_service &io, rx::observable<Element> &from, Action &&action) -> std::shared_ptr<blocking_then_state<Element, typename std::decay<Action>::type>>
{
auto state = std::make_shared<blocking_then_state<Element, typename std::decay<Action>::type>>(io, std::forward<Action>(action));
from.async_get_one(*state);
state->from = &from;
return state;
}
BOOST_AUTO_TEST_CASE(reactive_process)
{
rx::empty<char> input;
rx::process proc = rx::launch_process("/usr/bin/which", {"which"}, input);
boost::asio::io_service io;
auto blocking = blocking_then(io, proc.exit_code, [](boost::optional<int> ec)
{
BOOST_CHECK_EQUAL(0, ec);
});
io.run();
}
}
namespace rx
{
template <class Element>
using signal_observer_map = boost::container::flat_map<observer<Element> *, bool>;
template <class Element>
struct connection : observable<Element>
{
typedef Element element_type;
connection()
{
}
explicit connection(signal_observer_map<Element> &connections)
: connections(&connections)
{
}
connection(connection &&other)
: connections(other.connections)
, receiver_(other.receiver_)
{
other.connections = nullptr;
other.receiver_ = nullptr;
}
connection &operator = (connection &&other)
{
boost::swap(connections, other.connections);
boost::swap(receiver_, other.receiver_);
return *this;
}
~connection()
{
if (!connections)
{
return;
}
connections->erase(receiver_);
}
virtual void async_get_one(observer<element_type> &receiver) SILICIUM_OVERRIDE
{
auto * const old_receiver = receiver_;
connections->insert(std::make_pair(&receiver, true)).first->second = true;
if (old_receiver && (old_receiver != &receiver))
{
auto i = connections->find(receiver_);
assert(i->second);
connections->erase(i);
}
receiver_ = &receiver;
}
virtual void cancel() SILICIUM_OVERRIDE
{
assert(receiver_);
size_t erased = connections->erase(exchange(receiver_, nullptr));
assert(erased == 1);
}
private:
signal_observer_map<Element> *connections = nullptr;
observer<Element> *receiver_ = nullptr;
BOOST_DELETED_FUNCTION(connection(connection const &))
BOOST_DELETED_FUNCTION(connection &operator = (connection const &))
};
template <class Element>
struct signal
{
typedef connection<Element> connection_type;
connection_type connect()
{
return connection_type(observers);
}
void emit_one(Element const &value)
{
for (auto &observer : observers)
{
if (observer.second)
{
observer.second = false;
observer.first->got_element(value);
}
}
}
private:
signal_observer_map<Element> observers;
};
}
namespace
{
BOOST_AUTO_TEST_CASE(reactive_signal)
{
rx::signal<int> s;
auto con1 = s.connect();
auto con2 = s.connect();
std::vector<int> generated;
auto consumer = rx::consume<int>([&generated](boost::optional<int> value)
{
BOOST_REQUIRE(value);
generated.emplace_back(*value);
});
con1.async_get_one(consumer);
s.emit_one(2);
con2 = std::move(con1);
con2.async_get_one(consumer);
s.emit_one(3);
s.emit_one(4);
std::vector<int> const expected{2, 3};
BOOST_CHECK(expected == generated);
}
}
<commit_msg>make signal noncopyable<commit_after>#include <reactive/buffer.hpp>
#include <reactive/process.hpp>
#include <reactive/variant.hpp>
#include <reactive/coroutine.hpp>
#include <reactive/generate.hpp>
#include <reactive/consume.hpp>
#include <reactive/tuple.hpp>
#include <reactive/ptr_observable.hpp>
#include <reactive/transform.hpp>
#include <reactive/bridge.hpp>
#include <reactive/take.hpp>
#include <reactive/enumerate.hpp>
#include <reactive/cache.hpp>
#include <reactive/connector.hpp>
#include <reactive/receiver.hpp>
#include <reactive/deref_optional.hpp>
#include <boost/container/string.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/container/flat_map.hpp>
namespace rx
{
template <class Element>
struct empty : observable<Element>
{
virtual void async_get_one(observer<Element> &receiver) SILICIUM_OVERRIDE
{
return receiver.ended();
}
virtual void cancel() SILICIUM_OVERRIDE
{
throw std::logic_error("empty observable cannot be cancelled");
}
};
}
namespace Si
{
#if SILICIUM_RX_TUPLE_AVAILABLE
BOOST_AUTO_TEST_CASE(reactive_take)
{
auto zeros = rx::generate([]{ return 0; });
auto ones = rx::generate([]{ return 1; });
auto both = rx::make_tuple(zeros, ones);
std::vector<std::tuple<int, int>> const expected(4, std::make_tuple(0, 1));
std::vector<std::tuple<int, int>> const generated = rx::take(both, expected.size());
BOOST_CHECK(expected == generated);
}
#endif
#if SILICIUM_RX_TUPLE_AVAILABLE
BOOST_AUTO_TEST_CASE(reactive_transform)
{
auto twos = rx::generate([]{ return 2; });
auto ones = rx::generate([]{ return 1; });
auto both = rx::make_tuple(twos, ones);
auto added = rx::transform(both, [](std::tuple<int, int> const &element)
{
return std::get<0>(element) + std::get<1>(element);
});
std::vector<int> const expected(4, 3);
std::vector<int> const generated = rx::take(added, expected.size());
BOOST_CHECK(expected == generated);
}
#endif
#if SILICIUM_RX_TUPLE_AVAILABLE
BOOST_AUTO_TEST_CASE(reactive_bridge)
{
auto bridge = std::make_shared<rx::bridge<int>>();
rx::ptr_observable<int, std::shared_ptr<rx::observable<int>>> first(bridge);
auto ones = rx::generate([]{ return 1; });
auto both = rx::make_tuple(first, ones);
auto added = rx::transform(both, [](std::tuple<int, int> const &element)
{
return std::get<0>(element) + std::get<1>(element);
});
std::vector<int> generated;
auto consumer = rx::consume<int>([&generated](int element)
{
generated.emplace_back(element);
});
BOOST_CHECK(generated.empty());
added.async_get_one(consumer);
BOOST_CHECK(generated.empty());
bridge->got_element(2);
std::vector<int> const expected(1, 3);
BOOST_CHECK(expected == generated);
}
#endif
BOOST_AUTO_TEST_CASE(reactive_make_buffer)
{
auto bridge = std::make_shared<rx::bridge<int>>();
rx::ptr_observable<int, std::shared_ptr<rx::observable<int>>> first{bridge};
auto buf = rx::make_buffer(first, 2);
std::vector<int> generated;
auto consumer = rx::consume<int>([&generated](int element)
{
generated.emplace_back(element);
});
BOOST_CHECK(generated.empty());
for (size_t i = 0; i < 2; ++i)
{
BOOST_REQUIRE(bridge->is_waiting());
bridge->got_element(7);
}
BOOST_CHECK(!bridge->is_waiting());
BOOST_CHECK(generated.empty());
buf.async_get_one(consumer);
std::vector<int> expected(1, 7);
BOOST_CHECK(expected == generated);
buf.async_get_one(consumer);
expected.emplace_back(7);
BOOST_CHECK(expected == generated);
buf.async_get_one(consumer);
BOOST_CHECK(expected == generated);
}
BOOST_AUTO_TEST_CASE(reactive_coroutine_generate)
{
auto co = rx::make_coroutine<int>([](rx::yield_context<int> &yield) -> void
{
yield(1);
yield(2);
});
std::vector<int> generated;
auto collector = rx::consume<int>([&generated](int element)
{
generated.emplace_back(element);
});
for (;;)
{
auto old_size = generated.size();
co.async_get_one(collector);
if (generated.size() == old_size)
{
break;
}
BOOST_REQUIRE(generated.size() == old_size + 1);
}
std::vector<int> const expected{1, 2};
BOOST_CHECK(expected == generated);
}
BOOST_AUTO_TEST_CASE(reactive_coroutine_get_one)
{
rx::bridge<int> asyncs;
bool exited_cleanly = false;
auto co = rx::make_coroutine<int>([&asyncs, &exited_cleanly](rx::yield_context<int> &yield) -> void
{
auto a = yield.get_one(asyncs);
BOOST_REQUIRE(a);
yield(*a - 1);
exited_cleanly = true;
});
std::vector<int> generated;
auto collector = rx::consume<int>([&generated](int element)
{
generated.emplace_back(element);
});
co.async_get_one(collector);
BOOST_REQUIRE(generated.empty());
asyncs.got_element(4);
//TODO: reading past the end should not be the required way to avoid a force unwind of the coroutine
// because the unwinding is done by throwing an exception.
co.async_get_one(collector);
BOOST_CHECK(exited_cleanly);
std::vector<int> const expected{3};
BOOST_CHECK(expected == generated);
}
#if SILICIUM_RX_VARIANT_AVAILABLE
BOOST_AUTO_TEST_CASE(reactive_make_variant)
{
rx::bridge<int> first;
rx::bridge<boost::container::string> second;
auto variants = make_variant(rx::ref(first), rx::ref(second));
typedef Si::fast_variant<int, boost::container::string> variant;
std::vector<variant> produced;
auto consumer = rx::consume<variant>([&produced](variant element)
{
produced.emplace_back(std::move(element));
});
variants.async_get_one(consumer);
BOOST_CHECK(produced.empty());
first.got_element(4);
variants.async_get_one(consumer);
BOOST_CHECK_EQUAL(1,produced.size());
second.got_element("Hi");
std::vector<variant> const expected
{
4,
boost::container::string("Hi")
};
BOOST_CHECK(expected == produced);
BOOST_CHECK(!rx::get_immediate(variants));
}
#endif
template <class Element, class Action>
struct blocking_then_state : rx::observer<Element>
{
boost::asio::io_service &dispatcher;
boost::optional<boost::asio::io_service::work> blocker;
Action action;
rx::observable<Element> *from = nullptr;
explicit blocking_then_state(boost::asio::io_service &dispatcher, Action action)
: dispatcher(dispatcher)
, blocker(boost::in_place(boost::ref(dispatcher)))
, action(std::move(action))
{
}
~blocking_then_state()
{
if (!from)
{
return;
}
from->cancel();
}
virtual void got_element(Element value) SILICIUM_OVERRIDE
{
dispatcher.post(boost::bind<void>(action, boost::make_optional(std::move(value))));
blocker.reset();
}
virtual void ended() SILICIUM_OVERRIDE
{
dispatcher.post(boost::bind<void>(action, boost::optional<Element>()));
blocker.reset();
}
};
template <class Element, class Action>
auto blocking_then(boost::asio::io_service &io, rx::observable<Element> &from, Action &&action) -> std::shared_ptr<blocking_then_state<Element, typename std::decay<Action>::type>>
{
auto state = std::make_shared<blocking_then_state<Element, typename std::decay<Action>::type>>(io, std::forward<Action>(action));
from.async_get_one(*state);
state->from = &from;
return state;
}
BOOST_AUTO_TEST_CASE(reactive_process)
{
rx::empty<char> input;
rx::process proc = rx::launch_process("/usr/bin/which", {"which"}, input);
boost::asio::io_service io;
auto blocking = blocking_then(io, proc.exit_code, [](boost::optional<int> ec)
{
BOOST_CHECK_EQUAL(0, ec);
});
io.run();
}
}
namespace rx
{
template <class Element>
using signal_observer_map = boost::container::flat_map<observer<Element> *, bool>;
template <class Element>
struct connection : observable<Element>
{
typedef Element element_type;
connection()
{
}
explicit connection(signal_observer_map<Element> &connections)
: connections(&connections)
{
}
connection(connection &&other)
: connections(other.connections)
, receiver_(other.receiver_)
{
other.connections = nullptr;
other.receiver_ = nullptr;
}
connection &operator = (connection &&other)
{
boost::swap(connections, other.connections);
boost::swap(receiver_, other.receiver_);
return *this;
}
~connection()
{
if (!connections)
{
return;
}
connections->erase(receiver_);
}
virtual void async_get_one(observer<element_type> &receiver) SILICIUM_OVERRIDE
{
auto * const old_receiver = receiver_;
connections->insert(std::make_pair(&receiver, true)).first->second = true;
if (old_receiver && (old_receiver != &receiver))
{
auto i = connections->find(receiver_);
assert(i->second);
connections->erase(i);
}
receiver_ = &receiver;
}
virtual void cancel() SILICIUM_OVERRIDE
{
assert(receiver_);
size_t erased = connections->erase(exchange(receiver_, nullptr));
assert(erased == 1);
}
private:
signal_observer_map<Element> *connections = nullptr;
observer<Element> *receiver_ = nullptr;
BOOST_DELETED_FUNCTION(connection(connection const &))
BOOST_DELETED_FUNCTION(connection &operator = (connection const &))
};
template <class Element>
struct signal : boost::noncopyable
{
typedef connection<Element> connection_type;
connection_type connect()
{
return connection_type(observers);
}
void emit_one(Element const &value)
{
for (auto &observer : observers)
{
if (observer.second)
{
observer.second = false;
observer.first->got_element(value);
}
}
}
private:
signal_observer_map<Element> observers;
};
}
namespace
{
BOOST_AUTO_TEST_CASE(reactive_signal)
{
rx::signal<int> s;
auto con1 = s.connect();
auto con2 = s.connect();
std::vector<int> generated;
auto consumer = rx::consume<int>([&generated](boost::optional<int> value)
{
BOOST_REQUIRE(value);
generated.emplace_back(*value);
});
con1.async_get_one(consumer);
s.emit_one(2);
con2 = std::move(con1);
con2.async_get_one(consumer);
s.emit_one(3);
s.emit_one(4);
std::vector<int> const expected{2, 3};
BOOST_CHECK(expected == generated);
}
}
<|endoftext|> |
<commit_before>/*
* SessionHistory.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionHistory.hpp"
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <boost/utility.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/DateTime.hpp>
#include <core/json/JsonRpc.hpp>
#include <r/session/RConsoleHistory.hpp>
#include <session/SessionModuleContext.hpp>
using namespace core;
namespace session {
namespace modules {
namespace history {
namespace {
struct HistoryEntry
{
HistoryEntry() : index(0), timestamp(0) {}
HistoryEntry(int index, double timestamp, const std::string& command)
: index(index), timestamp(timestamp), command(command)
{
}
int index;
double timestamp;
std::string command;
};
void historyEntriesAsJson(const std::vector<HistoryEntry>& entries,
json::Object* pEntriesJson)
{
// clear inbound
pEntriesJson->clear();
// populate arrays
json::Array indexArray, timestampArray, commandArray;
for (std::size_t i=0; i<entries.size(); i++)
{
indexArray.push_back(entries[i].index);
timestampArray.push_back(entries[i].timestamp);
commandArray.push_back(entries[i].command);
}
// set arrays into result object
pEntriesJson->operator[]("index") = indexArray;
pEntriesJson->operator[]("timestamp") = timestampArray;
pEntriesJson->operator[]("command") = commandArray;
}
// simple reader for parsing lines of history file
class HistoryEntryReader
{
public:
HistoryEntryReader() : nextIndex_(0) {}
ReadCollectionAction operator()(const std::string& line,
HistoryEntry* pEntry)
{
// if the line doesn't have a ':' then ignore it
if (line.find(':') == std::string::npos)
return ReadCollectionIgnoreLine;
pEntry->index = nextIndex_++;
std::istringstream istr(line);
istr >> pEntry->timestamp ;
istr.ignore(1, ':');
std::getline(istr, pEntry->command);
// if we had a read failure log it and return ignore state
if (!istr.fail())
{
return ReadCollectionAddLine;
}
else
{
LOG_ERROR_MESSAGE("unexpected io error reading history line: " +
line);
return ReadCollectionIgnoreLine;
}
}
private:
int nextIndex_;
};
class History : boost::noncopyable
{
private:
History() : entryCacheLastWriteTime_(-1) {}
friend History& historyArchive();
public:
Error add(const std::string& command)
{
// reset the cache (since this write will invalidate the current one,
// no sense in keeping our cache around in memory)
entries_.clear();
entryCacheLastWriteTime_ = -1;
// write the entry to the file
std::ostringstream ostrEntry ;
double currentTime = core::date_time::millisecondsSinceEpoch();
writeEntry(currentTime, command, &ostrEntry);
ostrEntry << std::endl;
return appendToFile(historyDatabaseFilePath(), ostrEntry.str());
}
const std::vector<HistoryEntry>& entries() const
{
// calculate path to history db
FilePath historyDBPath = historyDatabaseFilePath();
// if the file doesn't exist then clear the collection
if (!historyDBPath.exists())
{
entries_.clear();
}
// otherwise check for divergent lastWriteTime and read the file
// if our internal list isn't up to date
else if (historyDBPath.lastWriteTime() != entryCacheLastWriteTime_)
{
entries_.clear();
Error error = readCollectionFromFile<std::vector<HistoryEntry> >(
historyDBPath,
&entries_,
HistoryEntryReader());
if (error)
{
LOG_ERROR(error);
}
else
{
entryCacheLastWriteTime_ = historyDBPath.lastWriteTime();
}
}
// return entries
return entries_;
}
static void migrateRhistoryIfNecessary()
{
// if the history database doesn't exist see if we can migrate the
// old .Rhistory file
FilePath historyDBPath = historyDatabaseFilePath();
if (!historyDBPath.exists())
attemptRhistoryMigration() ;
}
private:
static void writeEntry(double timestamp,
const std::string& command,
std::ostream* pOS)
{
*pOS << std::fixed << std::setprecision(0)
<< timestamp << ":" << command;
}
static std::string migratedHistoryEntry(const std::string& command)
{
std::ostringstream ostr ;
writeEntry(0, command, &ostr);
return ostr.str();
}
static void attemptRhistoryMigration()
{
Error error = writeCollectionToFile<r::session::ConsoleHistory>(
historyDatabaseFilePath(),
r::session::consoleHistory(),
migratedHistoryEntry);
// log any error which occurs
if (error)
LOG_ERROR(error);
}
static FilePath historyDatabaseFilePath()
{
return module_context::userScratchPath().complete("history_database");
}
private:
mutable std::time_t entryCacheLastWriteTime_;
mutable std::vector<HistoryEntry> entries_;
};
History& historyArchive()
{
static History instance;
return instance;
}
Error setJsonResultFromHistory(int startIndex,
int endIndex,
json::JsonRpcResponse* pResponse)
{
// get all entries
const std::vector<HistoryEntry>& allEntries = historyArchive().entries();
// validate indexes
int historySize = allEntries.size();
if ( (startIndex < 0) ||
(startIndex > historySize) ||
(endIndex < 0) ||
(endIndex > historySize) )
{
return Error(json::errc::ParamInvalid, ERROR_LOCATION);
}
// return the entries
std::vector<HistoryEntry> entries;
std::copy(allEntries.begin() + startIndex,
allEntries.begin() + endIndex,
std::back_inserter(entries));
json::Object entriesJson;
historyEntriesAsJson(entries, &entriesJson);
pResponse->setResult(entriesJson);
return Success();
}
bool matches(const HistoryEntry& entry,
const std::vector<std::string>& searchTerms)
{
// look for each search term in the input
for (std::vector<std::string>::const_iterator it = searchTerms.begin();
it != searchTerms.end();
++it)
{
if (!boost::algorithm::contains(entry.command, *it))
return false;
}
// had all of the search terms, return true
return true;
}
void historyRangeAsJson(int startIndex,
int endIndex,
json::Object* pHistoryJson)
{
// get the subset of entries
std::vector<HistoryEntry> historyEntries;
std::vector<std::string> entries;
r::session::consoleHistory().subset(startIndex, endIndex, &entries);
for (std::vector<std::string>::const_iterator it = entries.begin();
it != entries.end();
++it)
{
historyEntries.push_back(HistoryEntry(startIndex++, 0, *it));
}
// convert to json
historyEntriesAsJson(historyEntries, pHistoryJson);
}
Error getRecentHistory(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get params
int maxItems;
Error error = json::readParam(request.params, 0, &maxItems);
if (error)
return error;
// alias console history
using namespace r::session;
ConsoleHistory& consoleHistory = r::session::consoleHistory();
// validate
if (maxItems <= 0)
return Error(json::errc::ParamInvalid, ERROR_LOCATION);
// compute start and end indexes
int startIndex = std::max(0, consoleHistory.size() - maxItems);
int endIndex = consoleHistory.size();
// get json and set it
json::Object historyJson;
historyRangeAsJson(startIndex, endIndex, &historyJson);
pResponse->setResult(historyJson);
return Success();
}
Error getHistoryItems(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get start and end index
int startIndex; // inclusive
int endIndex; // exclusive
Error error = json::readParams(request.params, &startIndex, &endIndex);
if (error)
return error;
// get the range and return it
json::Object historyJson;
historyRangeAsJson(startIndex, endIndex, &historyJson);
pResponse->setResult(historyJson);
return Success();
}
void enqueConsoleResetHistoryEvent(bool preserveUIContext)
{
json::Array historyJson;
r::session::consoleHistory().asJson(&historyJson);
json::Object resetJson;
resetJson["history"] = historyJson;
resetJson["preserve_ui_context"] = preserveUIContext;
ClientEvent event(client_events::kConsoleResetHistory, resetJson);
module_context::enqueClientEvent(event);
}
Error removeHistoryItems(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get indexes
json::Array bottomIndexesJson;
Error error = json::readParam(request.params, 0, &bottomIndexesJson);
if (error)
return error;
// convert to top indexes
int historySize = r::session::consoleHistory().size();
std::vector<int> indexes;
for (std::size_t i=0; i<bottomIndexesJson.size(); i++)
{
const json::Value& value = bottomIndexesJson[i];
if (json::isType<int>(value))
{
int bottomIndex = value.get_int();
int topIndex = historySize - 1 - bottomIndex;
indexes.push_back(topIndex);
}
}
// remove them
r::session::consoleHistory().remove(indexes);
// enque event
enqueConsoleResetHistoryEvent(true);
return Success();
}
Error clearHistory(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
r::session::consoleHistory().clear();
enqueConsoleResetHistoryEvent(false);
return Success();
}
Error getHistoryArchiveItems(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get start and end index
int startIndex; // inclusive
int endIndex; // exclusive
Error error = json::readParams(request.params, &startIndex, &endIndex);
if (error)
return error;
// truncate indexes if necessary
int historySize = historyArchive().entries().size();
startIndex = std::min(startIndex, historySize);
endIndex = std::min(endIndex, historySize);
// return json for the appropriate range
return setJsonResultFromHistory(startIndex, endIndex, pResponse);
}
Error searchHistoryArchive(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get the query
std::string query;
int maxEntries;
Error error = json::readParams(request.params, &query, &maxEntries);
if (error)
return error;
// convert the query into a list of search terms
std::vector<std::string> searchTerms;
boost::char_separator<char> sep;
boost::tokenizer<boost::char_separator<char> > tok(query, sep);
std::copy(tok.begin(), tok.end(), std::back_inserter(searchTerms));
// examine the items in the history for matches
const std::vector<HistoryEntry>& allEntries = historyArchive().entries();
std::vector<HistoryEntry> matchingEntries;
for (std::vector<HistoryEntry>::const_reverse_iterator
it = allEntries.rbegin();
it != allEntries.rend();
++it)
{
// check limit
if (matchingEntries.size() >= static_cast<std::size_t>(maxEntries))
break;
// look for match
if (matches(*it, searchTerms))
{
// add entry
matchingEntries.push_back(*it);
}
}
// return json
json::Object entriesJson;
historyEntriesAsJson(matchingEntries, &entriesJson);
pResponse->setResult(entriesJson);
return Success();
}
Error searchHistoryArchiveByPrefix(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get the query
std::string prefix;
int maxEntries;
bool uniqueOnly;
Error error = json::readParams(request.params,
&prefix, &maxEntries, &uniqueOnly);
if (error)
return error;
// trim the prefix
boost::algorithm::trim(prefix);
// examine the items in the history for matches
const std::vector<HistoryEntry>& allEntries = historyArchive().entries();
std::set<std::string> matchedCommands;
std::vector<HistoryEntry> matchingEntries;
for (std::vector<HistoryEntry>::const_reverse_iterator
it = allEntries.rbegin();
it != allEntries.rend();
++it)
{
// check limit
if (matchingEntries.size() >= static_cast<std::size_t>(maxEntries))
break;
// look for match
if (boost::algorithm::starts_with(it->command, prefix))
{
if (!uniqueOnly || (matchedCommands.count(it->command) == 0))
{
matchingEntries.push_back(*it);
matchedCommands.insert(it->command);
}
}
}
// return json
json::Object entriesJson;
historyEntriesAsJson(matchingEntries, &entriesJson);
pResponse->setResult(entriesJson);
return Success();
}
void onHistoryAdd(const std::string& command)
{
// add command to history archive
Error error = historyArchive().add(command);
if (error)
LOG_ERROR(error);
// fire event
int entryIndex = r::session::consoleHistory().size() - 1;
std::vector<HistoryEntry> entries;
entries.push_back(HistoryEntry(entryIndex, 0, command));
json::Object entriesJson;
historyEntriesAsJson(entries, &entriesJson);
ClientEvent event(client_events::kHistoryEntriesAdded, entriesJson);
module_context::enqueClientEvent(event);
}
} // anonymous namespace
Error initialize()
{
// migrate .Rhistory if necessary
History::migrateRhistoryIfNecessary();
// connect to console history add event
r::session::consoleHistory().connectOnAdd(onHistoryAdd);
// install handlers
using boost::bind;
using namespace session::module_context;
ExecBlock initBlock ;
initBlock.addFunctions()
(bind(registerRpcMethod, "get_recent_history", getRecentHistory))
(bind(registerRpcMethod, "get_history_items", getHistoryItems))
(bind(registerRpcMethod, "remove_history_items", removeHistoryItems))
(bind(registerRpcMethod, "clear_history", clearHistory))
(bind(registerRpcMethod, "get_history_archive_items", getHistoryArchiveItems))
(bind(registerRpcMethod, "search_history_archive", searchHistoryArchive))
(bind(registerRpcMethod, "search_history_archive_by_prefix", searchHistoryArchiveByPrefix));
return initBlock.execute();
}
} // namespace history
} // namespace modules
} // namesapce session
<commit_msg>add rs_timestamp function<commit_after>/*
* SessionHistory.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionHistory.hpp"
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <boost/utility.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/format.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/DateTime.hpp>
#include <core/json/JsonRpc.hpp>
#include <r/RSexp.hpp>
#include <r/RRoutines.hpp>
#include <r/session/RConsoleHistory.hpp>
#include <session/SessionModuleContext.hpp>
using namespace core;
namespace session {
namespace modules {
namespace history {
namespace {
struct HistoryEntry
{
HistoryEntry() : index(0), timestamp(0) {}
HistoryEntry(int index, double timestamp, const std::string& command)
: index(index), timestamp(timestamp), command(command)
{
}
int index;
double timestamp;
std::string command;
};
void historyEntriesAsJson(const std::vector<HistoryEntry>& entries,
json::Object* pEntriesJson)
{
// clear inbound
pEntriesJson->clear();
// populate arrays
json::Array indexArray, timestampArray, commandArray;
for (std::size_t i=0; i<entries.size(); i++)
{
indexArray.push_back(entries[i].index);
timestampArray.push_back(entries[i].timestamp);
commandArray.push_back(entries[i].command);
}
// set arrays into result object
pEntriesJson->operator[]("index") = indexArray;
pEntriesJson->operator[]("timestamp") = timestampArray;
pEntriesJson->operator[]("command") = commandArray;
}
// simple reader for parsing lines of history file
class HistoryEntryReader
{
public:
HistoryEntryReader() : nextIndex_(0) {}
ReadCollectionAction operator()(const std::string& line,
HistoryEntry* pEntry)
{
// if the line doesn't have a ':' then ignore it
if (line.find(':') == std::string::npos)
return ReadCollectionIgnoreLine;
pEntry->index = nextIndex_++;
std::istringstream istr(line);
istr >> pEntry->timestamp ;
istr.ignore(1, ':');
std::getline(istr, pEntry->command);
// if we had a read failure log it and return ignore state
if (!istr.fail())
{
return ReadCollectionAddLine;
}
else
{
LOG_ERROR_MESSAGE("unexpected io error reading history line: " +
line);
return ReadCollectionIgnoreLine;
}
}
private:
int nextIndex_;
};
class History : boost::noncopyable
{
private:
History() : entryCacheLastWriteTime_(-1) {}
friend History& historyArchive();
public:
Error add(const std::string& command)
{
// reset the cache (since this write will invalidate the current one,
// no sense in keeping our cache around in memory)
entries_.clear();
entryCacheLastWriteTime_ = -1;
// write the entry to the file
std::ostringstream ostrEntry ;
double currentTime = core::date_time::millisecondsSinceEpoch();
writeEntry(currentTime, command, &ostrEntry);
ostrEntry << std::endl;
return appendToFile(historyDatabaseFilePath(), ostrEntry.str());
}
const std::vector<HistoryEntry>& entries() const
{
// calculate path to history db
FilePath historyDBPath = historyDatabaseFilePath();
// if the file doesn't exist then clear the collection
if (!historyDBPath.exists())
{
entries_.clear();
}
// otherwise check for divergent lastWriteTime and read the file
// if our internal list isn't up to date
else if (historyDBPath.lastWriteTime() != entryCacheLastWriteTime_)
{
entries_.clear();
Error error = readCollectionFromFile<std::vector<HistoryEntry> >(
historyDBPath,
&entries_,
HistoryEntryReader());
if (error)
{
LOG_ERROR(error);
}
else
{
entryCacheLastWriteTime_ = historyDBPath.lastWriteTime();
}
}
// return entries
return entries_;
}
static void migrateRhistoryIfNecessary()
{
// if the history database doesn't exist see if we can migrate the
// old .Rhistory file
FilePath historyDBPath = historyDatabaseFilePath();
if (!historyDBPath.exists())
attemptRhistoryMigration() ;
}
private:
static void writeEntry(double timestamp,
const std::string& command,
std::ostream* pOS)
{
*pOS << std::fixed << std::setprecision(0)
<< timestamp << ":" << command;
}
static std::string migratedHistoryEntry(const std::string& command)
{
std::ostringstream ostr ;
writeEntry(0, command, &ostr);
return ostr.str();
}
static void attemptRhistoryMigration()
{
Error error = writeCollectionToFile<r::session::ConsoleHistory>(
historyDatabaseFilePath(),
r::session::consoleHistory(),
migratedHistoryEntry);
// log any error which occurs
if (error)
LOG_ERROR(error);
}
static FilePath historyDatabaseFilePath()
{
return module_context::userScratchPath().complete("history_database");
}
private:
mutable std::time_t entryCacheLastWriteTime_;
mutable std::vector<HistoryEntry> entries_;
};
History& historyArchive()
{
static History instance;
return instance;
}
Error setJsonResultFromHistory(int startIndex,
int endIndex,
json::JsonRpcResponse* pResponse)
{
// get all entries
const std::vector<HistoryEntry>& allEntries = historyArchive().entries();
// validate indexes
int historySize = allEntries.size();
if ( (startIndex < 0) ||
(startIndex > historySize) ||
(endIndex < 0) ||
(endIndex > historySize) )
{
return Error(json::errc::ParamInvalid, ERROR_LOCATION);
}
// return the entries
std::vector<HistoryEntry> entries;
std::copy(allEntries.begin() + startIndex,
allEntries.begin() + endIndex,
std::back_inserter(entries));
json::Object entriesJson;
historyEntriesAsJson(entries, &entriesJson);
pResponse->setResult(entriesJson);
return Success();
}
bool matches(const HistoryEntry& entry,
const std::vector<std::string>& searchTerms)
{
// look for each search term in the input
for (std::vector<std::string>::const_iterator it = searchTerms.begin();
it != searchTerms.end();
++it)
{
if (!boost::algorithm::contains(entry.command, *it))
return false;
}
// had all of the search terms, return true
return true;
}
void historyRangeAsJson(int startIndex,
int endIndex,
json::Object* pHistoryJson)
{
// get the subset of entries
std::vector<HistoryEntry> historyEntries;
std::vector<std::string> entries;
r::session::consoleHistory().subset(startIndex, endIndex, &entries);
for (std::vector<std::string>::const_iterator it = entries.begin();
it != entries.end();
++it)
{
historyEntries.push_back(HistoryEntry(startIndex++, 0, *it));
}
// convert to json
historyEntriesAsJson(historyEntries, pHistoryJson);
}
Error getRecentHistory(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get params
int maxItems;
Error error = json::readParam(request.params, 0, &maxItems);
if (error)
return error;
// alias console history
using namespace r::session;
ConsoleHistory& consoleHistory = r::session::consoleHistory();
// validate
if (maxItems <= 0)
return Error(json::errc::ParamInvalid, ERROR_LOCATION);
// compute start and end indexes
int startIndex = std::max(0, consoleHistory.size() - maxItems);
int endIndex = consoleHistory.size();
// get json and set it
json::Object historyJson;
historyRangeAsJson(startIndex, endIndex, &historyJson);
pResponse->setResult(historyJson);
return Success();
}
Error getHistoryItems(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get start and end index
int startIndex; // inclusive
int endIndex; // exclusive
Error error = json::readParams(request.params, &startIndex, &endIndex);
if (error)
return error;
// get the range and return it
json::Object historyJson;
historyRangeAsJson(startIndex, endIndex, &historyJson);
pResponse->setResult(historyJson);
return Success();
}
void enqueConsoleResetHistoryEvent(bool preserveUIContext)
{
json::Array historyJson;
r::session::consoleHistory().asJson(&historyJson);
json::Object resetJson;
resetJson["history"] = historyJson;
resetJson["preserve_ui_context"] = preserveUIContext;
ClientEvent event(client_events::kConsoleResetHistory, resetJson);
module_context::enqueClientEvent(event);
}
Error removeHistoryItems(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get indexes
json::Array bottomIndexesJson;
Error error = json::readParam(request.params, 0, &bottomIndexesJson);
if (error)
return error;
// convert to top indexes
int historySize = r::session::consoleHistory().size();
std::vector<int> indexes;
for (std::size_t i=0; i<bottomIndexesJson.size(); i++)
{
const json::Value& value = bottomIndexesJson[i];
if (json::isType<int>(value))
{
int bottomIndex = value.get_int();
int topIndex = historySize - 1 - bottomIndex;
indexes.push_back(topIndex);
}
}
// remove them
r::session::consoleHistory().remove(indexes);
// enque event
enqueConsoleResetHistoryEvent(true);
return Success();
}
Error clearHistory(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
r::session::consoleHistory().clear();
enqueConsoleResetHistoryEvent(false);
return Success();
}
Error getHistoryArchiveItems(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get start and end index
int startIndex; // inclusive
int endIndex; // exclusive
Error error = json::readParams(request.params, &startIndex, &endIndex);
if (error)
return error;
// truncate indexes if necessary
int historySize = historyArchive().entries().size();
startIndex = std::min(startIndex, historySize);
endIndex = std::min(endIndex, historySize);
// return json for the appropriate range
return setJsonResultFromHistory(startIndex, endIndex, pResponse);
}
Error searchHistoryArchive(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get the query
std::string query;
int maxEntries;
Error error = json::readParams(request.params, &query, &maxEntries);
if (error)
return error;
// convert the query into a list of search terms
std::vector<std::string> searchTerms;
boost::char_separator<char> sep;
boost::tokenizer<boost::char_separator<char> > tok(query, sep);
std::copy(tok.begin(), tok.end(), std::back_inserter(searchTerms));
// examine the items in the history for matches
const std::vector<HistoryEntry>& allEntries = historyArchive().entries();
std::vector<HistoryEntry> matchingEntries;
for (std::vector<HistoryEntry>::const_reverse_iterator
it = allEntries.rbegin();
it != allEntries.rend();
++it)
{
// check limit
if (matchingEntries.size() >= static_cast<std::size_t>(maxEntries))
break;
// look for match
if (matches(*it, searchTerms))
{
// add entry
matchingEntries.push_back(*it);
}
}
// return json
json::Object entriesJson;
historyEntriesAsJson(matchingEntries, &entriesJson);
pResponse->setResult(entriesJson);
return Success();
}
Error searchHistoryArchiveByPrefix(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get the query
std::string prefix;
int maxEntries;
bool uniqueOnly;
Error error = json::readParams(request.params,
&prefix, &maxEntries, &uniqueOnly);
if (error)
return error;
// trim the prefix
boost::algorithm::trim(prefix);
// examine the items in the history for matches
const std::vector<HistoryEntry>& allEntries = historyArchive().entries();
std::set<std::string> matchedCommands;
std::vector<HistoryEntry> matchingEntries;
for (std::vector<HistoryEntry>::const_reverse_iterator
it = allEntries.rbegin();
it != allEntries.rend();
++it)
{
// check limit
if (matchingEntries.size() >= static_cast<std::size_t>(maxEntries))
break;
// look for match
if (boost::algorithm::starts_with(it->command, prefix))
{
if (!uniqueOnly || (matchedCommands.count(it->command) == 0))
{
matchingEntries.push_back(*it);
matchedCommands.insert(it->command);
}
}
}
// return json
json::Object entriesJson;
historyEntriesAsJson(matchingEntries, &entriesJson);
pResponse->setResult(entriesJson);
return Success();
}
void onHistoryAdd(const std::string& command)
{
// add command to history archive
Error error = historyArchive().add(command);
if (error)
LOG_ERROR(error);
// fire event
int entryIndex = r::session::consoleHistory().size() - 1;
std::vector<HistoryEntry> entries;
entries.push_back(HistoryEntry(entryIndex, 0, command));
json::Object entriesJson;
historyEntriesAsJson(entries, &entriesJson);
ClientEvent event(client_events::kHistoryEntriesAdded, entriesJson);
module_context::enqueClientEvent(event);
}
SEXP rs_timestamp(SEXP dateSEXP)
{
boost::format fmt("##------ %1% ------##");
std::string ts = boost::str(fmt % r::sexp::safeAsString(dateSEXP));
r::session::consoleHistory().add(ts);
module_context::consoleWriteOutput(ts + "\n");
return R_NilValue;
}
} // anonymous namespace
Error initialize()
{
// migrate .Rhistory if necessary
History::migrateRhistoryIfNecessary();
// connect to console history add event
r::session::consoleHistory().connectOnAdd(onHistoryAdd);
// register timestamp function
R_CallMethodDef methodDef;
methodDef.name = "rs_timestamp" ;
methodDef.fun = (DL_FUNC) rs_timestamp;
methodDef.numArgs = 1;
r::routines::addCallMethod(methodDef);
// install handlers
using boost::bind;
using namespace session::module_context;
ExecBlock initBlock ;
initBlock.addFunctions()
(bind(registerRpcMethod, "get_recent_history", getRecentHistory))
(bind(registerRpcMethod, "get_history_items", getHistoryItems))
(bind(registerRpcMethod, "remove_history_items", removeHistoryItems))
(bind(registerRpcMethod, "clear_history", clearHistory))
(bind(registerRpcMethod, "get_history_archive_items", getHistoryArchiveItems))
(bind(registerRpcMethod, "search_history_archive", searchHistoryArchive))
(bind(registerRpcMethod, "search_history_archive_by_prefix", searchHistoryArchiveByPrefix));
return initBlock.execute();
}
} // namespace history
} // namespace modules
} // namesapce session
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.